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

前端 未结 1 637
独厮守ぢ
独厮守ぢ 2020-12-11 12:42

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 ple

相关标签:
1条回答
  • 2020-12-11 13:32

    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();
    
    0 讨论(0)
提交回复
热议问题