2

我从数据库(id,name)中获取数据,我想在 ListView 中显示(name)。当用户单击时,我需要获取数据库(id)来执行操作。我让它工作,但我的解决方案对于这么简单的事情来说似乎很复杂。我想以某种方式将(id)以隐藏的方式存储在 ListView 中,并在用户选择项目时能够检索它。这是我的解决方案:

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 数组吗?这似乎确实是一种低效的方法。

4

2 回答 2

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();
        }
    });
于 2013-02-08T03:57:22.307 回答
0

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

  • 创建 ListActivity 是一种更好的开始方式(将负责注册监听器以进行项目点击)

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

  • 使用 SimpleCursorAdapter 时,似乎数据库 ID 将由onListItemClick. 这可能是因为我们在绑定 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 },

于 2013-02-22T06:13:37.540 回答