从App创建SQLite数据库时出现空指针异常

时间:2017-01-22 18:06:52

标签: android sqlite nullpointerexception

我正在尝试创建一个简单的应用程序,可以将用户输入的信息存储在Android手机的数据库中。我的代码如下:

import android.database.sqlite.SQLiteOpenHelper;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import java.io.IOException;


public class MainActivity extends AppCompatActivity {

    EditText userentry;
    TextView seeuserdata;
    DataBaseHelper DataBaseHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        userentry = (EditText) findViewById(R.id.userentry);
        seeuserdata = (TextView) findViewById(R.id.seeUserData);
        DataBaseHelper db = new DataBaseHelper(this, null, null, 1);
        printDatabase();
    }

    public void addButtonClicked(View view){
        Products product = new Products(userentry.getText().toString());


    }

    public void deleteButtonClicked(View view){
            String inputText = userentry.getText().toString();
            DataBaseHelper.deleteProduct(inputText);
            printDatabase();
    }

    public void printDatabase(){
        String dbString = DataBaseHelper.databaseToString();
        seeuserdata.setText(dbString);
        userentry.setText("");
    }
};

产品类

    public class Products {
    private int _id;
    private String _productname;

    public Products(String _productname){
        this._productname=_productname;
    }

    public void set_id(int _id) {
        this._id = _id;
    }

    public void set_productname(String _productname) {
        this._productname = _productname;
    }

    public int get_id() {
        return _id;
    }

    public String get_productname() {
        return _productname;
    }
}

和类DataBaseHelper

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

public class DataBaseHelper extends SQLiteOpenHelper {

    private static String DB_PATH = "/data/data/your.package/databases/";
    private static String DB_NAME = "products.db";
    private static int DB_VERSION = 1;
    private static final String TABLE_PRODUCTS = "products";
    public static final String COLUMN_ID = "_id";
    public static final String COLUMN_PRODUCTNAME = "productname";
    private static short WRITE_BUFFER_SIZE = 8192;
    private Context context;

    public DataBaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    public void addProduct(Products product){
        ContentValues values = new ContentValues();
        values.put(COLUMN_PRODUCTNAME, product.get_productname());
        SQLiteDatabase db = getWritableDatabase();
        db.insert(TABLE_PRODUCTS, null, values);
        db.close();
    }

    public void deleteProduct(String productName){
        SQLiteDatabase db = getWritableDatabase();
        db.execSQL("DELETE FROM " + TABLE_PRODUCTS + " WHERE " + COLUMN_PRODUCTNAME + "=\"" + productName + "\";");
    }

    public String databaseToString(){
        String dbString = "";
        SQLiteDatabase db  = getWritableDatabase();
        String query = "SELECT * FROM " + TABLE_PRODUCTS + " WHERE 1";
        Cursor c = db.rawQuery(query, null);
        c.moveToFirst();
        while(!c.isAfterLast()){
            if(c.getString(c.getColumnIndex("productname"))!=null){
                dbString += c.getString(c.getColumnIndex("productname"));
                dbString += "\n";
            }
        }
        db.close();
        return dbString;
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP_TABLE_IF_EXISTS" + TABLE_PRODUCTS);
        onCreate(db);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        String query = "CREATE TABLE" + TABLE_PRODUCTS + "(" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT "+ COLUMN_PRODUCTNAME + " TEXT " + ");";
        db.execSQL(query);
    }
}

错误是:

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.barry.recordtracker, PID: 11938
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.barry.recordtracker/com.example.barry.recordtracker.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.barry.recordtracker.DataBaseHelper.databaseToString()' on a null object reference
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3253)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3349)
                      at android.app.ActivityThread.access$1100(ActivityThread.java:221)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:158)
                      at android.app.ActivityThread.main(ActivityThread.java:7224)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
                   Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.barry.recordtracker.DataBaseHelper.databaseToString()' on a null object reference
                      at com.example.barry.recordtracker.MainActivity.printDatabase(MainActivity.java:40)
                      at com.example.barry.recordtracker.MainActivity.onCreate(MainActivity.java:26)
                      at android.app.Activity.performCreate(Activity.java:6876)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1135)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3206)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3349) 
                      at android.app.ActivityThread.access$1100(ActivityThread.java:221) 
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794) 
                      at android.os.Handler.dispatchMessage(Handler.java:102) 
                      at android.os.Looper.loop(Looper.java:158) 
                      at android.app.ActivityThread.main(ActivityThread.java:7224) 
                      at java.lang.reflect.Method.invoke(Native Method) 
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) 
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) 

我的理解是日志引用的空对象是在onCreate方法中初始化的数据库帮助器。在我看来,数据库助手已创建!它不是指向数据库助手吗?我用(this,null,null,1)初始化DB帮助器是一个问题吗? (意思是它应该用别的东西初始化?)

2 个答案:

答案 0 :(得分:2)

您使用的是本地变量db而不是DataBaseHelper引用变量,因此您需要初始化DataBaseHelper引用

onCreate

中替换它
DataBaseHelper db = new DataBaseHelper(this, null, null, 1);

用这个

DataBaseHelper = new DataBaseHelper(this, null, null, 1);

或为清楚起见,重命名 DataBaseHelper DataBaseHelper;

到此DataBaseHelper dataBaseHelper;并像这样使用

dataBaseHelper = new DataBaseHelper(this, null, null, 1);

答案 1 :(得分:0)

AddbuttonClicked方法不向数据库添加条目。 调用databasehelper的addProduct方法。