2012-01-29 33 views
0

我使用的代碼this blog有一個可拖動的列表。本教程使用自定義DragNDropAdapter ,將內容作爲ArrayList使用。從sqlite到ArrayList的數據<String>

在我的listActivity我查詢一個表返回列name。它有11個值插入。 我試圖將其轉換從string []到ArrayList中有很多方法,如:

String[] from = new String[]{DbManager.KEY_NAME}; 
ArrayList<String> content = new ArrayList<String>(); 

for (int i=-1,l=from.length; ++i<l;) { 
      content.add(from[i]); 
      //Log.i("ArrayList", from[i]); 
     } 

while(!mShopCatCursor.isAfterLast()){ 
     content.add(mShopCatCursor.getString(0)); 
    } 

什麼,我得到的是列,name的只是名稱的列表。 你有什麼想法

回答

0
String[] from = new String[]{DbManager.KEY_NAME}; 

因爲你的字符串數組只有一個值是KEY_NAME。

你需要做的是,使用循環和填充它的String []從以上光標

獲取值。

Cursor userCur = adaptor.getYourData(); 
      if (userCur != null) { 
       String[] strArr = new String[userCur.getCount()]; 
       startManagingCursor(userCur); 
       if (userCur.moveToFirst()) { 
        int count = 0; 
        do { 
         String userName = userCur.getString(1); 
         strArr[count] = userName.trim(); 
         count++; 
        } while (userCur.moveToNext()); 
       } 

ArrayList<String> content = new ArrayList<String>(); 
       for (int i=-1,l=from.length; ++i<l;) {  
       content.add(from[i]);    
     //Log.i("ArrayList", from[i]);   
    }     
} 

注意:我沒有在IDE中對此進行驗證,可能存在語法錯誤。

+0

謝謝你的工作,只是合理的。我從很多使用上述語法String [] from = new String [] {DbManager.KEY_NAME}的教程中感到困惑;並將from數組導入ListAdapters。我有一個問題,但你的答案。爲什麼我應該在第一行使用if(userCur!= null),而不是像這樣:cursor.moveToFirst()然後是while循環。第二個問題爲什麼我需要循環內部的修剪功能。無論如何非常感謝 – 2012-01-29 12:27:51

+0

很高興它的工作。請接受答案。享受編程。 – kosa 2012-01-29 12:29:02

+0

這取決於你的getYourData()方法是如何實現的。有些實現可能爲null,如果cursor爲null,則cursor.moveToFirst()將拋出NullPointerException。所以,最好做空檢查。 – kosa 2012-01-29 12:39:24

1

您可以使用以下方法,此方法將從db獲取數據,然後返回此數據的字符串ArrayList。在你的情況下,這個數組列表將包含名稱。

private ArrayList<String> getArrayList() { 

    ArrayList<String> namesList = null; 

    Cursor cursor = null; 
    try { 
     String query = "";//your query here 
     cursor = db.rawQuery(query,null); 
     if (cursor != null && cursor.moveToFirst()) { 
      namesList = new ArrayList<String>(); 
      do { 
       namesList.add(cursor.getString(0)); 
      } while (cursor.moveToNext()); 
     } 
    } catch (Exception e) { 
     e.printStackTrace(); 
     namesList = null; 
    } finally { 
     if (cursor != null && !cursor.isClosed()) { 
      cursor.deactivate(); 
      cursor.close(); 
      cursor = null; 
     } 
     close(); 
    } 
    return namesList; 
} 


/** 
* Closes the database 
*/ 
private void close() { 
    try { 
     if (db != null && db.isOpen()) { 
      DBHelper.close(); 
     } 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 
+0

返回前的close()函數有什麼作用? – 2012-01-29 13:05:06

+0

@NikTsekour,我已經添加了close()方法,它關閉了數據庫連接。 – 2012-01-29 13:11:32

相關問題