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

跟風遠走 提交于 2019-12-17 21:28:59

问题


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();
    ...
    }

回答1:


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();


来源:https://stackoverflow.com/questions/28267764/how-to-use-databasehelper-class-in-an-asynctask-class-working-on-a-different-cla

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!