5

我正在将我的应用程序从 Activity 更改为 Fragments,这很好,但是我有一个错误,它不会让我打开我的数据库。这是错误(来自logcat):

05-17 15:28:38.704  13025-13025/com.MJV.werktijden             E/AndroidRuntime: FATAL EXCEPTION: main
    java.lang.NullPointerException
    at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:224)
    at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
    at com.MJV.werktijden.DBAdapter.open(DBAdapter.java:71)
    at com.MJV.werktijden.OverviewFragment.onActivityCreated(OverviewFragment.java:38)
    at android.app.Fragment.performActivityCreated(Fragment.java:1703)
    at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:903)
    at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1057)
    at android.app.BackStackRecord.run(BackStackRecord.java:682)
    at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1435)
    at android.app.FragmentManagerImpl$1.run(FragmentManager.java:441)
    at android.os.Handler.handleCallback(Handler.java:725)
    at android.os.Handler.dispatchMessage(Handler.java:92)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:5041)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
    at dalvik.system.NativeStart.main(Native Method)

我试图自己解决它,但我找不到问题。只是因为当我将它与 Activity 一起使用时,这个数据库确实有效。我用这种方法打开数据库:

    //---opens the database---
public DBAdapter open() throws SQLException
{
    db = DBHelper.getWritableDatabase();
    return this;
}

该方法是从我的片段中调用的:

private final DBAdapter db = new DBAdapter(getActivity());

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.overview_layout, container, false);
    return rootView;
}

public void onActivityCreated (Bundle savedInstanceState){
    listView = (ListView) getView().findViewById(R.id.listView1);
    db.open();

感谢您提前提供帮助。

4

2 回答 2

16

修复

替换此行

private final DBAdapter db = new DBAdapter(getActivity());

有了这个

private DBAdapter db;

onActivityCreated()方法中,添加以下行

db = new DBAdapter(getActivity());

怎么了

在您的行private final DBAdapter db = new DBAdapter(getActivity());Fragment,您在创建活动之前调用getActivity()。因此,当SQLiteOpenHelper尝试使用Context(您的活动)时,它发现它为空。

简单的解决方法是仅在创建之后调用getActivity()(从而打开您的数据库)ActivityonActivityCreated()方法Activity在创建后调用,因此新代码将能够获取您的Activityvia的引用,getActivity()而不会引发任何空异常。

于 2013-05-18T14:34:17.647 回答
0

是否有任何挂起的连接,它通常发生在给定的数据库打开时Context

检查它是否存在任何未关闭的连接Fragment

于 2013-05-17T13:42:49.777 回答