getWritableDatabase()导致nullPointerException

时间:2018-12-07 04:31:51

标签: java android android-studio nullpointerexception android-sqlite

我想用SQLite打开数据库。但是,当尝试从TextInputEditText中获取数据并将其放入数据库时​​,它将在db = this.getWritableDatabase();

处抛出NPE。

似乎大多数情况下,这是由context为空引起的。但这不是null,我使用调试器进行了检查。 (myDB = new DatabaseHelper(this);

(我已经尝试过所有其他有关此问题的问题,但我的情况必须有所不同,因为它们没有帮助。)

MainActivity.java

public class MainActivity extends AppCompatActivity {
    DatabaseHelper myDB;
    TextInputEditText inputEmail;
    TextInputEditText inputPass;
    Button btn_login;
    Button btn_signup;

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

        try {
            myDB = new DatabaseHelper(this);
        } catch (Exception e) {
            System.out.print("Exception occurred");
        }
        btn_signup = findViewById(R.id.btn_signup);
        btn_login = findViewById(R.id.btn_login);
        addData();
    }

    public void addData() {
        btn_signup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                inputEmail = findViewById(R.id.editTextEmail);
                inputPass = findViewById(R.id.editTextPass);
                //try {
                myDB.insertData(inputEmail.getText().toString(), 
                inputPass.getText().toString());

                Toast.makeText(MainActivity.this, "Data Inserted", 
                Toast.LENGTH_LONG).show();

               // } catch (Exception e) {
               //     e.printStackTrace();
               // }
            }
        });
    }

DatabaseHelper.java

public class DatabaseHelper extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "Login_android.db";
    public static final String TABLE_NAME = "login_table.db";
    public static final String COL1 = "ID";
    public static final String COL2 = "EMAIL";
    public static final String COL3 = "PASSWORD";


    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);
        //SQLiteDatabase db = this.getWritableDatabase();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE " + TABLE_NAME +" (ID INTEGER PRIMARY KEY 
        AUTOINCREMENT, EMAIL TEXT, PASSWORD TEXT)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);
    }

    public boolean insertData(String email, String password) {

        SQLiteDatabase db = null;
        try {
            db = this.getWritableDatabase();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //db.isOpen();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL2, email);
        contentValues.put(COL3, password);
        long result = db.insert(TABLE_NAME, null, contentValues);
        if (result == -1) {
            return false;
        } else {
            return true;
        }
    }
}

例外

  

12-06 23:39:12.799 26304-26304 / com.example.ryan.temporaryname E / AndroidRuntime:FATAL EXCEPTION:main       流程:com.example.ryan.temporaryname,PID:26304       java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'long android.database.sqlite.SQLiteDatabase.insert(java.lang.String,java.lang.String,android.content.ContentValues)'           在com.example.ryan.temporaryname.DatabaseHelper.insertData(DatabaseHelper.java:45)           在com.example.ryan.temporaryname.MainActivity $ 1.onClick(MainActivity.java:64)           在android.view.View.performClick(View.java:6294)           在android.view.View $ PerformClick.run(View.java:24770)           在android.os.Handler.handleCallback(Handler.java:790)           在android.os.Handler.dispatchMessage(Handler.java:99)           在android.os.Looper.loop(Looper.java:164)           在android.app.ActivityThread.main(ActivityThread.java:6494)           在java.lang.reflect.Method.invoke(本机方法)           在com.android.internal.os.RuntimeInit $ MethodAndArgsCaller.run(RuntimeInit.java:438)           在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

2 个答案:

答案 0 :(得分:0)

我认为您应该(如果这不是一个测试用的sqlite应用程序)通过创建App()类并在其中初始化数据库来创建单例。也尝试找出问题所在

答案 1 :(得分:0)

我认为问题出在TABLE_NAME上-“ login_table.db”建议在名为“ login_table”的数据库中存在一个名为“ db”的表,该表不存在,并且返回空数据库对象。

请尝试更改名称。