我從數據庫(id,name)獲取數據,並且想要在ListView中顯示(名稱)。當用戶點擊時,我需要獲取數據庫(id)來執行操作。我得到它的工作,但我的解決方案似乎很複雜這樣一個簡單的事情。我想以某種方式以隱藏的方式將(id)存儲在ListView中,並且在用戶選擇項目時可以檢索它。 這裏是我的解決方案:從ListView獲取數據庫ID
class Route { //structure to store the data in ListView
public int id;
public String name;
public Route (int Id, String Name) {
id = Id;
name = Name;
}
}
// Create a custom adapter, we also created a corresponding
// layout (route_row) for each item of the ListView
public class MySimpleArrayAdapter extends ArrayAdapter<Route> {
private final Context context;
private final String[] values;
public MySimpleArrayAdapter(Context context, ArrayList<Route> routes) {
super(context, R.layout.route_row, routes);
this.context = context;
//Get the list of string array to display in the ListView
String[] values = new String[routes.size()];
//Loop around all the items to get the list of values to be displayed
for (int i=0; i<routes.size(); i++) values[i] =
routes.get(i).id + " - " + routes.get(i).name;
//We added route.id to route.name for debugging but route.id is not necessary
this.values = values; //String array used to display data in the ListView
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.route_row, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.routeName);
textView.setText(values[position]);
return rowView;
}
}
//output is a JSON array composed of JSON object routes
void DisplayListView(String output) { (id, name)
ListView listView = (ListView) findViewById(R.id.listView1);
ArrayList<Route> list = new ArrayList<Route>();
//Convert the JSON to ArrayList<Route>
try {
JSONArray json = new JSONArray(output); //Get JSON array
JSONObject jsonObj;
int id;
String name;
for(int i=0;i<json.length();i++) {
jsonObj = json.getJSONObject(i); //Get each JSON object
id = jsonObj.getInt("Id");
name = jsonObj.getString("Name");
list.add(new Route(id, name));
}
}
catch (Exception ex) {
Log.w("Commute", ex.toString());
ex.printStackTrace();
}
//Create ArrayAdapter
MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(getApplicationContext(),
list);
// Assign adapter to ListView
listView.setAdapter(adapter);
//Set a listener
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(),
"Click ListItem Number " +
((Route)parent.getItemAtPosition(position)).id,
Toast.LENGTH_LONG)
.show();
//It works when user clicks we display route.id
}
});
}
是不是有一個更簡單的方法來做到這一點?我發現了類似的問題,但沒有簡單或明確的答案。
我可以避免使用自定義適配器嗎?我只想爲每行顯示一個簡單的ListView和一個文本。
我可以避免繞過ArrayAdapter來爲adpater創建String數組嗎?這似乎確實是一種不太有效的方式。
我不能完全肯定,如果這是一個最好的做法,但實際上你可以存儲在'隱藏'的TextView id' '或標籤,然後爲該對象設置'android:visibility =「gone」'。 –