2013-01-11 84 views
1

請檢查這個問題。我試圖檢索我的表中的所有記錄(包含11列3列"name","address","city"),但我的代碼只顯示一個,即最後插入的記錄在我的屏幕上。但我需要顯示所有記錄。SQLite讀取所有數據操作

public void readData(View v) 
    { 
     DatabaseClass mydb = new DatabaseClass(this); 
     SQLiteDatabase readdata = mydb.getReadableDatabase(); 
     TextView tv = (TextView)findViewById(R.id.readtext); 
     Cursor c = readdata.rawQuery("select * from mylistdata", null); 
     int[] elementId = {R.id.textView1, R.id.textView2, R.id.textView3}; 
     if(c !=null) 
     { 
      c.moveToFirst(); 
      while(c.isAfterLast() == false) 
      { 
       listData = new ArrayList<GenericListItem>(); 
       String name = c.getString(c.getColumnIndex(DatabaseClass.NAME)); 
       String address = c.getString(c.getColumnIndex(DatabaseClass.ADDRESS)); 
       String city = c.getString(c.getColumnIndex(DatabaseClass.CITY)); 
       listData.add(new GenericListItem(new String[]{name,address,city})); 
       listAdapter = new GenericListAdapter(getApplicationContext(), R.layout.list_layout, listData, elementId); 
       result.setAdapter(listAdapter); 
       c.moveToNext(); 
      } 



     } 

回答

3

初始化listDataWhile環路的ArrayList外:

c.moveToFirst(); 
    listData = new ArrayList<GenericListItem>(); 
    while(c.isAfterLast() == false) 
    { 
     // add value here to listData 
     c.moveToNext(); 
    } 
    // set listData datasource to GenericListAdapter here 

    listAdapter = new GenericListAdapter(getApplicationContext(), 
       R.layout.list_layout, listData, elementId); 

    result.setAdapter(listAdapter); 
+0

感謝它的工作。 – Unknown

2

它看起來像問題是,你是通過每一次循環中重新創建列表。試試這個:

listData = new ArrayList<GenericListItem>(); //moved out of loop 

while(c.isAfterLast() == false) 
     { 
      String name = c.getString(c.getColumnIndex(DatabaseClass.NAME)); 
      String address = c.getString(c.getColumnIndex(DatabaseClass.ADDRESS)); 
      String city = c.getString(c.getColumnIndex(DatabaseClass.CITY)); 
      listData.add(new GenericListItem(new String[]{name,address,city})); 
      listAdapter = new GenericListAdapter(getApplicationContext(), R.layout.list_layout, listData, elementId); 
      c.moveToNext(); 
     } 

     result.setAdapter(listAdapter); // moved out of loop