从ListView获取数据库ID

时间:2013-02-08 03:13:16

标签: java android

我从数据库(id,name)获取数据,我想在ListView中显示(名称)。当用户点击我需要获取数据库(id)来执行操作。我得到它的工作,但我的解决方案似乎很复杂这么简单。我想以某种方式以隐藏的方式在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数组吗?这似乎是一种无效的方法。

2 个答案:

答案 0 :(得分:0)

使用View的setTag()方法将您自己的对象附加到视图。然后你可以使用这样的东西:

        vh.favourite.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            ForumThread th = (((ViewHolder) view.getTag()).thread);
            th.setWatched(!th.isWatched());
            th.saveLater();
            notifyDataSetChanged();
        }
    });

答案 1 :(得分:0)

我稍后会详细说明答案,但这里是答案的一部分。

  • 创建ListActivity是一种更好的启动方式(将负责注册项目点击的监听器)

  • 在自定义数组适配器中,覆盖:public long getItemId (int position)以在onListItemClick被调用时返回相应的ID。

  • 使用SimpleCursorAdapter时,似乎onListItemClick会自动识别数据库ID。这可能是因为我们在进行SimpleCursorAdapter的绑定时提供了id:
    new String[] { "Name", "IsOffer", "Distance", BaseColumns._ID }, //Columns from table BaseColumns._ID new int[] { R.id.name, R.id.isOffer, R.id.distance, R.id.id },