Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8013023
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T19:30:54+00:00 2026-06-04T19:30:54+00:00

I am currently working on an app that runs an AsyncTask in the background

  • 0

I am currently working on an app that runs an AsyncTask in the background and updates the UI with a progressbar. The progress bar works fine when the app is running, however, when the user exits the app and re-enters, the AsyncTask is still running in the background, but the progress bar won’t update. It’s as if the AsyncTask has detached itself from the activity. Does anyone have any ideas what might be causing this such as general rules involved with AsyncTasks. I can provide code if needed, but it is rather lengthy, so just let me know what parts you would need to see. I should also note that the AsyncTask does complete, I can tell this because it uploads a database to the server when it finishes.

Here is the code:

public class BackgroundAsyncTask extends AsyncTask {
int myProgress;

    @Override
    protected void onPostExecute(Void result) {
        ((TextView) findViewById(R.id.tv1)).setText("");
        Cursor cur = sql3.query("videohashes", null, null, null, null,
                null, null);
        cur.moveToFirst();
        while (!cur.isAfterLast()) {

            Cursor curFrame = sql3.query("table_" + cur.getString(2), null,
                    null, null, null, null, null);
            curFrame.moveToFirst();

            ((TextView) findViewById(R.id.tv1)).append("\nPath: "
                    + cur.getString(1) + "\nHash: " + cur.getString(2)
                    + "\nDate:" + cur.getString(3) + "\nSize: "
                    + cur.getString(4) + " bytes\nResolution"
                    + cur.getString(5) + "\nFormat: " + cur.getString(6)
                    + "\nCodec: " + cur.getString(7) + "\nFPS: "
                    + cur.getString(8) + "\n\nFirst Frame Info:\nType: "
                    + curFrame.getString(1) + "\ncp_num: "
                    + curFrame.getString(2) + "\ndp_num: "
                    + curFrame.getString(3) + "\npts: "
                    + curFrame.getString(4) + "\nqstride: "
                    + curFrame.getString(5) + "\nsize: "
                    + curFrame.getString(6) + "\nqp_stddev: "
                    + curFrame.getString(7) + "\ncount: "
                    + curFrame.getString(8) + "\nqp_avg: "
                    + curFrame.getString(9) + "\n\n");

            cur.moveToNext();
        }
        cur.close();
        ((Button) findViewById(R.id.btnSend)).setEnabled(true);
        ((Button) findViewById(R.id.btnStart)).setEnabled(true);
        sql3.close();
        sharedPreferences.edit().putString("lastVideoInfo", ((TextView) findViewById(R.id.tv1)).getText().toString()).commit();
        sharedPreferences.edit().putBoolean("asyncTaskRunning", false).commit();
        dateNow = new Date();
        super.onPostExecute(result);
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        totProgress = 0;
        currVid = 0;
        curProgress = 0;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        progress.setProgress(values[0]);
    }

    @Override
    protected Void doInBackground(Void... arg0) {

        // Calculate total size of all files
        for (String path : myFiles) {
            totProgress += getFileSize(path);
        }

        progress.setMax(totProgress);
        String strDB3File = getFilesDir().getPath() + "/VideoHashes.db3";
        sql3 = SQLiteDatabase.openDatabase(strDB3File, null,
                SQLiteDatabase.CREATE_IF_NECESSARY);

        try {
            String mysql = "CREATE TABLE IF NOT EXISTS videohashes (id INTEGER  NOT NULL PRIMARY KEY AUTOINCREMENT, path TEXT NOT NULL, hash TEXT NOT NULL, date TEXT NOT NULL, size INTEGER, resolution TEXT NOT NULL, codec TEXT NOT NULL, format TEXT NOT NULL, fps TEXT NOT NULL)";
            sql3.execSQL(mysql);
        } catch (SQLiteException e) {
            // TODO: handle exception
        }

        for (String path : myFiles) {
            try {

                String hash = getMD5Checksum(path);

                Cursor curFrame = sql3.query("videohashes",
                        new String[] { "hash" }, "hash=?",
                        new String[] { hash }, null, null, null);

                if (!curFrame.moveToFirst()) {
                    ContentValues myInsertData = new ContentValues();
                    myInsertData.put("path", path);
                    myInsertData.put("hash", hash);
                    Date date = new Date();
                    myInsertData.put("date", dateFormat.format(date));
                    myInsertData.put("size", getFileSize(path));

                    naInit(path);
                    Log.i("VPMA", "After naInit");
                    int[] prVideoRes = naGetVideoResolution();
                    myInsertData.put("resolution", prVideoRes[0] + "x"
                            + prVideoRes[1]);
                    String prVideoCodecName = naGetVideoCodecName();
                    myInsertData.put("codec", prVideoCodecName);
                    String prVideoFormatName = naGetVideoFormatName();
                    myInsertData.put("format", prVideoFormatName);
                    double prFps = naGetVideoFPS();
                    Log.i("VPMA", "fps: " + prFps);
                    myInsertData.put("fps", prFps);
                    Object[] prObjArray = naGetArray();
                    Log.i("VPMA", (String) prObjArray[0]);
                    String[] prStrArray = Arrays.copyOf(prObjArray,
                            prObjArray.length, String[].class);
                    Log.i("VPMA", "before frames");
                    try {
                        String mysql = "CREATE TABLE table_"
                                + hash
                                + " (id INTEGER  NOT  NULL PRIMARY KEY AUTOINCREMENT, type TEXT NOT NULL, cp_num TEXT NOT NULL, dp_num TEXT NOT NULL, pts TEXT NOT NULL, qstride TEXT NOT NULL, size TEXT NOT NULL, qp_stddev TEXT NOT NULL, count TEXT NOT NULL, qp_avg TEXT NOT NULL)";
                        sql3.execSQL(mysql);
                    } catch (SQLiteException e) {
                        // TODO: handle exception
                    }
                    for (String str : prStrArray) {
                        ContentValues myFrameInsertData = new ContentValues();
                        String[] strArr = str.split(",");
                        if (strArr.length == 9) {
                            String stddev = "", strCount = "", strQp_avg = "";
                            double sd, qp_avg, count = 0, sum = 0, sqrSum = 0;
                            try {
                                count = Integer.parseInt(strArr[6].trim());
                                sum = Integer.parseInt(strArr[7].trim());
                                sqrSum = Integer.parseInt(strArr[8].trim());

                                //sd = (sum * sum / count);
                                sd = (sqrSum - (sum*sum/count))/(count-1);//(sqrSum - sd) / (count - 1);
                                stddev = String.valueOf(sd);
                                qp_avg = sum / count;
                                strCount = String.valueOf(count);
                                strQp_avg = String.valueOf(qp_avg);
                            } catch (Exception e) {
                                Log.i("Error: ", "error converting values");
                            }
                            //Log.i("Java Code: ", "Sum: " + sum + " SqrSum: " + sqrSum + " Count: " + count);
                            //Log.i("Java Code: ", "StdDev: " + stddev + " qp_avg: " + strQp_avg);
                            myFrameInsertData.put("type", strArr[0]);
                            myFrameInsertData.put("cp_num", strArr[1]);
                            myFrameInsertData.put("dp_num", strArr[2]);
                            myFrameInsertData.put("pts", strArr[3]);
                            myFrameInsertData.put("qstride", strArr[4]);
                            myFrameInsertData.put("size", strArr[5]);
                            myFrameInsertData.put("qp_stddev", stddev);
                            myFrameInsertData.put("count", strCount);
                            myFrameInsertData.put("qp_avg", strQp_avg);

                            sql3.insert("table_" + hash, null,
                                    myFrameInsertData);
                        }
                    }
                    sql3.insert("videohashes", null, myInsertData);
                    naClose();
                }
                curFrame.close();
                currVid++;
                curProgress += getFileSize(path);
                publishProgress(curProgress);
                Log.i("Progress", "CurrVid:" + currVid + "  Max:"
                        + progress.getMax());
            } catch (Exception e) {
                Log.i("File", "File not Found");
            }
        }
        return null;
    }
}
    }
    if (sharedPreferences.getBoolean("asyncTaskRunning", false) == false)
    {
        ((Button) findViewById(R.id.btnStart)).setEnabled(false);
        progress = (ProgressBar) findViewById(R.id.progressBar1);
        text = (TextView) findViewById(R.id.tv1);
        if (sharedPreferences.contains("lastVideoInfo"))
        {
            text.setText("Last Video Information Parsed " + "(" + dateFormat.format(dateNow) + "):\n\n" +  sharedPreferences.getString("lastVideoInfo", ""));
            ((Button) findViewById(R.id.btnSend)).setEnabled(true);
        }
        else
        {
            text.setText("");
            ((Button) findViewById(R.id.btnSend)).setEnabled(false);
        }
        progress.setProgress(0);

        myFiles = new ArrayList<String>();
        new StartAsyncTask().execute();
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T19:30:57+00:00Added an answer on June 4, 2026 at 7:30 pm

    When the Activity is destroyed, it loses its reference to the AsyncTask, as when the AsyncTask is created it is passed in a reference to the instance of the Activity that creates it. When the instance dies, the reference to the Activity becomes useless.

    A better approach would be put the AsyncTask into a Service, set up the Service and set the AsyncTask running in the Service and bind your Activity to the Service.

    Then when a new instance of the Activity is created (ie when the user re-enters the app), it can bind to the same Service instance that’s already running and pass in a reference to its self to receive progress info.

    Another advantage of this approach is that your Service can put a notification icon in the notification bar, which greatly reduces it chances of being killed by the system, the user could view progress at a glance, and even be notified of when the process is complete.

    Allowing an AsyncTask to be cut loose from its owner (is the Activity) and trusting that it will complete what its doing is a pretty bad idea, and will probably have some unexpected results, lead to potential memory leaks etc.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm currently working on an app that lets the user choose an MP3 audio
I'm currently working on an app that is being created using Ironspeed Designer. It's
I'm currently working on an app that allows the user to draw pixelated images
I am currently working on a simple Silverlight app that will allow people to
I’m currently working on a small web app that allows people to search for
I am currently working on a mobile app that is going to communicate with
I'm currently working on a metro app that requires a few textual resources. Part
I'm currently working on developing a custom keyboard app that will be optimized for
I currently started working on a maven web-app project that needs to be launched
I'm working on an app that relies heavily on P2P, but I currently don't

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.