2012-07-25 70 views
2

剛開始學習如何爲Android編程,現在我陷入了一些疑慮。ListView上的Android SQLite查詢結果

我有一個SQLite數據庫與多個表和每個表與一些字段。

我創建了一個類來管理我的數據庫和想象的功能之一是這樣的:

public Cursor getGroupData() { 
    String[] values = new String[] {_ROWID, _NAME, _AGE, _PHONE}; 
    Cursor c = db.query(BD_TABLE, values, null, null, null, null, null); 
    return c; 
} 

現在我有兩種情況之一。

第一種情況

要展示,例如,所有的名字返回我在ListView查詢。就這樣,用戶可以在一個名字點擊和新的活動將展示(想象一個佈局,所有的用戶信息)

第二種情況

要展示,例如,所有的名字返回上我的查詢在ListView中。這樣,用戶可以點擊一個名字,並且將執行一個新的查詢(想象一下從該用戶那裏獲得其他數據)。查詢將導致返回各種數據,而我又想在ListView中顯示一些字段(例如地址)。現在,如果用戶點擊地址,將顯示一個新的活動(例如一個包含地址信息的佈局)。

在這兩種情況下,雖然我只是選擇一個名稱或地址,但SQLite返回的所有數據都必須可用,例如,在第一種情況下,我選擇一個名稱,它將顯示在佈局,就像聯繫信息一樣,但查詢,年齡和電話的結果也必須可用。

現在我在做這樣的事情:

Cursor values = db.getGroupData(); 
// Now I'm thinking in putting some code to iterate over the cursor and put what I want to display on my listview on a string array 

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, values_I_what_to_show); 
setListAdapter(adapter); 

這樣做的問題是,我把一個字符串數組上的數據,但需要查詢返回的所有數據。

你能指點一下嗎?

問候,

+1

我將建議使用[CursorAdapter的](HTTP: //developer.android.com/reference/and roid/widget/CursorAdapter.html)而不是ArrayAdapter – Vladimir 2012-07-25 09:41:54

+0

是不是不推薦?試圖理解CursorLoader,但沒有能力 – Favolas 2012-07-25 09:50:19

回答

5

嘗試這種情況:

Cursor cursor =db.getGroupData(); 
ArrayList<MyData> listData = new ArrayList<MyData>(); 
while (cursor.moveToNext()) { 
     MyData temp = new MyData(); 
     temp.id = cursor.getInt(0); 
     temp.name = cursor.getString(1); 
     temp.age= cursor.getInt(2); 
     temp.phone= cursor.getInt(3); 
     listData .add(temp); 
        temp =null; 
    } 
cursor.close(); 
MyAdapter myAdapter = new MyAdapter(this, 
      R.layout.list_item, listData); //use custom adapter 
listView.setAdapter(myAdapter); 

聲明邁德特類:

private class MyData{ 
    int id ; 
    String name; 
    int age; 
    int phone; 
} 

MyAdapter類:

private class MyAdapter extends ArrayAdapter<projData> { 
    private ArrayList<MyData> items; 
    private Context context; 

    public MyAdapter(Context context, int textViewResourceId, 
      ArrayList<MyData> items) { 
     super(context, textViewResourceId, items); 
     this.context = context; 
     this.items = items; 
     } 

    public View getView(final int position, View convertView, 
      ViewGroup parent) { 
     View view = convertView; 
     if (view == null) { 
      LayoutInflater inflater = (LayoutInflater) context 
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
      view = inflater.inflate(R.layout.list_item, null); 
     } 
    //here getview code as per ur req 
     } 
    return view; 
    } 
} 
+0

謝謝,但不明白什麼是MyAdapter。它在哪裏定義? – Favolas 2012-07-26 09:35:16

+0

我已更新代碼 – Archana 2012-07-27 04:35:52

+0

謝謝。以其他方式管理,但將在未來有用 – Favolas 2012-07-27 13:38:08