当我尝试在数据库中添加信息时,应用停止。 这是我存储项目信息的类(我在数据库中有3列):
public class Elevator extends AppCompatActivity {
public int id ;
public String name;
public Date date;
//getters and setters here
public Elevator(int id, String name, Date date){
setId(id);
setName(name);
setDate(date);
DatabaseHelper myDB = new DatabaseHelper(this);
myDB.addData(id,name,date);
}
}
我使用Button的主要活动是clickListener:
public class MainActivity extends AppCompatActivity {
DatabaseHelper myDB;
Button btnAdd;
EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnAdd = (Button) findViewById(R.id.btnAdd);
editText = (EditText) findViewById(R.id.editText);
myDB = new DatabaseHelper(this);
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String newEntry = editText.getText().toString();
int id = myDB.getLastID();
if (id == -1) {
id=1;
new Elevator(id,newEntry,null);
} else{
new Elevator(id,newEntry,null);
}
}
});
}
}
在构造函数中添加数据库中的信息是否正确,或者我应该以其他方式执行此操作? 我的Elevator类是否应该扩展AppCompatActivity,如果它不能使用我的DatabaseHelperClass的实例。
这是logcat:
07-24 11:51:55.141: E/AndroidRuntime(5251): FATAL EXCEPTION: main
E/AndroidRuntime(5251): Process: com.example.goshoy.elevatorapp, PID: 5251
E/AndroidRuntime(5251): 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
E/AndroidRuntime(5251): at
android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:269)
E/AndroidRuntime(5251): at
android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked
(SQLiteOpenHelper.java:223)
E/AndroidRuntime(5251): at
android.database.sqlite.SQLiteOpenHelper.getWritableDatabase
(SQLiteOpenHelper.java:163)
E/AndroidRuntime(5251): at
com.example.goshoy.elevatorapp.DatabaseHelper.addData
(DatabaseHelper.java:49)
E/AndroidRuntime(5251): at com.example.goshoy.elevatorapp.Elevator.
<init>(Elevator.java:45)
E/AndroidRuntime(5251): at
com.example.goshoy.elevatorapp.MainActivity$1.onClick(MainActivity.java:34)
E/AndroidRuntime(5251): at
android.view.View.performClick(View.java:5198)
E/AndroidRuntime(5251): at
android.view.View$PerformClick.run(View.java:21147)
E/AndroidRuntime(5251): at
android.os.Handler.handleCallback(Handler.java:739)
E/AndroidRuntime(5251): at
android.os.Handler.dispatchMessage(Handler.java:95)
E/AndroidRuntime(5251): at android.os.Looper.loop(Looper.java:148)
E/AndroidRuntime(5251): at
android.app.ActivityThread.main(ActivityThread.java:5417)
E/AndroidRuntime(5251): at java.lang.reflect.Method.invoke(Native
Method)
E/AndroidRuntime(5251): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run
(ZygoteInit.java:726)
E/AndroidRuntime(5251): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)