尝试插入SQLite时的NullPointerException - Android

时间:2013-01-03 17:20:03

标签: java android sqlite nullpointerexception insertion

任何关注Android代码的人都可能对我很熟悉。我正在努力为我的高分数量实现SQLite数据库。这也是我第一次使用SQLite。

我试图只插入两个变量 - int和long。我的insert()方法无法正常工作。除了上面谈到的内容之外的任何建议也表示赞赏。

提前感谢您的帮助。

Highscores.java

public class Highscores extends Activity {

    DatabaseHelper dh;
    SQLiteDatabase db;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.highscoresmain);

        dh = new DatabaseHelper(this);
        dh.openDB(db);
        long x = 11;
        int y = 22;

        TextView rank = (TextView)findViewById(R.id.rank);
        TextView percentage = (TextView)findViewById(R.id.percentage);
        TextView score = (TextView)findViewById(R.id.score);

        TextView r1r = (TextView)findViewById(R.id.r1r);
        TextView r1p = (TextView)findViewById(R.id.r1p);
        TextView r1s = (TextView)findViewById(R.id.r1s);

        dh.insert(x, y, db);  //Line 55
        scores = dh.getScore(db);
        percentages = dh.getPercentage(db);

        rank.setText("Rank Column - TEST");
        percentage.setText("Percentage Column - TEST ");
        score.setText("Score Column - Test");
        r1r.setText("test..rank");
        r1p.setText("" + percentages);
        r1s.setText("test..score");

        table = (TableLayout)findViewById(R.id.tableLayout);

        dh.closeDB(db);
    }
}

DatabaseHelper.java

public class DatabaseHelper extends SQLiteOpenHelper { 

    SQLiteDatabase db;

    // Table columns names. 
    private static final String RANK = "_id"; 
    private static final String SCORE = "score"; 
    private static final String PERCENTAGE = "percentage";

    public DatabaseHelper(Context context) { 
        super(context, DB_NAME, null, DATABASE_VERSION); 
    }

    public SQLiteDatabase openDB(SQLiteDatabase db) {
        db = this.getWritableDatabase();
        return db;
    }

    public int getPercentage(SQLiteDatabase db) {
        //Cursor c = db.rawQuery("SELECT " + PERCENTAGE + " FROM " + TABLE + " WHERE " + PERCENTAGE + " = " + 22 + ";", null);
        Cursor c = db.rawQuery("SELECT " + PERCENTAGE + " FROM " + TABLE + ";", null);
        int i = 0;
        if(c.getCount() == 0) {
            i = 333;
        } else if (c.getCount() == 1) {
            i = 444;
        } else {
            i = 888;
               /*c.moveToFirst();
               int columnIndex = c.getInt(c.getColumnIndex("PERCENTAGE"));
               if(columnIndex != -1) {
                   i = c.getInt(columnIndex);
               } else { 
                   i = 999; 
               }*/
        }
        c.close();
        return i;
   }

    //Insert new record.
    public long insert(long score, int percentage, SQLiteDatabase db) {
        ContentValues values = new ContentValues();
        values.put(SCORE, score);
        values.put(PERCENTAGE, percentage);

        return db.insert(TABLE, null, values);  //Line 120
    }

    public synchronized void closeDB(SQLiteDatabase db) {
        if(db != null) {
            db.close();
        }
        super.close();
    }

    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE " + TABLE + " ("
                + RANK + " INTEGER PRIMARY KEY AUTOINCREMENT,"
                + SCORE + " LONG,"
                + PERCENTAGE + " INTEGER"
                + ");");
}

LogCat输出

01-03 17:09:18.232: E/AndroidRuntime(1712): FATAL EXCEPTION: main
01-03 17:09:18.232: E/AndroidRuntime(1712): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.test/com.example.test.Highscores}: java.lang.NullPointerException
01-03 17:09:18.232: E/AndroidRuntime(1712):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
01-03 17:09:18.232: E/AndroidRuntime(1712):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
01-03 17:09:18.232: E/AndroidRuntime(1712):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
01-03 17:09:18.232: E/AndroidRuntime(1712):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
01-03 17:09:18.232: E/AndroidRuntime(1712):     at android.os.Handler.dispatchMessage(Handler.java:99)
01-03 17:09:18.232: E/AndroidRuntime(1712):     at android.os.Looper.loop(Looper.java:137)
01-03 17:09:18.232: E/AndroidRuntime(1712):     at android.app.ActivityThread.main(ActivityThread.java:5039)
01-03 17:09:18.232: E/AndroidRuntime(1712):     at java.lang.reflect.Method.invokeNative(Native Method)
01-03 17:09:18.232: E/AndroidRuntime(1712):     at java.lang.reflect.Method.invoke(Method.java:511)
01-03 17:09:18.232: E/AndroidRuntime(1712):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
01-03 17:09:18.232: E/AndroidRuntime(1712):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
01-03 17:09:18.232: E/AndroidRuntime(1712):     at dalvik.system.NativeStart.main(Native Method)
01-03 17:09:18.232: E/AndroidRuntime(1712): Caused by: java.lang.NullPointerException
01-03 17:09:18.232: E/AndroidRuntime(1712):     at com.example.test.DatabaseHelper.insert(DatabaseHelper.java:120)
01-03 17:09:18.232: E/AndroidRuntime(1712):     at com.example.test.Highscores.onCreate(Highscores.java:55)
01-03 17:09:18.232: E/AndroidRuntime(1712):     at android.app.Activity.performCreate(Activity.java:5104)
01-03 17:09:18.232: E/AndroidRuntime(1712):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
01-03 17:09:18.232: E/AndroidRuntime(1712):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
01-03 17:09:18.232: E/AndroidRuntime(1712):     ... 11 more

2 个答案:

答案 0 :(得分:4)

在此行中,您打开数据库:

dh.openDB(db);

这将数据库的成员变量存储在DatabaseHelper.db中(但在其他地方,尤其不在Highscores.db中)。然后,你打电话:

dh.insert(x, y, db);

使用null中的db Highscores个对象。最后,在insert()内,您可以使用此null db对象:

return db.insert(TABLE, null, values);

您应该做的是使用以下insert()方法:

public long insert(long score, int percentage) { // Remove db parameter
    ContentValues values = new ContentValues();
    values.put(SCORE, score);
    values.put(PERCENTAGE, percentage);

    return db.insert(TABLE, null, values); // This will use the member variable
}

然后,请改为呼叫dh.insert(x, y);

您还应该将openDB(SQLiteDatabase db)更改为openDB(),以便正在编写正确的数据库;就目前而言,它只是覆盖局部变量的值(一旦完成函数的范围,它就不会改变)。

答案 1 :(得分:1)

而不是

dh.openDB(db);

db = dh.openDB(db);

(尽管openDB方法确实不需要参数)。您对openDB的调用并未将数据库对象引用存储在db中,因此当您调用dh.insert(..., db);时它将为NULL。