无法提交到SQLite数据库

时间:2017-04-13 14:29:38

标签: android xml

我无法提交到SQLite数据库,因为它不断出现“尝试在空对象引用上调用虚方法”的错误

               Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.sqlite.SQLiteDatabase android.content.Context.openOrCreateDatabase(java.lang.String, int, android.database.sqlite.SQLiteDatabase$CursorFactory, android.database.DatabaseErrorHandler)' on a null object reference

使用定义数据库常量的合约类

    public class TableData {
public static abstract class TableInfo{

    public static final String USER_FIRSTNAME = "firstname";
    public static final String USER_LASTNAME = "lastname";
    public static final String USER_TABLE = "my_table";

}

}

然后我在MyDBHelper类中描述我的数据库

    public class MyDbHelper extends SQLiteOpenHelper{

private static final String DB_NAME = "USERNAMES.DB";
private static final int DB_VERSION = 1;
private static final String CREATE_QUERY = "CREATE TABLE "+TableData.TableInfo.USER_TABLE+" " +
        "("+TableData.TableInfo.USER_FIRSTNAME+" TEXT, "+TableData.TableInfo.USER_LASTNAME+" TEXT)";

public MyDbHelper(Context context) {
    super(context, DB_NAME , null, DB_VERSION);
    Log.e("DB OPERATIONS", "Database Created");
}

@Override
public void onCreate(SQLiteDatabase db) {

    db.execSQL(CREATE_QUERY);
    Log.e("DB OPERATIONS", "Table Created");

}
public void addInfo(String fName, String Lname, SQLiteDatabase db){

    ContentValues contentValues = new ContentValues();
    contentValues.put(TableData.TableInfo.USER_FIRSTNAME, fName);
    contentValues.put(TableData.TableInfo.USER_LASTNAME,Lname);
    db.insert(TableData.TableInfo.USER_TABLE, null, contentValues);

    Log.e("DB OPERATIONS", "Data has been inserted");

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

}

最后初始化MainActivity类的activity_main.xml中的提交按钮的功能

    public class MainActivity extends AppCompatActivity {

EditText fName, lName;
MyDbHelper myDbHelper;
Context context;
SQLiteDatabase sqLiteDatabase;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    fName = (EditText) findViewById(R.id.fname);
    lName = (EditText) findViewById(R.id.lname);

}

public void onClick(View v){
    String firstname = fName.getText().toString();
    String lastname = lName.getText().toString();

    myDbHelper = new MyDbHelper(context);
    sqLiteDatabase = myDbHelper.getWritableDatabase();
    myDbHelper.addInfo(firstname, lastname, sqLiteDatabase);

    Toast.makeText(getBaseContext(), "DATA HAS BEEN INSERTED", Toast.LENGTH_LONG).show();
    myDbHelper.close();
}

}

1 个答案:

答案 0 :(得分:0)

您没有在活动中初始化context,因此您将null上下文传递到MyDbHelper。当你从一个Activity(扩展Context)调用时,请尝试这样做:

myDbHelper = new MyDbHelper(this);