0

我正在尝试使用 SimpleAdapter 和 TableView 显示我的 SQLite 表的内容。它在第一次启动时工作得很好,但是当我重新启动 Activity 时,它会在 listView 中再次添加表格。每次我从前面的菜单启动意图时都会发生这种情况。

在我看来,SimpleAdapter 是上次存储的,并在从菜单打开意图时再次添加?

也许有一种方法可以在每次启动适配器时重置它?

我是编程新手,希望有人可以帮助我:)

一些代码:

static final ArrayList<HashMap<String,String>> results = new ArrayList<HashMap<String,String>>(); 
private String tableName = DBAdapter.tableName;
private SQLiteDatabase newDB;



@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    openAndQueryDatabase();

    displayResultList();

    }



private void displayResultList() {

    ListAdapter adapter = new SimpleAdapter(
            this,
            results,
            R.layout.liste,
            new String[] {"Name","LastName","Age"},
            new int[] {R.id.item_id,R.id.item_name,R.id.item_tid}
            );
    setListAdapter(adapter);

}
    private void openAndQueryDatabase() {
        try {
            DBAdapter dbHelper = new DBAdapter(this.getApplicationContext());
            newDB = dbHelper.getWritableDatabase();
            Cursor c = newDB.rawQuery("SELECT Startnr, Navn, Tid FROM " +
                    tableName + " ORDER BY Startnr ASC" , null);

            if (c != null ) {
                if  (c.moveToFirst()) { 
                    do {
                        HashMap<String,String> list = new HashMap<String,String>();
                        String firstName = c.getString(c.getColumnIndex("Startnr"));
                        String lastName = c.getString(c.getColumnIndex("Navn"));
                        String age = c.getString(c.getColumnIndex("Tid"));
                        list.put("Name", "" + firstName);
                        list.put("LastName", "" + lastName);
                        list.put("Age", "" + age);
                        results.add(list);
                    }while (c.moveToNext());
                } 
            }           
        } catch (SQLiteException se ) {
            Log.e(getClass().getSimpleName(), "Could not create or Open the database");
        } finally {
            if (newDB != null) 
                newDB.close();                  
        }

    }
4

1 回答 1

1
Its because you have declared the "results" array list as a "static" variable.
于 2012-01-29T14:00:02.447 回答