Android / SQLite:空指针异常?

时间:2014-08-08 00:10:56

标签: android nullpointerexception android-sqlite

我在Android活动中获得了与某种方法相关的NullPointerException

此活动从数据库助手类调用方法。

错误与displayAverageOfAllAttValues()方法有关。

在添加问题方法之前,请务必注意代码与displayAverageOfAllMedLevels()完美配合。

我的代码中有什么错误?

是否与不关闭数据库实例db

有关

活动

public class thirdActivity extends ActionBarActivity {

    TextView count;
    TextView avgMed;
    TextView avgAtt;

    DatabaseHelper db = new DatabaseHelper(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.summary);

        initialiseVars();

        displayAllResults();
    }

    public void initialiseVars(){
        count= (TextView) findViewById(R.id.tvSummary1);
        avgMed= (TextView) findViewById(R.id.tvSummary2);
        avgAtt= (TextView) findViewById(R.id.tvSummary3);
    }

    //Facade method that then calls all the rest
    public void displayAllResults(){
        displayNumberofGamesPlayed();
        displayAverageOfAllMedValues();
        displayAverageOfAllAttValues();
    }

    public void displayNumberofGamesPlayed(){
        //show how many games have been played
        int totalGamesPlayed = db.getTotalGamesPlayed();
        count.setText("games played " + totalGamesPlayed);
    }

    public void displayAverageOfAllMedValues() {
        //Setting cursor to return value of the method?
        int i = db.getTotalOfAllAvgMedLevels();
        avgMed.setText("Total of med" + i );
    }

    public void displayAverageOfAllAttValues() {
        //Setting cursor to return value of the method?
        int i = db.getTotalOfAllAvgAttLevels();
        avgAtt.setText("Total of att" + i );
    }
}
databaseHelper类中的

displayAverageOfAllAttValues()方法:

public int getTotalOfAllAvgAttLevels(){
    SQLiteDatabase db = this.getWritableDatabase();

    String query = "SELECT SUM(avgattention) FROM " + TABLE_SCORE;

    Cursor c = db.rawQuery(query, null);

    c.moveToFirst(); 
    int i=c.getInt(0);

    return i;
}

logcat的

08-08 00:36:45.400: E/AndroidRuntime(10219): FATAL EXCEPTION: main
08-08 00:36:45.400: E/AndroidRuntime(10219): Process: com.example.brianapp, PID: 10219
08-08 00:36:45.400: E/AndroidRuntime(10219): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.brianapp/com.example.brianapp.thirdActivity}: java.lang.NullPointerException
08-08 00:36:45.400: E/AndroidRuntime(10219):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2305)
08-08 00:36:45.400: E/AndroidRuntime(10219):    at android.app.ActivityThread.startActivityNow(ActivityThread.java:2140)
08-08 00:36:45.400: E/AndroidRuntime(10219):    at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:135)
08-08 00:36:45.400: E/AndroidRuntime(10219):    at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:347)
08-08 00:36:45.400: E/AndroidRuntime(10219):    at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:749)
08-08 00:36:45.400: E/AndroidRuntime(10219):    at android.widget.TabHost.setCurrentTab(TabHost.java:413)
08-08 00:36:45.400: E/AndroidRuntime(10219):    at android.widget.TabHost$2.onTabSelectionChanged(TabHost.java:154)
08-08 00:36:45.400: E/AndroidRuntime(10219):    at android.widget.TabWidget$TabClickListener.onClick(TabWidget.java:625)
08-08 00:36:45.400: E/AndroidRuntime(10219):    at android.view.View.performClick(View.java:4633)
08-08 00:36:45.400: E/AndroidRuntime(10219):    at android.view.View$PerformClick.run(View.java:19330)
08-08 00:36:45.400: E/AndroidRuntime(10219):    at android.os.Handler.handleCallback(Handler.java:733)
08-08 00:36:45.400: E/AndroidRuntime(10219):    at android.os.Handler.dispatchMessage(Handler.java:95)
08-08 00:36:45.400: E/AndroidRuntime(10219):    at android.os.Looper.loop(Looper.java:157)
08-08 00:36:45.400: E/AndroidRuntime(10219):    at android.app.ActivityThread.main(ActivityThread.java:5356)
08-08 00:36:45.400: E/AndroidRuntime(10219):    at java.lang.reflect.Method.invokeNative(Native Method)
08-08 00:36:45.400: E/AndroidRuntime(10219):    at java.lang.reflect.Method.invoke(Method.java:515)
08-08 00:36:45.400: E/AndroidRuntime(10219):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
08-08 00:36:45.400: E/AndroidRuntime(10219):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
08-08 00:36:45.400: E/AndroidRuntime(10219):    at dalvik.system.NativeStart.main(Native Method)
08-08 00:36:45.400: E/AndroidRuntime(10219): Caused by: java.lang.NullPointerException
08-08 00:36:45.400: E/AndroidRuntime(10219):    at com.example.brianapp.thirdActivity.displayAverageOfAllAttValues(thirdActivity.java:78)
08-08 00:36:45.400: E/AndroidRuntime(10219):    at com.example.brianapp.thirdActivity.displayAllResults(thirdActivity.java:55)
08-08 00:36:45.400: E/AndroidRuntime(10219):    at com.example.brianapp.thirdActivity.onCreate(thirdActivity.java:34)
08-08 00:36:45.400: E/AndroidRuntime(10219):    at android.app.Activity.performCreate(Activity.java:5426)
08-08 00:36:45.400: E/AndroidRuntime(10219):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
08-08 00:36:45.400: E/AndroidRuntime(10219):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2269)
08-08 00:36:45.400: E/AndroidRuntime(10219):    ... 18 more

数据库助手类中的表结构(供参考):

public class DatabaseHelper extends SQLiteOpenHelper {

    // Database Version
    private static final int DATABASE_VERSION = 10;

    // Database Name
    private final static String DATABASE_NAME = "MeditationDatabase";

    // Contacts table name
    private static final String TABLE_SCORE = "scores";

    // Contacts Table Columns names
    private static final String COL_SESSION = "sessionid";
    private static final String COL_GAMETITLE = "game";
    private static final String COL_NAME = "name";
    private static final String COL_MED = "avgmeditation";
    private static final String COL_MAX = "maxmeditation";
    private static final String COL_AVGATT = "avgattention";
    private static final String COL_MAXATT = "maxattention";
    private static final String COL_SCORE = "score";
    private static final String COL_DATE = "date";

    /**
     * Constructor
     * 
     * @param context
     */
    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    /**
     * Method that creates the database
     */
    @Override
    public void onCreate(SQLiteDatabase db) {
        //VERY IMPORTANT: ALWAYS CHECK THAT THERE ARE SPACES AND COMMAS IN CORRECT PLACE IN CODE BELOW:

        String CREATE_TABLE_SCORE = "CREATE TABLE " + TABLE_SCORE + "(" + COL_SESSION
            + " STRING PRIMARY KEY, " + COL_GAMETITLE + " STRING, "  + COL_NAME + " STRING, " + COL_MED + " INTEGER, "
            + COL_MAX + " INTEGER, " + COL_AVGATT + " INTEGER, " + COL_MAXATT + " INTEGER, "  + COL_SCORE +  " INTEGER, " + COL_DATE + " STRING " + ")";

        db.execSQL(CREATE_TABLE_SCORE);
    }

4 个答案:

答案 0 :(得分:1)

DatabaseHelper db = new DatabaseHelper(this);

是错误的,因为您正在初始化新的DatabaseHelper(上下文),当您的活动尚未创建时,检查我的代码是否无效请告诉我。

DatabaseHelper db;////Correction


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.summary);

    initialiseVars();

    displayAllResults();



}

public void initialiseVars(){

    count= (TextView) findViewById(R.id.tvSummary1);
    avgMed= (TextView) findViewById(R.id.tvSummary2);
    avgAtt= (TextView) findViewById(R.id.tvSummary3);
    db = new DatabaseHelper(this);////Initializing variable.
}

答案 1 :(得分:1)

我找到了解决问题的方法。

这是因为我将内容视图设置为错误的相应XML。

即。在onCreate()中:

setContentView(R.layout.summary);

这是设置为不正确的XML,因此,由于无法在此布局中找到所需的TextView,因此存在空指针异常。

答案 2 :(得分:0)

当moveToFirst()返回boolean时,请尝试使用:

if(c.moveToFirst()){
    return c.getInt(0);
}

有这样的事情:

public int getTotalOfAllAvgAttLevels(){
    SQLiteDatabase db = this.getWritableDatabase();
    String query = "SELECT SUM(avgattention) FROM " + TABLE_SCORE;
    Cursor c = db.rawQuery(query, null);
    if(c.moveToFirst()){
    return c.getInt(0);
}

    return -1; //return whatever you want when c.moveToFirst() condition fails.

    }

答案 3 :(得分:0)

我认为问题出在您创建DatabaseHelper实例时。

执行此操作时:

DatabaseHelper db = new DatabaseHelper(this);

在变量声明中,您违反了Activity生命周期。调用Activity方法时会认为onCreate已创建。因此,请在DatabaseHelper方法上实例化onCreate,并且不要忘记将其置于onDestroy方法上:

public class MyActivity extends Activity {
    private DatabaseHelper db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
        db = new DatabaseHelper(this);
        ...

        initialiseVars();

        displayAllResults();
    }

    @Override
    protected void onDestroy() {
        db.close();
    }
}