2011-06-24 75 views
0

IM在安卓progmmaing一個新手,我要問一個簡單的問題從一個ArrayList中複製特定項目到另一個數組列表

我已成功地解析一個RSS feed,並保存特定元素(如標題,pubdate的,鏈接,媒體和描述)。然後我使用arraylist從數據庫中檢索數據。該代碼是

public static ArrayList<Item> GetItems(AndroidDB androiddb) { 
    SQLiteDatabase DB = androiddb.getReadableDatabase(); 
    ArrayList<Item> result = new ArrayList<Item>(); 
    try {  
    Cursor c = DB.rawQuery("select * from ITEMS_TABLE", null); 
    if (c.getCount() > 0) { 
     c.moveToFirst(); 
     do { 
      result.add(new Item(
        c.getString(0), 
        c.getString(1), 
        c.getString(2), 
        c.getString(3), 
        c.getString(4))); 
     } while (c.moveToNext()); 

    } 
    c.close(); 
    DB.close(); 
} catch (SQLException e){ 
    Log.e("DATABASE", "Parsing Error", e); 

} 
return result; 

}

其中0數據庫的第一列包含標題元件

現在我想創建一個列表視圖僅與標題元件,所以我創建的ArrayList在我的onCreate方法和我的問題是我怎麼能從前面的ArrayList只複製引用標題元素的項目。我寫了這部分代碼。我應該在循環中寫什麼來複制特定項目?

 ArrayList<String> first_item = new ArrayList<String>(); 
       items=AndroidDB.GetItems(rssHandler.androiddb); 
       int numRows=items.size(); 
        for(int i=0; i < numRows; ++i) { 

       first_item.add()); 
          } 

     setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, first_item)); 

        ListView lv = getListView(); 
        lv.setTextFilterEnabled(true); 

        lv.setOnItemClickListener(new OnItemClickListener() { 
        public void onItemClick(AdapterView<?> parent, View view, 
         int position, long id) { 
         // When clicked, show a toast with the TextView text 
         Toast.makeText(getApplicationContext(), ((TextView) view).getText(), 
          Toast.LENGTH_SHORT).show(); 
        } 
        }); 
       } 

     catch (Exception e) { 
      tv.setText("Error: " + e.getMessage()); 
      Log.e(MY_DEBUG_TAG, "Parsing Error", e); 
      } 
     this.setContentView(tv); 
    } 

在此先感謝

回答

0

一對夫婦的快速評論 - 首先,

if (c.getCount() > 0) { 
    c.moveToFirst(); 
    do { 
     result.add(new Item(
       c.getString(0), 
       c.getString(1), 
       c.getString(2), 
       c.getString(3), 
       c.getString(4))); 
    } while (c.moveToNext()); 
} 

可以安全地用一個簡單的替換:

while (c.moveToNext()) { 
    .... 
} 

沒有什麼特別的原因,檢查大小這樣,你不需要在遊標上調用moveToFirst()。這只是一個可維護性的建議,並不回答你的問題,但我想把它扔在那裏,以保存將來的擊鍵。

至於你的問題 - 如果我理解正確,你想從一個複合物列表中獲取一個元素列表 - 基本上,一個列表中包含一個特定屬性的所有實例該財產。沒有捷徑可以做到這一點。幸運的是,你可以比你的其他代碼更乾淨做到這一點:

List<CompoundObjectWithAStringProperty> foo = /* go get the list */ 
List<String> allProperties = new ArrayList<String>(); 

for (CompoundObjectWithAStringProperty obj : foo) { 
    allProperties.add(obj.getStringProperty()); 
} 

你的代碼是存在的方式90%,但其所謂C-喜歡哦。

相關問題