当我从Fragment中获取asyntake并访问sqlite时,我遇到了以下错误。
引起:java.lang.NullPointerException 在android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:224)
这是我的编码。我不知道为什么我收到此错误,即使我已经声明“DatabaseUtil dbUtil = new DatabaseUtil(ctx);”
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
.
..
}
public static class ContentFragment extends Fragment {
public ContentFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.list_layout, container, false);
MainActivity myActivity = new MainActivity();
MainActivity.GetDataTask asyncTask = myActivity.new GetDataTask();
return rootView;
}
}
private class GetDataTask extends AsyncTask<Object, Void, Integer> {
protected void onPreExecute() {
}
@Override
protected Integer doInBackground(Object... args) {
DatabaseUtil dbUtil = new DatabaseUtil(ctx);
dbUtil.open();
dbUtil.insertRecord(....);
dbUtil.close();
return 1;
}
@Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
}
}
答案 0 :(得分:1)
你在做什么是错的
MainActivity myActivity = new MainActivity();
您正在创建活动类的实例。活动由startActivtiy(new Intent(params))
开始。活动有ui和生命周期。因此,不需要创建实例od活动类。
建议在你的片段类中有asynctask
另外
DatabaseUtil dbUtil = new DatabaseUtil(getActivtiy());
编辑问题
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
.
..
}
然后在ContentFragment.java
中 public class ContentFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.list_layout, container, false);
new GetDataTask(getActivity()).execute(params);
return rootView;
}
}
class GetDataTask extends AsyncTask<Object, Void, Integer> {
Context mContext;
public GetDataTask(Activity activity) {
// TODO Auto-generated constructor stub
mContext = activity;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Integer doInBackground(Object... args) {
DatabaseUtil dbUtil = new DatabaseUtil(mContext);
dbUtil.open();
dbUtil.insertRecord(....);
dbUtil.close();
return 1;
}
@Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
}
}
答案 1 :(得分:0)
您可以为 GetDataTask ....
制作构造函数Context ctx;
public GetDataTask(Context c){
this.ctx = c;
}
现在您可以使用此 ctx 变量
DatabaseUtil dbUtil = new DatabaseUtil(ctx);