如果我清除我的应用程序的数据然后运行它,它工作正常。如果我重新打开或重新运行我的应用程序,它会强制关闭并抛出java.lang.NullPointerException
?错误出现在代码的这一部分
private static class DbHelper extends SQLiteOpenHelper{
public DbHelper(Context context) {
super(context, DB_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + DB_TBL + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_LEVEL + " INTEGER NOT NULL, " +
KEY_HEALTH + " INTEGER NOT NULL, " +
KEY_NAME + " TEXT NOT NULL, " +
KEY_CRIT + " INTEGER NOT NULL, " +
KEY_CRIT_RANGE + " INTEGER NOT NULL, " +
KEY_CRIT_INC + " INTEGER NOT NULL, " +
KEY_HIT_RANGE + " INTEGER NOT NULL, " +
KEY_HIT_INC + " INTEGER NOT NULL, " +
KEY_CHAR_IMG + " INTEGER NOT NULL, " +
KEY_TOTAL_XP + " INTEGER NOT NULL, " +
KEY_XP + " INTEGER NOT NULL, " +
KEY_XP_NEEDED + " INTEGER NOT NULL, " +
KEY_COINS + " INTEGER NOT NULL, " +
KEY_SMALL_POTS + " INTEGER NOT NULL, " +
KEY_LARGE_POTS + " INTEGER NOT NULL)"
);
values = new ContentValues();
values.put(KEY_NAME, "User1");
values.put( KEY_LEVEL, 1);
values.put(KEY_HEALTH, 10);
values.put(KEY_CRIT, 5);
values.put(KEY_CRIT_RANGE, 2);
values.put(KEY_CRIT_INC, 2);
values.put(KEY_HIT_RANGE, 2);
values.put(KEY_HIT_INC, 0);
values.put(KEY_TOTAL_XP, 0);
values.put(KEY_XP, 0);
values.put(KEY_XP_NEEDED, 5);
values.put(KEY_COINS, 5);
values.put(KEY_SMALL_POTS, 0);
values.put(KEY_LARGE_POTS, 0);
values.put(KEY_CHAR_IMG, 1);
db.insert(DB_TBL, null, values);
}
java.lang.NullPointerException
指向此
public int getLevel() {
open();
int level = values.getAsInteger(KEY_LEVEL);
close();
return level;
}
这是我的Stack Trace
01-04 14:45:45.694: W/dalvikvm(20858): threadid=9: thread exiting with uncaught exception (group=0x4001e578)
01-04 14:45:45.694: E/AndroidRuntime(20858): FATAL EXCEPTION: UpdateThread
01-04 14:45:45.694: E/AndroidRuntime(20858): java.lang.NullPointerException
01-04 14:45:45.694: E/AndroidRuntime(20858): at com.tanukiproductions.battleforchristmas.SQLiteTable.getLevel(SQLiteTable.java:110)
01-04 14:45:45.694: E/AndroidRuntime(20858): at com.tanukiproductions.battleforchristmas.Profile.<init>(Profile.java:57)
01-04 14:45:45.694: E/AndroidRuntime(20858): at com.tanukiproductions.battleforchristmas.MainMenuScene.onMenuItemClicked(MainMenuScene.java:37)
这是open()
和close()
public static void open() throws SQLException{
ourDatabase = ourHelper.getWritableDatabase();
}
public static void close() throws SQLException{
ourHelper.close();
}
答案 0 :(得分:1)
由于在您运行应用程序至少一次后创建新的DbHelper对象时未调用onCreate()
,因此values
为空。
如果您想从表中提取此数据,请使用SQLiteDatabase#query()
。
public int getLevel() {
int level = -1;
open();
Cursor cursor = ourDatabase.query(DB_TBL, new String[] {KEY_LEVEL}, null, null, null, null, null);
if(cursor.moveToFirst())
level = cursor.getInt(0); // get the first column from your Select statement, i.e. KEY_LEVEL
cursor.close();
close();
return level;
}
但这仅返回找到的第一个“级别”,使用_id
参数选择特定行。