android:尝试将计数器信息添加到sqlite数据库

时间:2013-11-17 20:17:11

标签: java android sqlite

我做了一个计数器应用程序,我想添加一个保存功能,它将计数器的当前数量保存到数据库中。但是当我试图运行它时,它意外关闭。

logcat和代码在

之下
    package com.example.testdatabase;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

int counter;
Button add;
Button sub;
Button save;
TextView display;
private SharedPreferences prefs;
private String prefName = "MyPref";
MySQLiteHelper db = new MySQLiteHelper(this);


public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    counter = 0;
    add = (Button) findViewById(R.id.button1);
    sub = (Button) findViewById(R.id.button2);
    display = (TextView) findViewById(R.id.tvDisplay);
    add.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            counter++;
            display.setText("Counter: " + counter);
        }
    });
    sub.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            counter--;
            display.setText("Counter: " + counter);
        }
    });

    save.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            db.add(counter);

        }
    });
}

protected void onPause()
{
    super.onPause();

    prefs = getSharedPreferences(prefName, MODE_PRIVATE);
    SharedPreferences.Editor edit = prefs.edit();

    edit.putInt("counter", counter);
    edit.commit();

}

protected void onResume()
{
    super.onResume();

    prefs = getSharedPreferences(prefName, MODE_PRIVATE);

    counter = prefs.getInt("counter", counter);
    display.setText("Counter: " + counter);


}


}

处理数据库内容的类

    package com.example.testdatabase;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class MySQLiteHelper extends SQLiteOpenHelper {

// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "CountDB";

public MySQLiteHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);  
}

@Override
public void onCreate(SQLiteDatabase db) {
    // SQL statement to create counter table
    String CREATE_COUNT_TABLE = "CREATE TABLE count ( " +
            "id INTEGER PRIMARY KEY AUTOINCREMENT, " + 
            "amount INT )";

    // create books table
    db.execSQL(CREATE_COUNT_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Drop older counter table if existed
    db.execSQL("DROP TABLE IF EXISTS count");

    // create fresh count table
    this.onCreate(db);
}

// Books table name
private static final String TABLE_COUNTER= "count";

// Books Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_AMOUNT = "amount";


private static final String[] COLUMNS = {KEY_ID,KEY_AMOUNT};

public void add(int counter){

    // 1. get reference to writable DB
    SQLiteDatabase db = this.getWritableDatabase();

    // 2. create ContentValues to add key "column"/value
    ContentValues values = new ContentValues();
    values.put(KEY_AMOUNT, counter); // get counter amount


    // 3. insert
    db.insert(TABLE_COUNTER, // table
            null, //nullColumnHack
            values); // key/value -> keys = column names/ values = column values

    // 4. close
    db.close(); 
}

logcat

    15:08:30.713: D/AndroidRuntime(302): Shutting down VM
11-17 15:08:30.713: W/dalvikvm(302): threadid=1: thread exiting with uncaught exception  (group=0x4001d800)
11-17 15:08:30.742: E/AndroidRuntime(302): FATAL EXCEPTION: main
11-17 15:08:30.742: E/AndroidRuntime(302): java.lang.RuntimeException: Unable to start  activity ComponentInfo{com.example.testdatabase/com.example.testdatabase.MainActivity}: java.lang.NullPointerException
11-17 15:08:30.742: E/AndroidRuntime(302):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
11-17 15:08:30.742: E/AndroidRuntime(302):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
11-17 15:08:30.742: E/AndroidRuntime(302):  at android.app.ActivityThread.access$2300(ActivityThread.java:125)
11-17 15:08:30.742: E/AndroidRuntime(302):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
11-17 15:08:30.742: E/AndroidRuntime(302):  at android.os.Handler.dispatchMessage(Handler.java:99)
11-17 15:08:30.742: E/AndroidRuntime(302):  at android.os.Looper.loop(Looper.java:123)
11-17 15:08:30.742: E/AndroidRuntime(302):  at android.app.ActivityThread.main(ActivityThread.java:4627)
11-17 15:08:30.742: E/AndroidRuntime(302):  at java.lang.reflect.Method.invokeNative(Native Method)
11-17 15:08:30.742: E/AndroidRuntime(302):  at java.lang.reflect.Method.invoke(Method.java:521)
11-17 15:08:30.742: E/AndroidRuntime(302):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
11-17 15:08:30.742: E/AndroidRuntime(302):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
11-17 15:08:30.742: E/AndroidRuntime(302):  at dalvik.system.NativeStart.main(Native Method)
11-17 15:08:30.742: E/AndroidRuntime(302): Caused by: java.lang.NullPointerException
11-17 15:08:30.742: E/AndroidRuntime(302):  at com.example.testdatabase.MainActivity.onCreate(MainActivity.java:49)
11-17 15:08:30.742: E/AndroidRuntime(302):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
11-17 15:08:30.742: E/AndroidRuntime(302):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
11-17 15:08:30.742: E/AndroidRuntime(302):  ... 11 more

任何想法?

1 个答案:

答案 0 :(得分:1)

程序在以下位置抛出异常:

save.setOnClickListener(new View.OnClickListener() ...

似乎Button save未初始化。