我正在開發一個數據庫應用程序來輸入它的註釋。但是當我在模擬器上運行此應用程序時,它立即停止說Unfortunately!Notepad2 has stopped working
。請幫助我正確地工作。 有兩個文件。 一個MainActivity.java:運行時創建數據庫異常
package com.example.notepad2;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements OnClickListener {
EditText title,body;
Button btn;
NotepadDb notepad;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
title=(EditText)findViewById(R.id.title);
body=(EditText)findViewById(R.id.body);
btn=(Button)findViewById(R.id.btn);
btn.setOnClickListener(this);
notepad=new NotepadDb(this);
notepad=notepad.open();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
notepad.insert(title.getText().toString(), body.getText().toString());
notepad.close();
}
}
,另一個是NotepadDb.java
package com.example.notepad2;
import android.app.Activity;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class NotepadDb extends Activity {
private static final String DATABASE_NAME="Notepad";
private static final String TABLE_NAME="note";
private final int DATABASE_VERSION=1;
private static final String KEY_TITLE="title";
private static final String KEY_BODY="body";
private static final String ID="_id";
private static final String Query="create table note(_id integer auto_increment primary key,title text not null,body text not null);";
DatabaseHelper dbHelper;
SQLiteDatabase mydb;
private Context cntxt;
public class DatabaseHelper extends SQLiteOpenHelper{
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME,null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(Query);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("drop table note");
onCreate(db);
}
}
public NotepadDb(Context context){
cntxt=context;
}
public NotepadDb open() throws SQLException{
dbHelper=new DatabaseHelper(cntxt);
mydb=dbHelper.getReadableDatabase();
return this;
}
public void insert(String title,String body){
mydb.execSQL("insert into note values(null,"+title+","+body+");");
}
public void close(){
dbHelper.close();
}
}
檢查logcat的,看看您的Java堆棧跟蹤告訴你的。 – CommonsWare
發佈整個堆棧跟蹤.. – bakriOnFire
請在您的代碼中放置錯誤日誌以標識實際錯誤 –