我试图在 MainActivity 的 onCreate 期间自动将值插入到 sqlite 数据库中。
这是一些代码:
public static final String KEY_RULEID = "_id";
public static final String KEY_RULE = "rule";
public static final String KEY_TYPE = "type";
public static final String KEY_ENABLED = "enabled";
private static final String rulesc = "??????";
private static final int typesc = 0;
private static final String enabledsc = "TRUE";
private SQLiteDatabase db;
/* insert default rules into the database */
private void insertDefaultRule(String rule, int type, String enabled) {
ContentValues defaultValues = new ContentValues();
defaultValues.put(KEY_RULE, rulesc);
defaultValues.put(KEY_TYPE, typesc);
defaultValues.put(KEY_ENABLED, enabledsc);
System.out.println("line 175");
db.insert(Constants.DATABASES_TABLE_RULES, null, defaultValues);
}
第 175 行被打印到系统日志中,所以我知道 db.insert 行是错误的来源。主要错误是 NullPointerException 但这是另一半,可能会有所帮助。
java.lang.NullPointerException
E/AndroidRuntime(7178): at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:118)
E/AndroidRuntime(7178): at com.prototype.sample.RulesDatabaseAdapter.open(RulesDatabaseAdapter.java:55)
E/AndroidRuntime(7178): at com.prototype.sample.RulesDatabaseAdapter.insertDefualtRules(RulesDatabaseAdapter.java:155)
E/AndroidRuntime(7178): at com.prototype.sample.MessagesList.DefaultRules(MessagesList.java:88)
E/AndroidRuntime(7178): at com.prototype.sample.MessagesList.onCreate(MessagesList.java:53)
E/AndroidRuntime(7178): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
E/AndroidRuntime(7178): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
E/AndroidRuntime(7178): ... 11 more
编辑:添加信息。这个类确实扩展了 SQLiteOpenHelper。
Constants.DATABASES_TABLE_RULES 在 Constants 类中定义如下:
public final static String DATABASES_TABLE_RULES = "rules";
打开数据库的代码:
/* opens the database */
public RulesDatabaseAdapter open() throws SQLException {
db = DBHelper.getWritableDatabase();
return this;
}