android应用程序开发中的SQLite数据库行为

时间:2011-07-04 14:57:26

标签: java android sqlite

您好我尝试了以下代码,并在列表视图中正确地将表中的记录列表作为输出。

但是当我评论Main_Activity类中的以下两个方法时,数据库记录不会被加载。      CREATETABLE();      insertData();

当我们在关闭它之后打开相同的应用程序时,我想知道是否必须再次创建表并插入相同的记录集。

有没有人知道为什么会这样发生......谢谢..

public class Main_Activity extends ListActivity {

private static String SAMPLE_TABLE_NAME = "PERSONS_TABLE";
private SQLiteDatabase sampleDB = null;
private List<String> results = new ArrayList<String>();
private Cursor cursor = null;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main); 

    try
    {
        sampleDB = openOrCreateDatabase("NAME", MODE_PRIVATE, null);
        createTable();
        insertData();
        lookupData();
        this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,results));
    }
    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 createTable()
{
   sampleDB.execSQL("CREATE TABLE IF NOT EXISTS " +
                SAMPLE_TABLE_NAME +
                " (PERSON_NAME VARCHAR, " +
                "  COUNTRY VARCHAR, " +
                "  AGE INT(3));");
}

private void insertData()
{
    sampleDB.execSQL("INSERT INTO " + SAMPLE_TABLE_NAME + " Values ('James','ENGLAND',25);");
    sampleDB.execSQL("INSERT INTO " + SAMPLE_TABLE_NAME + " Values ('Dave','USA',18);");
    sampleDB.execSQL("INSERT INTO " + SAMPLE_TABLE_NAME + " Values ('Jean-Paul','FRANCE',33);");
    sampleDB.execSQL("INSERT INTO " + SAMPLE_TABLE_NAME + " Values ('Sergio','SPAIN',42);");
    sampleDB.execSQL("INSERT INTO " + SAMPLE_TABLE_NAME + " Values ('Hitori','JAPAN',73);");
}

private void lookupData()
{
    cursor = sampleDB.rawQuery("SELECT PERSON_NAME, COUNTRY, AGE FROM " +
            SAMPLE_TABLE_NAME +
            " where AGE > 10 ", null);

    if (cursor != null)
    {
        if (cursor.moveToFirst())
        {
            do
            {
                String personName =     cursor.getString(cursor.getColumnIndex("PERSON_NAME"));
                String country = cursor.getString(cursor.getColumnIndex("COUNTRY"));
                int age = cursor.getInt(cursor.getColumnIndex("AGE"));
                results.add("" + personName + ", " + country + ", " + age);
            } 
            while (cursor.moveToNext());
        }
        cursor.close();
    }
}
}

1 个答案:

答案 0 :(得分:1)

在你的try语句中,你正在创建数据库,填充它......然后在finally语句中删除所有记录。这就是你的数据库总是空着的原因。你应该记住,在try或catch之后最终会执行任何操作。