2016-05-12 47 views
2

嘿,我一直在努力爲我的大學的Android項目工作,但我堅持在這一點上。我想從表students中提取所有行,將它們填充到ArrayList中,然後使用ListViewCardView來顯示每個學生的記錄。這是我正在使用的代碼:如何獲取表SQLite中的所有行?

public ArrayList<String> getStudentsEntry() 
    { 

     ArrayList<String> arrayList = new ArrayList<>(); 

     Cursor cursor = db.query("STUDENT", ALL_COLUMN_NAME, null, null, null, null, null); 
     if(cursor.getCount()<1) // UserName Not Exist 
     { 
      cursor.close(); 
      return null; 
     } 
     cursor.moveToFirst(); 
     while(cursor.isAfterLast()) { 
      String name = cursor.getString(cursor.getColumnIndex("NAME")); 
      String enrollment = cursor.getString(cursor.getColumnIndex("ENROLLMENT")); 
      String year = cursor.getString(cursor.getColumnIndex("YEAR")); 
      String dob = cursor.getString(cursor.getColumnIndex("DOB")); 
      String email = cursor.getString(cursor.getColumnIndex("EMAIL")); 
      String caste = cursor.getString(cursor.getColumnIndex("CASTE")); 
      String fname = cursor.getString(cursor.getColumnIndex("FNAME")); 
      String mname = cursor.getString(cursor.getColumnIndex("MNAME")); 
      String address = cursor.getString(cursor.getColumnIndex("ADDRESS")); 
      String contact = cursor.getString(cursor.getColumnIndex("CONTACT")); 

      arrayList.add(name); 
      arrayList.add(enrollment); 
      arrayList.add(year); 
      arrayList.add(dob); 
      arrayList.add(email); 
      arrayList.add(caste); 
      arrayList.add(fname); 
      arrayList.add(mname); 
      arrayList.add(address); 
      arrayList.add(contact); 

     } 
     return arrayList; 
    } 

它沒有返回任何東西。我無法從數據庫中獲取數據。數組大小爲零:

Caused by: java.lang.IndexOutOfBoundsException: Invalid index 1, size is 0 

在java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:25

請幫我傢伙,我是新來的這個東東

+0

這是一個不同恩方案有@ShreeKrishna ..我無法從數據庫中檢索數據.. –

回答

2

它不是while(cursor.isAfterLast())應該while(!cursor.isAfterLast())或者根本

while (cursor.moveToNext()) { 
    ... 
} 
+0

感謝@克里希納@工作! :-)只是做了'cursor.moveToNext' –

1
ArrayList<String> arrayList = new ArrayList<>(); 

Cursor cursor = database.query("STUDENT", ALL_COLUMN_NAME, null, null, null, null, null); 
if(cursor.getCount()<1) // UserName Not Exist 
{ 
    cursor.close(); 
    return null; 
} 
cursor.moveToFirst(); 
while(!cursor.isAfterLast()) { 
    for (int column = 0; column < cursor.getColumnCount(); column ++) { 
     arrayList.add(cursor.getString(column));  
    } 
} 
return arrayList; 
相關問題