2011-06-24 62 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-喜欢哦。

相关问题