[英]Copy one item from an ArrayList to another ArrayList Java 8
[英]copy specific item from one arraylist to another arraylist
我是android progmmaing的新手,我想問一個簡單的問題
我已經設法解析一個RSS提要,並將特定的元素(例如Title,pubdate,link,media和description)保存在數據庫中。 然后我使用了一個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包含標題元素的數據庫的第一列
現在我只想用title元素創建一個listview,所以我在onCreate方法中創建了一個ArrayList,我的問題是我如何才能從以前的ArrayList中僅復制引用Title元素的項目。 我已經編寫了這部分代碼。 我應該在循環中寫些什么來復制特定項目?
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);
}
提前致謝
一些簡短的評論-首先,
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。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.