2017-04-10 60 views
0

更新:問題修復 - ActionBar覆蓋列表中的第一個項目。ListView不顯示第一行值

SOLUTION:Android AppBarLayout overlaps listview

在我的計劃,我從數據庫中檢索數據,並使用列表視圖顯示它。 但是,第一行元素總是在進程中跳過,顯示從第二行開始。

public void displaydata(){ 
    Cursor res = myDb.getAllData(); 
    lv = (ListView) findViewById(R.id.idListView); 
    if(res.getCount() == 0){ 
     //show message 
     return; 
    } 
    ArrayList<String> buffer = new ArrayList<>(); 
    while(res.moveToNext()){ 
     buffer.add(res.getString(1)); 
    }; 
    ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,buffer); 
    lv.setAdapter(adapter); 
} 

如何從第一行顯示? 任何幫助表示讚賞,謝謝。

編輯:我試過所有建議使用'做'和'for循環'的答案,所有這些都給出了相同的結果。

+0

我相信它是因爲'res.moveToNext()'所以索引0被跳過轉到下一行 – Derek

+0

相關:http://stackoverflow.com/questions/10723770/whats-the-best-way- to-iterate-an-android-cursor – JBC

+0

[重複Android遊標的最佳方式是什麼?](http://stackoverflow.com/questions/10723770/whats-the-best-way-to-iterate- an-android-cursor) –

回答

0

試試這個

for(res.moveToFirst(); !res.isAfterLast(); res.moveToNext()){ 
    buffer.add(res.getString(1)); 
} 
+0

仍然得到相同的結果:/ ..第一行仍然被跳過。 –

1

嘗試改變

while(res.moveToNext()){ 
     buffer.add(res.getString(1)); 
    }; 

編輯:改變一段時間,所以之後遞增:

do { 
    buffer.add(res.getString(1)); 
} while (cursor.moveToNext()); 
+1

'do {...} while(res.moveToNext());''以避免重複的'getCount()'調用是首選 –

+0

@Derek Baxter這不起作用,因爲我需要使'res'指向下一個數據項目使用'res.moveToNext'。 –

+0

@SouravSamanta http://stackoverflow.com/a/22417381/2308683 –

0

就個人而言,我會建議使用數據庫時的。

lv = (ListView) findViewById(R.id.idListView); 

String from = { COLUMN_NAME }; 
int[] to = { android.R.id.text1 }; 

SimpleCursorAdapter adapter = 
    new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, 
      myDb.getAllData(), 
      from, to); 
lv.setAdapter(adapter); 
+0

它說「SimpleCursorAdapter」已棄用 –

+0

是的,這是真的,但這並不意味着這不應該工作 –

0

試一試這個代碼可能對於使用遊標從數據庫中獲取數據很有用。

public ArrayList<BasicInfo> getFetchBasicInfo() { 

    ArrayList<BasicInfo> data = new ArrayList<BasicInfo>(); 

    String sql = "select * from basic_info; 

    Cursor c = fetchData(sql); 

    if (c != null) { 
     while (c.moveToNext()) { 

      String FirstName = c.getString(c.getColumnIndex("first_name")); 

      String LastName = c.getString(c.getColumnIndex("last_name")); 
      String Sabcription = c.getString(c 
        .getColumnIndex("salutation_id")); 
      data.add(new BasicInfo(FirstName, LastName)); 
     } 
     c.close(); 
    } 
    return data; 
}