Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use SQLite DB from AsyncTask?

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

like image 620
ZiGi Avatar asked Nov 24 '10 01:11

ZiGi


2 Answers

you need to pass the application context here

this.db = new TheDB(getApplicationContext());
like image 130
Manish Khot Avatar answered Oct 09 '22 12:10

Manish Khot


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(); 
    }
}
like image 22
a0s Avatar answered Oct 09 '22 13:10

a0s