如何根据位置在ListView中获取值?

时间:2016-11-19 05:32:23

标签: android listview

我正在尝试将数据库值显示到Listview中,但是,我手动设置元素的位置(例如if(position == 0){})以执行下一个活动的意图。但是我想根据它们的id,name和mobile显示这些元素(即第一个元素活动可以将这些参数解析为下一个活动,因为第二个参数可以保存它们的适当值......等等)。 那我该怎么做呢!

List.java

  protected void showList(){
            try {
                JSONObject jsonObj = new JSONObject(myJSON);
                peoples = jsonObj.getJSONArray(TAG_RESULTS);

                for(int i=0;i<peoples.length();i++){
                    JSONObject c = peoples.getJSONObject(i);
                    String id = c.getString(TAG_ID);
                    String name = c.getString(TAG_NAME);
                    String mobile = c.getString(TAG_MOB);

                    HashMap<String,String> persons = new HashMap<String,String>();

                    persons.put(TAG_ID,id);
                    persons.put(TAG_NAME,name);
                    persons.put(TAG_MOB,mobile);

                    personList.add(persons);
                }

                ListAdapter adapter = new SimpleAdapter(
                        User_List.this, personList, R.layout.list_item,
                        new String[]{TAG_ID,TAG_NAME,TAG_MOB},
                        new int[]{R.id.id, R.id.name, R.id.mobile}
                );

                list.setAdapter(adapter);
                list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            if(position==0) {

                                Intent intent = new Intent(User_List.this, MapsActivity.class);
                                startActivity(intent);
                            }
                    }
                });

            } catch (JSONException e) {
                e.printStackTrace();
            }

1 个答案:

答案 0 :(得分:0)

您需要做的就是在personList数组中的那个位置发送Hashmap对象,如下所示:

list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                                Intent intent = new Intent(User_List.this, MapsActivity.class);
                                intent.putExtra("object",(Serializable)personList.get(position));
                                startActivity(intent);
                            }

                });

并在另一项活动中:

  HashMap<String,String> object=(HashMap<String, String>)getIntent().getSerializableExtra("object");

然后只需将textview设置为:

textview.setText(object.TAG_ID);
textview1.setText(object.TAG_NAME);
textview2.setText(object.TAG_MOB);

检查这是否有效!!!!!

如果你对如何在行为之间传递hashmap有任何疑问,请查看以下链接:

Android - How to pass HashMap<String,String> between activities?