-3

I have a json in which i have product_id and product_name through the Json products are showing in listview now i want that when clicked on item then id of that product should be show in toast. I am new to android i am unable to do this can anyone tell me how can i do this please

 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);

} }

Code of Service Handlerclass:

 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;

}

code of Hospital Activity in which hospital is showing in listview i want that not all hospitals show only show hospital of specific city

 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);




    }
}
Tom
  • 133
  • 1
  • 1
  • 8

3 Answers3

2

public class CityNameActivity extends 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);
        }
    }

}

sanky jain
  • 873
  • 1
  • 5
  • 14
  • do it below for (int i = 0; i < Cities.length(); i++) { JSONObject c = Cities.getJSONObject(i); – sanky jain Feb 29 '16 at 06:48
  • cityListWithId can not reslove – Tom Feb 29 '16 at 06:54
  • Map cityListWithId = new HashMap(); this line should at top, just after you start your class – sanky jain Feb 29 '16 at 06:56
  • print tag name and tagId and see what you are getting – sanky jain Feb 29 '16 at 07:01
  • tagname i am getting but tagid null – Tom Feb 29 '16 at 07:03
  • print cityListWithId, i want to confirm are you able to add values correctly to Hashmap – sanky jain Feb 29 '16 at 07:05
  • am not able to do this here everything is new for me i did so far as u give me code – Tom Feb 29 '16 at 07:07
  • String tagname = ((TextView) findViewById(R.id.name)).getText().toString(); String tagId = cityListWithId.get(tagname); Toast.makeText(getApplication(), tagId, Toast.LENGTH_LONG).show(); – Tom Feb 29 '16 at 07:08
  • i pasted this line as u told me – Tom Feb 29 '16 at 07:08
  • Chnage private static final String TAG_ID = "id"; to private static final String TAG_ID = "city_id"; try it we are very close – sanky jain Feb 29 '16 at 07:17
  • sorry i try now there is network problem so just i read your comment – Tom Feb 29 '16 at 07:31
  • i debug it when i come on toast line it shows tagname="Gr.Noida" and tagId="null" – Tom Feb 29 '16 at 07:35
  • its difficult to know where you are facing problem. If you want you can send me your full code. I will solve and send you back – sanky jain Feb 29 '16 at 07:38
  • how can you take this via mail or i post here – Tom Feb 29 '16 at 07:44
  • i have posted u can see – Tom Feb 29 '16 at 08:04
  • i try to run your code, but its not giving any result and giving permission denied. What permission you added to get data – sanky jain Feb 29 '16 at 08:49
  • It is working now. I tested it. Copy my code and try now – sanky jain Feb 29 '16 at 09:05
  • can you one more help – Tom Feb 29 '16 at 09:14
  • i have another activity in which i am showing list of hospitals from another json, all hospital have own id ok now my task is when i click on first city which has id 1 then hospital of same id should be show in listview. Hope you understand what i am saying – Tom Feb 29 '16 at 09:18
  • have you got what i am asking – Tom Feb 29 '16 at 09:21
  • you want on click of city for eg - Delhi it will open another activity with a list of hospitals for Delhi? – sanky jain Feb 29 '16 at 09:24
  • exactly i want this when i clicked on delhi it will another activity with a list of hospitals for delhi. – Tom Feb 29 '16 at 09:27
  • In on click delete toast and add below code Intent i = new Intent(this, HospitalActivity.class); i.putExtra(TAG_ID , tagId ); startActivity(i); Then in onCreate of HospitalActivity fetch the tagId and use it to get values – sanky jain Feb 29 '16 at 09:27
  • if you are interested then i can post code of my hospital activity – Tom Feb 29 '16 at 09:28
  • i wrote this. Is it right? Intent intent = getIntent(); hospitalname = intent.getExtras().getString("tagId"); – Tom Feb 29 '16 at 09:36
  • @ sanky jain i have posted code of hospital list when i click on delhi then all hospitals shows but i dont want this i want when i click on delhi then hospital of delhi should be show please help me please – Tom Feb 29 '16 at 10:01
  • i try to do this but i a unable so please when you have sometime please give me code i am waiting please please – Tom Feb 29 '16 at 11:48
  • why did you unmarked my anser, your actaul problem you posted is solved right? – sanky jain Mar 01 '16 at 04:41
  • oh sorry i did not this actually my friend did this for fun i saw right now after your comment so sorry from my side your answer is good helpful for me thanks for help – Tom Mar 01 '16 at 05:07
0

On ItemClick() method you can add this to get the id of the product.

HashMap<String,String> data = cityList.get(position);
//position is the paramater from ItemClick
String id = data.get("your key for Id");
Ravi Theja
  • 3,063
  • 1
  • 20
  • 32
  • in your city_id is null – Tom Feb 29 '16 at 07:12
  • can you please explain clearly what your problem is.? if it is null may be you are parsing wrong or you don't have a value for id.what do you mean by how can i know id is this? Debug and cross check with the json – Ravi Theja Feb 29 '16 at 07:28
  • i want get only id of city when i clicked parsing is right from from cities are showing – Tom Feb 29 '16 at 07:37
  • that is what the code i have given should do..as you are storing your values in list of hashmap,get the hashmap of that position and get the id from the map – Ravi Theja Feb 29 '16 at 09:13
  • id has been shown in toast but i have another task can you help me – Tom Feb 29 '16 at 09:15
  • what can i help you with – Ravi Theja Feb 29 '16 at 09:16
  • i have you shown cities in listview and every city has own id and i have another actvity in which list of hospitals is showing all hospitals have own id now i want that when i click on first city of id 1 then all the hospital of same id as city has should be show in listview – Tom Feb 29 '16 at 09:21
  • if you are interested then i can give you code of second activity in which hospital are showing – Tom Feb 29 '16 at 09:24
  • you have to have api's for that .That is to be handled by api's.Or if you are storing everything in local db some query should do it.To get the Id of each hospital follow the same procedure as cities – Ravi Theja Feb 29 '16 at 09:59
  • i have service of hospital name and id i have posted my second activity code u can check tell me what i can now – Tom Feb 29 '16 at 10:08
  • pass the id of the selected city in intent and receive that in the second Activity.use the id in your service call to get the hospitals in that city – Ravi Theja Feb 29 '16 at 10:48
  • Sorry i don't how i will code for this because i am new to android so i am asking code – Tom Feb 29 '16 at 11:12
  • i am not passing data from one activity to another activity i want that when i click on item(city name) then another item(hospital name corresponds to city) of same id should be show – Tom Feb 29 '16 at 12:07
0

why you every time hit the service . as per my opinion don't call service in onItemClick . when you start activity or app start Async task and pass data to list view .

please find below code . i am just refactor few thing so please let me if there some thing wrong

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);




        }
    }
}
Damodhar
  • 1,167
  • 7
  • 16