0

我正在编写一个程序,它需要活动 A 将数据写入数据库,而活动 B 从数据库中读取数据。我将 SQLiteOpenHelper 类扩展为 DatabaseHelper,并以这种方式在 Activity A 中获取我的数据库:

SQLiteOpenHelper dbHelper = new DatabaseHelper(this, "classtableDatabase", null, 1);
SQLiteDatabase db = dbHelper.getWritableDatabase();

它在 Activity 中运行良好。当我尝试以相同的方式打开由 Activity A 在 Activity B 中创建的数据库时,它失败了,并且我收到以下错误消息:

FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{cn.square2.iscut/cn.square2.iscut.ClassTableDetails}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1891)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1992)
at android.app.ActivityThread.access$600(ActivityThread.java:127)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1158)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4441)
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:823)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:590)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:221)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:157)
at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:231)
at cn.square2.iscut.ClassTableDetails.<init>(ClassTableDetails.java:28)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1319)
at android.app.Instrumentation.newActivity(Instrumentation.java:1023)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1882)
... 11 more

我应该怎么做才能解决这个问题?谢谢您的帮助!

4

1 回答 1

0

我有同样的问题。您不需要做任何事情,只需从您的活动以外的MAIN活动中对数据库进行静态引用。

于 2013-10-24T05:24:58.873 回答