代码:
public class DatabaseOpenHelper extends SQLiteOpenHelper {
public String str=null;
public static final String TABLE_SPEECH = "takespeech";
public static final String COLUMN_ID = "id";
public static final String SPEECH_TEXT = "speech";
private static final String DATABASE_NAME = "speechtext.db";
private static final int DATABASE_VERSION = 1;
private SQLiteDatabase database;
private DatabaseOpenHelper dbHelper;
private static final String TABLE_CREATE =
"CREATE TABLE " + TABLE_SPEECH + "(" + COLUMN_ID +" INTEGER, " +
SPEECH_TEXT + " TEXT);";
DatabaseOpenHelper(Context context) {
super(context,DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(TABLE_CREATE);
Log.v("MainActivity", "after creation");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_SPEECH);
// Create tables again
onCreate(db);
}
public void open() throws SQLException {
database=dbHelper.getWritableDatabase();
}
public void close() {
database.close();
}
public void insert(String getpass) {
ContentValues cv=new ContentValues();
cv.put(COLUMN_ID, 1);
cv.put(SPEECH_TEXT,getpass);
// open();
database.insert(TABLE_SPEECH, null, cv);
// close();
}
public String readme() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT"+SPEECH_TEXT+"FROM"+TABLE_SPEECH,null);
if (cursor.moveToFirst()) {
str = cursor.getString(cursor.getColumnIndex(SPEECH_TEXT));
}
return str;
}
}
并在 Mainactivty 中添加和创建表和表值的按钮(是):单击此应用程序崩溃后。
yes.setOnClickListener(new View.OnClickListener(){
public void onClick(View view) {
try {
createTable();
}
catch (SQLiteException se) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
}
}
});
这是当用户单击“是”按钮并插入数据并应调用 onCreate() 时调用的函数,但是当我单击“是”不知道时它会崩溃。
public void createTable() {
DatabaseOpenHelper dbhelper=new DatabaseOpenHelper(getBaseContext());
dbhelper.getWritableDatabase();
dbhelper.insert(pass);
String a=dbhelper.readme();
TextView reads=(TextView)findViewById(R.id.textView2);
reads.setText(a);
}