Question

I've been using my Activity class to access my DB which made my program freeze sometimes.

So I decided to use AsyncTask instead to handle the DB.

My problem is I don't know how to instantiate my SQLite DB "TheDB" from AsyncTask's class

public class myClass extends AsyncTask<Void, Void, Void>{
private TheDB db;

any method() {
    this.db = new TheDB(this);  //<-- Error here
}

this worked fine on the Activity class, but it I dont know how to use it here

TheDB's constructor is TheDB(Context context) but this class is not a "context" so how can i use my DB here?

please provide examples if you can

and please do not give me links to google's references, am a newbie and i find them hard to follow

Was it helpful?

Solution

you need to pass the application context here

this.db = new TheDB(getApplicationContext());

OTHER TIPS

import android.content.Context;

public class SuperTask extends AsyncTask<Void, Void, Void> {
    private final Context mContext; 

    public SuperTask(Context context) {
        super();
        this.mContext = context
    }

    protected Void doInBackground(Void... params) {
        // using this.mContext
    }
}

public class MainActivity extends Activity {
    // and run from Activity
    public void onButtonClick(View view) {
        new SuperTask(this.getApplicationContext()).execute(); 
    }
}

There are two ways that i see:

  1. Pass a context object to your AsyncTask constructor, then instantiate database like this this.db = new TheDB(context);

  2. Or you probably can pass the actual database object to the constructor, but the first approach seems better.

An important part of learning to program is learning to read and understand documentation. As documentation goes, the Android docs are pretty detailed, so its really worth your time to understand how they work.

As you can see in the AsyncTask docs, there is no onCreate or onExecute method in an AsyncTask.

The docs clearly walk you through the 4 main functions of an AsyncTask, onPreExecute(), doInBackground(Params...), onProgressUpdate(Progress...), onPostExecute(Result).

The likely choices for your instance are onPreExecute() or doInBackground(Params...). The difference is whether or not you want the initializition to occur on the UI thread. If you don't, then do it in doInBackground(Params...).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top