从应用程序创建 SQLite 数据库时出现空指针异常 [重复]

Posted

技术标签:

【中文标题】从应用程序创建 SQLite 数据库时出现空指针异常 [重复]【英文标题】:Null Pointer Exception when creating SQLite Database from App [duplicate] 【发布时间】:2017-06-07 06:08:25 【问题描述】:

我正在尝试制作一个简单的应用程序,该应用程序可以获取用户输入的信息并将其存储在 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 ComponentInfocom.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 助手有问题吗? (意思是应该用别的东西初始化?)

【问题讨论】:

【参考方案1】:

您使用的是局部变量 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);

【讨论】:

有效,现在出现其他错误... @bdpolinsky 很高兴我能帮上忙,祝编码愉快:)【参考方案2】:

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

【讨论】:

以上是关于从应用程序创建 SQLite 数据库时出现空指针异常 [重复]的主要内容,如果未能解决你的问题,请参考以下文章

从firebase检索时出现空指针异常[重复]

有时在调用时与对手创建 QBRTCSession 时出现空指针异常

尝试使用 pyspark 从 S3 获取数据时出现空指针异常

访问片段的子视图时出现空指针异常

使用TestNG运行代码时出现空指针异常

从活动调用片段方法时出现空指针异常