从数据库中检索太游标时出现Nullpointer异常

时间:2012-01-13 13:56:07

标签: android database cursor nullpointerexception sqliteopenhelper

编辑4:我有一个游戏我试图用来保存高分。在主菜单中,用户按下“查看高分”按钮,该按钮调用ViewHighscores活动。从此处,活动会尝试显示所有当前保存的分数。看起来它认为数据库是空的,它从未到达onCreate,但我不知道为什么

package nick.android.com;

import java.util.ArrayList;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;

public class ViewHighscores extends ListActivity {

/** Called when the activity is first created. */

private ArrayAdapter<String> myHighscoreAdapter;
private ArrayList<String> myHighscoreMessage = new ArrayList<String>();
ArrayList<Object> data = new ArrayList<Object>();

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.viewhighscores);

    myHighscoreAdapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, myHighscoreMessage);

    setListAdapter(myHighscoreAdapter);

    retrieveHighscores();

}

public void retrieveHighscores() {

    DatabaseOpenHelper database = new DatabaseOpenHelper(this);

    Cursor cursor = database.getHighscore();

    if (cursor != null && cursor.getCount() > 0) {

        cursor.moveToFirst();

        while (cursor.isAfterLast() == false) {

            data.add(cursor.getString(0));
            data.add(cursor.getString(1));

            displayHighscores();

            cursor.moveToNext();
        }
    } else {
        myHighscoreAdapter.add("No Highscores Recorded Yet");
    }

}

public void displayHighscores() {

    myHighscoreAdapter.add("Highscore: " + data);

}

public void returnToMenu(View view) {

    finish();
    Intent returnToMenuButton = new Intent(view.getContext(),
            MainMenu.class);
    startActivity(returnToMenuButton);
}

}

以下是来自游戏本身的一段代码,它也尝试编写数据库。 getUserName();从editText检索userName,numberOfGuesses是1到12之间的数字

public void saveHighscore() {

    scoreSaved = true;

    getUserName();

    DatabaseOpenHelper database = new DatabaseOpenHelper(this);

    database.addHighscore(userName, numberOfGuesses);

}

这是DatabaseOpenHelper类

package nick.android.com;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.Cursor;
import android.util.Log;

public class DatabaseOpenHelper extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 2;
private static final String DATABASE_NAME = "HIGHSCORE_DATABASE";
private static final String HIGHSCORE_TABLE = "highscore";
static final String col_HighscoreID = "_id";
static final String col_HighscoreUser = "highscoreuser";
static final String col_Highscore = "highscore";
private SQLiteDatabase db;

DatabaseOpenHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);

}

public void onCreate(SQLiteDatabase db) {

    db.execSQL("CREATE TABLE " + HIGHSCORE_TABLE + " (" + col_HighscoreID
            + " INTEGER PRIMARY KEY AUTOINCREMENT, " + col_HighscoreUser
            + " TEXT , " + col_Highscore + " INTEGER)");

    System.out.println("ITS GETTING HERE");

    inputComputerHighscores();

}

public void inputComputerHighscores() {

    ContentValues value = new ContentValues();
    SQLiteDatabase db = this.getWritableDatabase();

    try {

        value.put(col_HighscoreUser, "Gold");
        value.put(col_Highscore, "3");
        db.insert(HIGHSCORE_TABLE, null, value);

        long dbcheck = db.insert(HIGHSCORE_TABLE, null, value);
        System.out.println(dbcheck);

        value.put(col_HighscoreUser, "Silver");
        value.put(col_Highscore, "6");
        db.insert(HIGHSCORE_TABLE, null, value);

        value.put(col_HighscoreUser, "Bronze");
        value.put(col_Highscore, "9");
        db.insert(HIGHSCORE_TABLE, null, value);

    } catch (Exception e) {

        Log.e("DB Error", e.toString());
        e.printStackTrace();

    }

    db.close();

}

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

}

public Cursor getHighscore() {

    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = null;

    try {

        cursor = db.query(HIGHSCORE_TABLE, new String[] { col_HighscoreID,
                col_HighscoreUser, col_Highscore }, null, null, null, null,
                col_Highscore + " asc");

    } catch (Exception e) {

        Log.e("DB Retrieval Error", e.toString());
        e.printStackTrace();

    }

    db.close();

    return cursor;

}


public void addHighscore(String Username, int Score) {

    ContentValues value = new ContentValues();

    value.put(col_HighscoreUser, Username);
    value.put(col_Highscore, Score);

    SQLiteDatabase db = this.getWritableDatabase();

    try {

        db.insert(HIGHSCORE_TABLE, null, value);

    } catch (Exception e) {

        Log.e("DB Error", e.toString());
        e.printStackTrace();

    }

}

}

如果我打开ViewHighscores活动&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;改编编辑5 - 现在再次强制关闭:

01-13 16:06:17.032: D/AndroidRuntime(444): Shutting down VM
01-13 16:06:17.032: W/dalvikvm(444): threadid=1: thread exiting with uncaught exception (group=0x40015560)
01-13 16:06:17.042: E/AndroidRuntime(444): FATAL EXCEPTION: main
01-13 16:06:17.042: E/AndroidRuntime(444): java.lang.RuntimeException: Unable to start activity ComponentInfo{nick.android.com/nick.android.com.ViewHighscores}: java.lang.IllegalStateException: getWritableDatabase called recursively
01-13 16:06:17.042: E/AndroidRuntime(444):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
01-13 16:06:17.042: E/AndroidRuntime(444):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
01-13 16:06:17.042: E/AndroidRuntime(444):  at android.app.ActivityThread.access$1500(ActivityThread.java:117)
01-13 16:06:17.042: E/AndroidRuntime(444):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
01-13 16:06:17.042: E/AndroidRuntime(444):  at android.os.Handler.dispatchMessage(Handler.java:99)
01-13 16:06:17.042: E/AndroidRuntime(444):  at android.os.Looper.loop(Looper.java:123)
01-13 16:06:17.042: E/AndroidRuntime(444):  at android.app.ActivityThread.main(ActivityThread.java:3683)
01-13 16:06:17.042: E/AndroidRuntime(444):  at java.lang.reflect.Method.invokeNative(Native Method)
01-13 16:06:17.042: E/AndroidRuntime(444):  at java.lang.reflect.Method.invoke(Method.java:507)
01-13 16:06:17.042: E/AndroidRuntime(444):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
01-13 16:06:17.042: E/AndroidRuntime(444):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
01-13 16:06:17.042: E/AndroidRuntime(444):  at dalvik.system.NativeStart.main(Native Method)
01-13 16:06:17.042: E/AndroidRuntime(444): Caused by: java.lang.IllegalStateException: getWritableDatabase called recursively
01-13 16:06:17.042: E/AndroidRuntime(444):  at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:101)
01-13 16:06:17.042: E/AndroidRuntime(444):  at nick.android.com.DatabaseOpenHelper.inputComputerHighscores(DatabaseOpenHelper.java:40)
01-13 16:06:17.042: E/AndroidRuntime(444):  at nick.android.com.DatabaseOpenHelper.onCreate(DatabaseOpenHelper.java:33)
01-13 16:06:17.042: E/AndroidRuntime(444):  at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:126)
01-13 16:06:17.042: E/AndroidRuntime(444):  at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:187)
01-13 16:06:17.042: E/AndroidRuntime(444):  at nick.android.com.DatabaseOpenHelper.getHighscore(DatabaseOpenHelper.java:78)
01-13 16:06:17.042: E/AndroidRuntime(444):  at nick.android.com.ViewHighscores.retrieveHighscores(ViewHighscores.java:39)
01-13 16:06:17.042: E/AndroidRuntime(444):  at nick.android.com.ViewHighscores.onCreate(ViewHighscores.java:31)
01-13 16:06:17.042: E/AndroidRuntime(444):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-13 16:06:17.042: E/AndroidRuntime(444):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
01-13 16:06:17.042: E/AndroidRuntime(444):  ... 11 more

1 个答案:

答案 0 :(得分:0)

改变这个:

if (!(cursor == null)) {

    cursor.moveToFirst();

    if (!cursor.isAfterLast()) {

这样的事情和一段时间:

if (cursor != null && cursor.getCount() > 0) {

    cursor.moveToFirst();

while (cursor.isAfterLast() == false){

//Do what you want


 cursor.moveToNext();
}

但根据你的上一次编辑,这可能还不够,因为也许你没有保存任何东西。