2

我遇到了无法在 Fragment 中加载 sqlite 数据的问题,如下所示

public class ListFragment extends Fragment {

    DatabaseUtil dbUtil = new DatabaseUtil(this.getActivity());
    private ArrayList <HashMap<String, Object>> getNews;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View v = inflater.inflate(R.layout.activity_list, container, false);


        new LoadNewsLists().execute("");        

        return v;
    }

这是从 sqlite 加载数据

Cursor cursor = dbUtil.fetchAllData(arg[0]);

遇到以下错误。

03-08 12:21:52.900: E/AndroidRuntime(25895): Caused by: java.lang.NullPointerException
03-08 12:21:52.900: E/AndroidRuntime(25895):    at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:224)
4

2 回答 2

3

您不能在定义它的同时初始化您的 db 对象。您应该将初始化代码移动到onCreateView()回调:

DatabaseUtil dbUtil ;
private ArrayList <HashMap<String, Object>> getNews;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    final View v = inflater.inflate(R.layout.activity_list, container, false);

    dbUtil = new DatabaseUtil(getActivity());
    new LoadNewsLists().execute("");        

    return v;
}
于 2013-03-08T06:44:57.337 回答
1

我不确定构造函数内部发生了什么,但是在到达回调DatabaseUtil(this.getActivity())之前,您不应该依赖 Activity 被完全初始化。Fragment.onActivityCreated()

于 2013-03-08T07:01:20.757 回答