如何在处理不同类的asynctask类中使用databasehelper类

时间:2015-02-01 20:55:43

标签: java android database android-asynctask android-sqlite

大家好,我被困在某一点,问题是我有三个类如下所示,我想在AsyncTask类中实例化我的DatabaseHelper类。你能帮忙吗,我怎样才能在AsyncTask课程中获得上下文?

解决了问题

  1. MainActivity类

    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类

    public class FetchData extends AsyncTask<String, String, String> {
    ....
    DatabaseHelper db = new DatabaseHelper(); //need context here!!!
    ....
    }
    
  4. 感谢Kasra,我创建了一个4h类并在调用AsyncTask之前在MainActivity中使用它

    1. ContextStatic类

      public class ContextStatic {
      private static Context mContext;
      
      public static Context getmContext() {
          return mContext;
      }
      public static void setmContext(Context mContext) {
          ContextStatic.mContext = mContext;
      }
      }
      
    2. 更新了MainActivity类

          public class MainActivity extends Activity {
          ...
          ContextStatic.setmContext(this);
          FetchData fetchData = new FetchData();
          fetchData.execute();
          ...
          }
      

1 个答案:

答案 0 :(得分:1)

试试这个:

 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
     }
 }

您可以通过以下行调用此AsyncTask - 假设您处于活动中:

 new FetchData().execute(this);

如果您无法更改AsyncTask减速度,那么您可以尝试使用静态变量 - 尽管它不如AsyncTask减速那样高效和漂亮。试试这个:

Class myStatic{
private  static Context mContext;


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

static public Context getContext(){
return mContext;
}

}

在主代码中,在调用AsyncTask之前,请调用:

myStatic.setContext(this);

在AsyncTask的doInBackground方法中,添加:

Context myContext = myStatic.getContext();