2012-07-10 102 views
0

我想存儲數組中的特定列的值,因爲我是一個新手,我不知道如何做到這一點。我從sqlite得到的值爲在android(java)數組中獲取和存儲sqlite的列值

1 
2 
123 
432 
3 
5 

我想將這些值存儲在字符串數組中。請告訴我,我沒有找到任何合適的例子,提前通過Google搜索這個.. thanx。

public void fun(String query){ 
    Cursor cursor = db.rawQuery(query, null); 

    try{ 
     String[] arr = new String[cursor.getCount()]; 
     if(cursor != null){ 
      while(cursor.moveToNext()){ 
       for(int i = 0; i < cursor.getCount(); i++){ 
        arr[i] = cursor.getString(0).trim(); 

       } 
       cursor.moveToNext(); 
      } 
      cursor.close(); 
     } 

    }finally{ 
     cursor.close(); 
    } 

} 

這裏查詢

SELECT <COLUMN_NAME> FROM <TABLE_NAME> WHERE <CONDITION>; 

我想我做錯了請糾正我的錯誤...

+1

把你的代碼如何從數組中獲取這些值,所以我們可以爲你填充這些數組。 – Waqas 2012-07-10 11:34:40

回答

2

我考慮使用rawQuery是個壞習慣,儘量避免這種情況(極端情況除外)

嘗試如下解決您的問題,希望這將幫助你:

public ArrayList<String> getAllStringValues() { 
    ArrayList<String> yourStringValues = new ArrayList<String>(); 
    Cursor result = db.query(true, YOUR_TABLE, 
      new String[] { YOUR_COLUMN_NAME }, null, null, null, null, 
      null, null); 

    if (result.moveToFirst()) { 
     do { 
      yourStringValues.add(result.getString(result 
        .getColumnIndex(YOUR_COLUMN_NAME))); 
     } while (result.moveToNext()); 
    } else { 
     return null; 
    } 
    return yourStringValues; 
} 

使用此方法YourCustomDBManager類。考慮NotePad android開發人員網站示例程序員指南獲取更好的概念的示例。它將幫助你學習如何處理SQLite。我也是Android的新手,但我從NotePad的例子中學到了有關SQLite的一切。

1
Vector<String> vecInt = new Vector<String>; // you can use any datatype <int><float> 

cursor.moveToFirst(); 
for(i=0;i<cursor.getCount();i++) 
{ 
     vecInt.add(cursor.getString(COLUMN_NUM));// if you are using datatype other then string then need to convert here 
} 
1
int [] val = new int[cursor.getCount()]; // integer array 
for(int i= 0; i<cursor.getCount(); i++) 
    val[i] = cursor.getInt(cursor.getColumnIndex(COLUMN_NAME)); 
+0

我已經把我的代碼做了這樣的事情,但沒有得到確切的答案..請檢查 – 2012-07-10 11:41:13

相關問題