我正在为我的android应用程序实现sqlite db(数据库)。当我打开我的应用程序时,我将数据插入数据库并且应用程序退出。当我第二次打开应用程序并尝试检索数据时,我刚刚插入应用程序在我点击后崩溃用于从数据库中检索数据的按钮。是每次打开我的应用程序时数据库都会重置,还是我实现数据库的方式存在问题。这是我的代码:
//用于创建表:
私有静态字符串 SAMPLE_TABLE_NAME = "PERSONS_TABLE";
私有 SQLiteDatabase sampleDB;
private void createTable()
{
sampleDB.execSQL("CREATE TABLE IF NOT EXISTS " +
SAMPLE_TABLE_NAME +
" (COUNT INT(3),PERSON_NAME VARCHAR); ");
}
//插入
private void insertData()
{
sampleDB.execSQL("INSERT INTO " + SAMPLE_TABLE_NAME + " Values ('"+c+"','"+pass+"');");
}
// 仅检索第一列
public int cdata()
{
cursor = sampleDB.rawQuery("SELECT COUNT FROM " +
SAMPLE_TABLE_NAME, null);
if (cursor != null)
{
cursor.moveToFirst();
c=cursor.getInt(cursor.getColumnIndex("COUNT"));
cursor.close();
}
return c;
}
然后我使用这个 c 使用按钮将我的 textview 设置为数据库中的值,以便在单击按钮时,我会知道它们是否是该列中数据库中的任何数据,但我第二次打开应用程序时。所以这次它崩溃了。
用户单击名为“是”的按钮后在数据库中存储语音识别词的代码//使用它来存储语音识别词
@Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK)
{
// Populate the wordsList with the String values the recognition engine thought it heard
ArrayList<String> matches = data.getStringArrayListExtra(
RecognizerIntent.EXTRA_RESULTS);
pass = matches.get(0);
按钮是 = (Button) findViewById(R.id.button1);
yes.setOnClickListener(new View.OnClickListener(){
public void onClick(View view)
{
try
{
c=1;
sampleDB = openOrCreateDatabase("NAME", MODE_PRIVATE, null);
createTable();
insertData();
seeData();
}
catch (SQLiteException se)
{
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
}
finally
{
if (sampleDB != null)
sampleDB.execSQL("DELETE FROM " + SAMPLE_TABLE_NAME);
sampleDB.close();
}
}} );
private void seeData()
{
TextView txts=(TextView)findViewById(R.id.textView2);
cursor = sampleDB.rawQuery("SELECT COUNT,PERSON_NAME FROM " +
SAMPLE_TABLE_NAME, null);
if (cursor != null)
{
cursor.moveToFirst();
String personName = cursor.getString(cursor.getColumnIndex("PERSON_NAME"));
c=cursor.getInt(cursor.getColumnIndex("COUNT"));
//String country = cursor.getString(cursor.getColumnIndex("COUNTRY"));
//int age = cursor.getInt(cursor.getColumnIndex("AGE"));
txts.setText(personName);
if ( pass.equals(personName))
{
Toast.makeText(getApplicationContext(), "Device is unlocked", Toast.LENGTH_SHORT).show();
finish();
}
else
{
Toast.makeText(getApplicationContext(), "WRONG PASSWORD", Toast.LENGTH_SHORT).show();
}
cursor.close();
}
}