OnItemClickListener只返回顶部项目

时间:2014-01-30 09:35:48

标签: android json

我正在开发一个JSON解析应用程序。收到的JSON数据显示在列表视图中。我正在尝试在选择项目时显示单个联系人。但它只显示列表顶部元素的详细信息(如果我向下滚动,它会显示当前顶部元素的详细信息)。以下是我的代码

MainActivity.java

package example.json;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class MainActivity extends ListActivity {

    private ProgressDialog pDialog;

    static String url = "http://api.androidhive.info/contacts/";

    // JSON nodes
    private static final String TAG_CONTACTS = "contacts";
    private static final String TAG_ID = "id";
    private static final String TAG_NAME = "name";
    private static final String TAG_EMAIL = "email";
    private static final String TAG_ADDRESS = "address";
    //private static final String TAG_GENDER = "gender";
    private static final String TAG_PHONE = "phone";
    private static final String TAG_PHONE_MOBILE = "mobile";
    //private static final String TAG_PHONE_HOME = "home";
    //private static final String TAG_PHONE_OFFICE = "office";

    JSONArray contacts = null;

    ArrayList<HashMap<String, String>> contactList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        contactList = new ArrayList<HashMap<String, String>>();
        ListView list = getListView();

        list.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // TODO Auto-generated method stub
                // Getting values from selected list item

                HashMap<String, String> contact = (HashMap<String, String>)  parent.getItemAtPosition(position);
                String name = contact.get(TAG_NAME);
                String email = contact.get(TAG_EMAIL);
                String address = contact.get(TAG_EMAIL);
                String mobile = contact.get(TAG_PHONE_MOBILE);

                // Starting single contact activity

                Intent intent = new Intent(getApplicationContext(), SingleContactActivity.class);
                intent.putExtra(TAG_NAME, name);
                intent.putExtra(TAG_EMAIL, email);
                intent.putExtra(TAG_ADDRESS, address);
                intent.putExtra(TAG_PHONE_MOBILE, mobile);
                startActivity(intent);

            }
        });

        new GetContacts().execute();

    }

    private class GetContacts extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {

            ServiceHandler serviceHandler = new ServiceHandler();
            String jsonString = serviceHandler.makeServiceCall(url,
                    ServiceHandler.GET);

            Log.d("Response: ", "> " + jsonString);

            boolean flag = jsonString != null;

            if (flag) {
                try {
                    JSONObject jsnObject = new JSONObject(jsonString);
                    contacts = jsnObject.getJSONArray(TAG_CONTACTS);
                    int max = contacts.length();

                    for (int i = 0; i < max; i++) {
                        JSONObject jsonObject = contacts.getJSONObject(i);

                        String id = jsonObject.getString(TAG_ID);
                        String name = jsonObject.getString(TAG_NAME);
                        String email = jsonObject.getString(TAG_EMAIL);
                        String address = jsonObject.getString(TAG_ADDRESS);
                        //String gender = jsonObject.getString(TAG_GENDER);

                        // Phone node is a JSON object
                        JSONObject phone = jsonObject.getJSONObject(TAG_PHONE);
                        String mobile = phone.getString(TAG_PHONE_MOBILE);
                        //String home = phone.getString(TAG_PHONE_HOME);
                        //String office = phone.getString(TAG_PHONE_OFFICE);

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

                        // Adding each child node to Hashmap key => value
                        contact.put(TAG_ID, id);
                        contact.put(TAG_NAME, name);
                        contact.put(TAG_EMAIL, email);
                        contact.put(TAG_ADDRESS, address);
                        contact.put(TAG_PHONE_MOBILE, mobile);

                        // Adding contact to contactList
                        contactList.add(contact);
                    }
                } catch (JSONException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            } else {
                Log.e("Service Handler", "Couldn't load any data from URL");
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

            if (pDialog.isShowing())
                pDialog.dismiss();

            ListAdapter adapter = new SimpleAdapter(MainActivity.this,
                    contactList, R.layout.list_item, new String[] { TAG_NAME,
                            TAG_ADDRESS, TAG_EMAIL, TAG_PHONE_MOBILE },
                    new int[] { R.id.name, R.id.address, R.id.email,
                            R.id.mobile });
            setListAdapter(adapter);

        }

    }

}

这是我的布局文件

activity_main.xml中

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <ListView 
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"></ListView>

</LinearLayout>

list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    android:orientation="vertical" >

    <TextView 
        android:id="@+id/name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="2dip"
        android:paddingTop="6dip"
        android:textSize="18sp"
        android:textStyle="bold"
        android:textColor="@android:color/black"/>

    <TextView 
        android:id="@+id/address"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="2dip"
        android:paddingTop="6dip"
        android:textSize="14sp"
        android:textColor="@android:color/black"/>

    <TextView 
        android:id="@+id/email"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="2dip"
        android:textSize="14sp"
        android:textColor="@android:color/black"/>

    <TextView 
        android:id="@+id/mobile"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="2dip"
        android:paddingTop="6dip"
        android:textSize="12sp"
        android:text="@string/mobile_num"
        android:textStyle="italic"
        android:textColor="@android:color/black"/>


</LinearLayout>

2 个答案:

答案 0 :(得分:1)

在你的onItemClick中,你正在查看你的观点的活动 - 它将返回它找到的第一个带有id的视图;列表视图第一行中的视图。

使用传递给方法的view搜索id,它将查看该行的子项:

String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String email = ((TextView) view.findViewById(R.id.email)).getText().toString();
String address = ((TextView) view.findViewById(R.id.address)).getText().toString();
String mobile = ((TextView) view.findViewById(R.id.mobile)).getText().toString();

答案 1 :(得分:0)

你必须使用onItemClick提供的AdapterView实例来检索你点击的行的内容,通过getItemAtPosition:

Object object = parent.getItemAtPosition(position);

它将返回一个可以强制转换为适用于适配器的类型的对象。

编辑:我简要介绍了您的代码,我认为以下代码段应该有效:

HashMap<String, String> contact = (HashMap<String, String>)  parent.getItemAtPosition(position);
String name = contact.get(TAG_NAME);
String email = contact.get(TAG_EMAIL);
String address = contact.get(TAG_EMAIL);
String mobile = contact.get(TAG_PHONE_MOBILE);