我是Android开发新手,在尝试获取可写数据库时遇到NullPointerException。这是代码:
主要活动
public class MainActivity extends AppCompatActivity {
MyDatabase myDatabase;
SQLiteDatabase sqLiteDatabase;
EditText textOne;
EditText textTwo;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textOne = (EditText) findViewById(R.id.textOne);
textTwo = (EditText) findViewById(R.id.textTwo);
}
public void addInfo(View view) {
String name = textOne.getText().toString();
String address = textTwo.getText().toString();
myDatabase = new MyDatabase(context);
sqLiteDatabase = myDatabase.getWritableDatabase();
myDatabase.addData(name, address, sqLiteDatabase);
myDatabase.close();
textOne.setText("");
textTwo.setText("");
}
}
我的数据库代码:
public class MyDatabase extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "info.db";
private static final String TABLE_NAME = "Personal_Info";
private static final String NAME_COLUMN = "names";
private static final String ADDRESS_COLUMN = "address";
private static final String ROW_IDENTIFIER = "_id";
private static int DATABSE_VERSION = 1;
private static String query = "CREATE TABLE " + TABLE_NAME + "(" + ROW_IDENTIFIER + " INTEGER PRIMARY KEY AUTOINCREMENT, " + NAME_COLUMN + " TEXT, " + ADDRESS_COLUMN + " TEXT);";
public MyDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABSE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(query);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void addData(String name, String address, SQLiteDatabase db) {
ContentValues contentValues = new ContentValues();
contentValues.put(NAME_COLUMN,name);
contentValues.put(ADDRESS_COLUMN,address);
db.insert(TABLE_NAME,null,contentValues);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME );
} catch (SQLException e) {
e.printStackTrace();
}
onCreate(db);
}
}
MainActivity中的这一行抛出错误:
myDatabase = new MyDatabase(context);
欢迎所有输入。
答案 0 :(得分:0)
您从未初始化变量myDatabase = new MyDatabase(this);
,因此它为null。既然你有一个Activity,你也可以这样做:
this
其中onCreate()
指的是Activity实例。如果您愿意,可以在addItem()
内执行此操作,或将其保留在 $('#estimate').validator({
custom: {
'distance': function() {
if( $("#distance-group").hasClass("invalid")){
return false;
console.log("ERROR")
}else{
return true;
console.log("NO ERROR")
}
}
},
errors: {
'distance': "Nope"
}
})
内的位置。