当我们点击listview中的项目时,我们如何获得该项目的ID

时间:2016-02-29 06:15:10

标签: android json listview

我有一个json,我有通过Json产品的product_id和product_name现在在listview中显示我希望当点击item时,那个产品的id应该在toast中显示。我是android的新手,我无法做到这一点 谁能告诉我怎么能这样做呢

 public class CityNameActivity extends ListActivity{
ListView list;

private ProgressDialog pDialog;
// URL to get Cities JSON
private static String url = "http://14.140.200.186/Hospital/get_city.php";
// JSON Node names
private static final String TAG_CITIES = "Cities";
//private static final String TAG_ID = "id";
private static final String TAG_NAME = "city_name";
// Cities JSONArray
JSONArray Cities = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> citylist;
//ArrayList<String> citylist;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.cityname_activity_main);
    ListView listView=getListView();
    citylist = new ArrayList<HashMap<String, String>>();
  // list.setOnClickListener(this);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

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

            Intent in = new Intent(getApplicationContext(),
                    Specialities_Activity.class);

            startActivity(in);}
        });
            new GetCities().execute();
        }
/**
 * Async task class to get json by making HTTP call
 * */
private class GetCities extends AsyncTask<Void, Void, Void> {

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

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        // Creating service handler class instance
        ServiceHandler sh = new ServiceHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

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

        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting JSON Array node
                Cities = jsonObj.getJSONArray(TAG_CITIES);

                // looping through All Cities
                for (int i = 0; i < Cities.length(); i++) {
                    JSONObject c = Cities.getJSONObject(i);

                    //String id = c.getString(TAG_ID);
                    String name = c.getString(TAG_NAME);
                    HashMap<String, String> Cities = new HashMap<String, String>();
                    Cities.put(TAG_NAME, name);


                    // adding contact to Cities list
                    citylist.add(Cities);


                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            Log.e("ServiceHandler", "Couldn't get any data from the url");
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result)
    {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();
        /**`enter code here`
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(CityNameActivity.this, citylist, R.layout.city_list_item, new String[] { TAG_NAME}, new int[] { R.id.name});
        setListAdapter(adapter);

}     }

服务代码处理程序类:

 public class ServiceHandler {

static String response = null;
public final static int GET = 1;
public final static int POST = 2;

public ServiceHandler() {

}

/*
 * Making service call
 * @url - url to make request
 * @method - http request method
 * */
public String makeServiceCall(String url, int method) {
    return this.makeServiceCall(url, method, null);
}

/*
 * Making service call
 * @url - url to make request
 * @method - http request method
 * @params - http request params
 * */
public String makeServiceCall(String url, int method,
        List<NameValuePair> params) {
    try {
        // http client
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpEntity httpEntity = null;
        HttpResponse httpResponse = null;

        // Checking http request method type
        if (method == POST) {
            HttpPost httpPost = new HttpPost(url);
            // adding post params
            if (params != null) {
                httpPost.setEntity(new UrlEncodedFormEntity(params));
            }

            httpResponse = httpClient.execute(httpPost);

        } else if (method == GET) {
            // appending params to url
            if (params != null) {
                String paramString = URLEncodedUtils
                        .format(params, "utf-8");
                url += "?" + paramString;
            }
            HttpGet httpGet = new HttpGet(url);

            httpResponse = httpClient.execute(httpGet);

        }
        httpEntity = httpResponse.getEntity();
        response = EntityUtils.toString(httpEntity);

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return response;

}
医院在listview中显示的医院活动代码我希望并非所有医院都显示特定城市的展示医院

 public class HospitalList_Activity extends ListActivity {
private ProgressDialog pDialog;
// URL to get Hospitals JSON
private static String url = "http://14.140.200.186/hospital/get_hospital.php";
// JSON Node names
private static final String TAG_HOSPITAL = "Hospitals";
//private static final String TAG_ID = "id";
private static final String TAG_NAME = "hospital_name";
// Hospitals JSONArray
JSONArray Hospitals = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> hospitallist;
//ArrayList<String> citylist;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_hospital_list_);
    ListView listView=getListView();
    hospitallist = new ArrayList<HashMap<String, String>>();
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

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

            Intent in = new Intent(getApplicationContext(), Specialities_Activity.class);
            startActivity(in);
        }
    });
    new GetHospitals().execute();
}
/**
 * Async task class to get json by making HTTP call
 * */
private class GetHospitals extends AsyncTask<Void, Void, Void> {

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

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        // Creating service handler class instance
        ServiceHandler sh = new ServiceHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

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

        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting JSON Array node
                Hospitals = jsonObj.getJSONArray(TAG_HOSPITAL);

                // looping through All Cities
                for (int i = 0; i < Hospitals.length(); i++) {
                    JSONObject c = Hospitals.getJSONObject(i);

                    //String id = c.getString(TAG_ID);
                    String name = c.getString(TAG_NAME);
                    HashMap<String, String> Hospitals = new HashMap<String, String>();
                    Hospitals.put(TAG_NAME, name);


                    // adding contact to Cities list
                    hospitallist.add(Hospitals);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            Log.e("ServiceHandler", "Couldn't get any data from the url");
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result)
    {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();
        /**`enter code here`
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(HospitalList_Activity.this, hospitallist, R.layout.hospital_list_item, new String[] { TAG_NAME}, new int[] { R.id.name});
        setListAdapter(adapter);




    }
}

3 个答案:

答案 0 :(得分:2)

公共类CityNameActivity扩展了ListActivity {

    ListView list;
    Map <String, String> cityListWithId = new HashMap<String, String>();
    private ProgressDialog pDialog;
    // URL to get Cities JSON
    private static String url = "http://14.140.200.186/Hospital/get_city.php";
    // JSON Node names
    private static final String TAG_CITIES = "Cities";
    private static final String TAG_ID = "city_id";
    private static final String TAG_NAME = "city_name";
    // Cities JSONArray
    JSONArray Cities = null;
    // Hashmap for ListView
    ArrayList<HashMap<String, String>> citylist;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.cityname_activity_main);
        ListView listView=getListView();
        citylist = new ArrayList<HashMap<String, String>>();
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
              //String tagname = ((TextView) findViewById(R.id.name)).getText().toString();
              Map<String, String> tempHashmap =  (Map<String, String>) parent.getItemAtPosition(position);
              String tagName = tempHashmap.get(TAG_NAME);
              System.out.println("tagname" + tagName);
              String tagId = (String)cityListWithId.get(tagName);

              System.out.println("tagId" + tagId);
              Toast.makeText(CityNameActivity.this, tagId,Toast.LENGTH_SHORT).show();

            }
            });
                new GetCities().execute();
            }
    /**
     * Async task class to get json by making HTTP call
     * */
    private class GetCities extends AsyncTask<Void, Void, Void> {

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

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            // Creating service handler class instance
            ServiceHandler sh = new ServiceHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

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

            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    Cities = jsonObj.getJSONArray(TAG_CITIES);

                    // looping through All Cities
                    for (int i = 0; i < Cities.length(); i++) {
                        JSONObject c = Cities.getJSONObject(i);

                        //String id = c.getString(TAG_ID);
                        String name = c.getString(TAG_NAME);
                        cityListWithId.put(c.getString(TAG_NAME), c.getString(TAG_ID));
                        HashMap<String, String> Cities = new HashMap<String, String>();
                        Cities.put(TAG_NAME, name);

                        // adding contact to Cities list
                        citylist.add(Cities);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e("ServiceHandler", "Couldn't get any data from the url");
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result)
        {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            /**`enter code here`
             * Updating parsed JSON data into ListView
             * */
            ListAdapter adapter = new SimpleAdapter(CityNameActivity.this, citylist, R.layout.city_list_item, new String[] { TAG_NAME}, new int[] { R.id.name});
            setListAdapter(adapter);
        }
    }

}

答案 1 :(得分:0)

processing time方法上,您可以添加此项以获取产品的ID。

ItemClick()

答案 2 :(得分:0)

为什么每次都要点击这项服务。根据我的意见,不要在onItemClick上调用服务。当您启动活动或应用程序启动异步任务并将数据传递到列表视图时。

请找到以下代码。我只是重构一些事情,所以如果有什么不对的话请让我

public class CityNameActivity extends ListActivity
{
    private ProgressDialog pDialog;
    // URL to get Cities JSON
    private static String url = "http://14.140.200.186/Hospital/get_city.php";
    // JSON Node names
    private static final String TAG_CITIES = "Cities";
    //private static final String TAG_ID = "id";
    private static final String TAG_NAME = "city_name";
    // Cities JSONArray
    JSONArray Cities = null;
    // Hashmap for ListView
    ArrayList<HashMap<String, String>> citylist;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        new GetCities().execute();

        ListView listView=getListView();
        citylist = new ArrayList<HashMap<String, String>>();
        // list.setOnClickListener(this);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(citylist!=null && !citylist.isEmpty())
                {
                    Toast.makeText(CityNameActivity.this,""+citylist.get(position).get(TAG_NAME).toString(),Toast.LENGTH_SHORT).show();
                }
            }
        });

        new GetCities().execute();
    }




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

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

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            // Creating service handler class instance
            ServiceHandler sh = new ServiceHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

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

            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    Cities = jsonObj.getJSONArray(TAG_CITIES);

                    // looping through All Cities
                    for (int i = 0; i < Cities.length(); i++) {
                        JSONObject c = Cities.getJSONObject(i);

                        //String id = c.getString(TAG_ID);
                        String name = c.getString(TAG_NAME);
                        HashMap<String, String> Cities = new HashMap<String, String>();
                        Cities.put(TAG_NAME, name);


                        // adding contact to Cities list
                        citylist.add(Cities);


                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e("ServiceHandler", "Couldn't get any data from the url");
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result)
        {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            /**`enter code here`
             * Updating parsed JSON data into ListView
             * */
            ListAdapter adapter = new SimpleAdapter(CityNameActivity.this, citylist, R.layout.city_list_item, new String[] { TAG_NAME}, new int[] { R.id.name});
            setListAdapter(adapter);




        }
    }
}