Search code examples
androidsqlitelistviewlistadaptersimpleadapter

avoid that SQLite table is added in listview everytime the activity is launched


I'm trying to display the content of my SQLite table using SimpleAdapter and TableView. It works just fine at first launch, but when i relaunch the Activity it adds the table one more time in the listView. This happens everytime i launch the intent from my front menu.

It seems to me that the SimpleAdapter is stored from the last time, and added again when the intent is opend from the menu?

Maybe there is a way to reset the adapter everytime it is launched?

I'm new to programming and hope someone can help me:)

Some code:

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();                  
        }

    }

Solution

  • Its because you have declared the "results" array list as a "static" variable.