Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
175 views
in Technique[技术] by (71.8m points)

java - How to use databasehelper class in an asynctask class working on a different class

Hi everybody I was stuck at a point, the problem is that I have three classes shown below and I want to instantiate my DatabaseHelper class in AsyncTask class. Could you please help, how can I get context in AsyncTask class?

Problem Solved

  1. MainActivity class

    public class MainActivity extends Activity {
    ...
    FetchData fetchData = new FetchData();
    fetchData.execute();
    ...
    }
    
  2. DatabaseHelper

    public class DatabaseHelper extends SQLiteOpenHelper {
    ....
    public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    ....
    }
    
  3. FetchData class

    public class FetchData extends AsyncTask<String, String, String> {
    ....
    DatabaseHelper db = new DatabaseHelper(); //need context here!!!
    ....
    }
    
#

Thanks to Kasra, I create a fourh class and use it in MainActivity before calling AsyncTask

  1. ContextStatic class

    public class ContextStatic {
    private static Context mContext;
    
    public static Context getmContext() {
        return mContext;
    }
    public static void setmContext(Context mContext) {
        ContextStatic.mContext = mContext;
    }
    }
    

Updated MainActivity class

    public class MainActivity extends Activity {
    ...
    ContextStatic.setmContext(this);
    FetchData fetchData = new FetchData();
    fetchData.execute();
    ...
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try this:

 private class FetchData extends AsyncTask<Context, Void, Void> {
     protected Long doInBackground(Context... c) {
         Context myContext = c[0];
// Do your things here....
     }


     protected void onPostExecute() {
// Insert your post execute code here
     }
 }

You can call this AsyncTask by the following line - assuming you are in an activity:

 new FetchData().execute(this);

if You cannot change your AsyncTask deceleration, then you can try using a static variable - although it is not as efficient and pretty as AsyncTask deceleration. Try this:

Class myStatic{
private  static Context mContext;


static public void setContext(Context c);
mContext = c;
}

static public Context getContext(){
return mContext;
}

}

and in your main code, before you call AsyncTask, call this:

myStatic.setContext(this);

in your doInBackground method of your AsyncTask, add this:

Context myContext = myStatic.getContext();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...