Android 写入数据库时​​应用崩溃

Android app crashes when write Database

我想将一些数据写入 SQLite 数据库。 在我的应用程序中,我有一个主单例 class,代码为:

public class Singleton extends Application {

    public static DBHelper dbHelper;
    public static SQLiteDatabase db;

    @Override
    public void onCreate() {
        super.onCreate();
        dbHelper = new DBHelper(this);
        db = dbHelper.getWritableDatabase();

    }
}

DBHelper.java:

public class DBHelper extends SQLiteOpenHelper {

    public DBHelper(Context context) {
        super(context, "myDB", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE AlarmListTable ("
            + "id integer primary key autoincrement, "
            + "time text, "
            + "date text, "
            + "comment text "
            + ");");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}

我有一个 activity,其中我有一个方法:

ContentValues cv = new ContentValues();
cv.put("time", entTime.getText().toString());
cv.put("date", entTime.getText().toString());
cv.put("comment", entTime.getText().toString());
Singleton.db.insert("AlarmListTable", null, cv);

但是应用程序崩溃了。 请帮帮我。有什么问题吗?

logcat:

FATAL EXCEPTION: main
java.lang.NullPointerException at Singleton.db.insert("AlarmListTable", null, cv);

主要问题可能是因为您忘记删除字符串末尾的逗号。在每个逗号后添加一个 space。

   db.execSQL("CREATE TABLE AlarmListTable ("
                + "id integer primary key autoincrement, "
                + "time text, "
                + "date text, "
                + "comment text "
                + ");");

您必须添加更多关于实际错误的详细信息,才能确定问题出在哪里。

看起来 Singleton.db 为空。

您确定正在调用 Singleton 中的 onCreate() 吗?对于 Application 子类,您需要在 AndroidManifest.xml 文件的 android:name 属性中添加子类的名称。