2012-07-27 40 views
0

我正在開發一個應用程序爲的Android有沒有更好的方式來處理這個字符串列表?

我有不同的類別:

String[] cat = { "Category", "Books", "Clothing", "Shoes", "Hobbies", 
       "General", "Electronics", "Transportation", "Medicine", 
       "Sports", "Education", "Outdoor"}; 

的UI讓用戶選擇一個類別,名稱,以及一些介紹,然後將其寫入到數據庫。當用戶按下列表按鈕時,將顯示填充的每個類別,並且該類別下的項目也使用ExpandableListActivity顯示。

List<List<String>> children = new ArrayList<List<String>>(); 

/********************** 
    I have a list for each category!!! But I don't like this solution. :(
**********************/ 
List<String> books = new ArrayList<String>(); 
List<String> clothing = new ArrayList<String>(); 
    ... 
    ... 

public void fillData() { 

// Get all of the notes from the database and create the item list 
Cursor c = mDbHelper.fetchAllItems(); 

startManagingCursor(c); 

// for all rows 
for(int i=0; i<c.getCount(); i++) 
{ 
    // next row 
    c.moveToNext(); 

    // pick a category 
    String t = c.getString(c.getColumnIndex("category")); 

    switch (getCat(t)) 
    { 
    case Books: 
     books.add(c.getString(c.getColumnIndex("name"))); 
     break; 
    case Clothing: 
      // do stuff for Clothing 
     break; 

    /** 
     And there are other cases for the rest of the categories but i am not listing 
     them here, since it is the same process 
    */ 
     default: 
     break; 
    } // end switch 
} // end for loop 

    //for each category that has been filled up 
    children.add(category); 
} // end function 

我的問題:

是有可能不必爲每個類別的清單?我嘗試了一個列表,但結果看起來不太好。所有類別顯示相同的項目,而不是單個項目,這是有道理的。

+1

不要這樣想。清單列表似乎是在不過度複雜的情況下構建數據的最佳方式。 – 2012-07-27 18:57:22

回答

0

您不需要自己創建列表。

你可能想要有兩個表 - 一個列出類別名稱和它們的ID(這將是主表鍵),另一個列出每行有一個項目的類別ID,項目名稱和任何其他單個項目。

然後你就可以擁有SimpleCursorTreeAdapter這樣的:

SimpleCursorTreeAdapter (Context context, Cursor cursor, int groupLayout, String[] groupFrom, int[] groupTo, int childLayout, String[] childFrom, int[] childTo). 

對於groupLayout你將有android.R.layout.simple_expandable_list_item_1。對於childLayout你將有android.R.layout.simple_list_item_1

groupFrom你將不得不

字符串[] groupFrom = {FLD_CATEGORY_NAME}; int [] groupTo = {android.R.id.text1};

對於childFrom你將有

String[] childFrom = { FLD_ITEM_NAME }; 
int[] childTo = { android.R.id.text1 }; 

或者說自己的佈局,如果你想顯示超過1或2元

,你將有

protected Cursor getChildrenCursor(Cursor groupCursor) { 
     int categoryId = groupCursor.getColumnIndex(FLD_CATEGORY_ID); 
     // and here you a Cursor from your items table WHERE CTAEGORY_ID == categoryId 
} 
+0

但是如果說用戶想要刪除一個項目,它會不會有點混亂。例如,在我想刪除'perl編程'的書籍下面? – infinitloop 2012-07-27 20:28:35

+0

@rashid我只是說SimpleCursorTreeAdapter很適合在ExpandableListView中顯示錶數據 – 2012-07-27 20:50:18

相關問題