Hasna Amir
Hasna Amir

Reputation: 21

Why showing same data in android json parsing at single activity

Actually i want to show only hospital name in list view and want to show details in single activity but in single activity showing same data for different hospital. Im using eclipse.

Ambulance Activity

public class AmbulanceActivity extends ListActivity {

    private ProgressDialog pDialog;

    // URL to get contacts JSON
    private static String url = "http://10.0.2.2/health/admin/myapi_emargencyHospital.php";

    // JSON Node names
    private static final String TAG_AMB = "ambulance";
    private static final String TAG_ID = "id";
    private static final String TAG_AREA = "area_nam";
    private static final String TAG_HOSPITAL = "hos_nam";
    private static final String TAG_NUMBER = "emar_amb_no";
    private static final String TAG_ADDRESS = "hos_add";

    private String id, areNam, hosNam, hosPhn, hosAddr;
    // contacts JSONArray
    JSONArray ambulance = null;

    // Hashmap for ListView
       /* public static ArrayList<HashMap<String, String>> gdiseaseList;*/

    ArrayList<HashMap<String, String>> gdiseaseList;

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

        gdiseaseList = new ArrayList<HashMap<String, String>>();

        ListView lv = getListView();


        // Listview on item click listener
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                // getting values from selected ListItem
                //String area = ((TextView) view.findViewById(R.id.abArea_name))
                //        .getText().toString();
                String hosNam = ((TextView) view.findViewById(R.id.abHos_name))
                        .getText().toString();
                //String abNum = ((TextView) view.findViewById(R.id.abPhon_numb))
                //       .getText().toString();
                //String abAddress = ((TextView) view.findViewById(R.id.abHos_address))
                //       .getText().toString();


                // Starting single contact activity
                Intent in = new Intent(getApplicationContext(),
                        AmbulanceSingleActivity.class);
                in.putExtra(TAG_AREA, areNam);
                in.putExtra(TAG_HOSPITAL, hosNam);
                in.putExtra(TAG_NUMBER, hosPhn);
                in.putExtra(TAG_ADDRESS, hosAddr);

          /*   in.putExtra("positonn", position);
             Log.e("positonn", ""+position);
           */
                startActivity(in);

            }
        });

        // Calling async task to get json
        new GDisease().execute();
    }

    /**
     * `Async task` class to get json by making HTTP call
     */

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

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(AmbulanceActivity.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
                    ambulance = jsonObj.getJSONArray(TAG_AMB);

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

                        id = c.getString(TAG_ID);
                        areNam = c.getString(TAG_AREA);
                        hosNam = c.getString(TAG_HOSPITAL);
                        hosPhn = c.getString(TAG_NUMBER);
                        hosAddr = c.getString(TAG_ADDRESS);


                        // tmp hashmap for single contact
                        HashMap<String, String> sdieasess = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        sdieasess.put(TAG_ID, id);
                        sdieasess.put(TAG_AREA, areNam);
                        sdieasess.put(TAG_HOSPITAL, hosNam);
                        sdieasess.put(TAG_NUMBER, hosPhn);
                        sdieasess.put(TAG_ADDRESS, hosAddr);


                        // adding contact to contact list
                        gdiseaseList.add(sdieasess);
                    }
                } 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();
            /**
             * Updating parsed JSON data into ListView
             * */
            ListAdapter adapter = new SimpleAdapter(
                    AmbulanceActivity.this, gdiseaseList,
                    R.layout.list_item_ambulance, new String[]{TAG_HOSPITAL}, new int[]{R.id.abHos_name});

            setListAdapter(adapter);
        }
    }
}

AmbulanceSingleActivity

public class AmbulanceSingleActivity extends Activity {

    Button call;

    private static final String TAG_AREA = "area_nam";
    private static final String TAG_HOSPITAL = "hos_nam";
    private static final String TAG_NUMBER = "emar_amb_no";
    private static final String TAG_ADDRESS = "hos_add";
    private Uri number;
    private String phoneNumber, hospitalName;


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

        // getting intent data
        Intent in = getIntent();

        // Get JSON values from previous intent
        String area_nam = "Area Name : " + in.getStringExtra(TAG_AREA);
        String hos_nam = "Hospital Name : " + in.getStringExtra(TAG_HOSPITAL);
        String emar_amb_no = "Phone Number : " + in.getStringExtra(TAG_NUMBER);
        String hos_add = "Hospital Address : " + in.getStringExtra(TAG_ADDRESS);


        phoneNumber = in.getStringExtra(TAG_NUMBER);
        hospitalName = in.getStringExtra(TAG_HOSPITAL);
        getActionBar().setTitle(hospitalName);

        // Displaying all values on the screen
        TextView AreaName = (TextView) findViewById(R.id.ab_S_area);
        TextView HosName = (TextView) findViewById(R.id.ab_s_hosname);
        TextView PhonNam = (TextView) findViewById(R.id.ab_s_phonNUm);
        TextView HosAdd = (TextView) findViewById(R.id.ab_s_hosAddress);
        call = (Button) findViewById(R.id.btn_call);


        AreaName.setText(area_nam);
        HosName.setText(hos_nam);
        PhonNam.setText(emar_amb_no);
        HosAdd.setText(hos_add);


        call.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                number = Uri.parse("tel:" + phoneNumber);
                Intent callIntent = new Intent(Intent.ACTION_CALL);
                callIntent.setData(number);
                startActivity(callIntent);
            }
        });
    }

}

Upvotes: 0

Views: 50

Answers (2)

Pankaj Nimgade
Pankaj Nimgade

Reputation: 4549

This May not directly answer your question but will help you looking at your code in OOP's way a little which will indeed help you further.

Make a class that will represent Hospital in your application.

/**
 * This is blue-print to create instance of Hospital
 * @author Pankaj Nimgade
 * */
public class Hospital {

    private String id;
    private String area_Name;
    private String hospital_Name;
    private String hospital_Phone;
    private String hospital_Address;

    /**
     * Have a empty constructor in case in future you want 
     * to implement parsing of the class'es object with some library (GSON/ Simple XML framework)
     * */
    public Hospital() {
        // TODO Auto-generated constructor stub
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getArea_Name() {
        return area_Name;
    }

    public void setArea_Name(String area_Name) {
        this.area_Name = area_Name;
    }

    public String getHospital_Name() {
        return hospital_Name;
    }

    public void setHospital_Name(String hospital_Name) {
        this.hospital_Name = hospital_Name;
    }

    public String getHospital_Phone() {
        return hospital_Phone;
    }

    public void setHospital_Phone(String hospital_Phone) {
        this.hospital_Phone = hospital_Phone;
    }

    public String getHospital_Address() {
        return hospital_Address;
    }

    public void setHospital_Address(String hospital_Address) {
        this.hospital_Address = hospital_Address;
    }


/**
     * this class overrides toString, i will explain wby
     * */
    @Override
    public String toString() {
        return hospital_Name;
    }
}

Populate your ArrayList like this

  JSONArray jsonArray = null;
        try {
            jsonArray = new JSONArray("your json array");
            ArrayList<Hospital> hospitals = new ArrayList<>();
            for (int i = 0; i < jsonArray.length(); i++) {
                Hospital hospital = new Hospital();
                JSONObject jsonObject =jsonArray.getJSONObject(i);
                hospital.setId(""+jsonObject.get("id"));
                hospital.setHospital_Name(""+jsonObject.get("hos_nam"));
                hospital.setArea_Name(""+jsonObject.get("area_nam"));
                hospital.setHospital_Phone(""+jsonObject.get("emar_amb_no"));
                hospital.setHospital_Address(""+jsonObject.get("hos_add"));
                hospitals.add(hospital);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

Once you have your List ready do this.

 ArrayAdapter myAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, hospitals);
        listView.setAdapter(myAdapter);

Now remember we have overriden the toString in Hospital class which returns hostpital name so you will have a normal listview showing your Hospital List

Kindly wait for further edit, i have to drink something,

what to do now

 listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Hospital hospital = (Hospital)listView.getItemAtPosition(position);
                Intent intent = new Intent(this, AmbulanceSingleActivity.class);
                intent.putExtra("id", hospital.getId());
                intent.putExtra("hos_nam", hospital.getId());
                intent.putExtra("area_nam", hospital.getId());
                intent.putExtra("emar_amb_no", hospital.getId());
                intent.putExtra("hos_add", hospital.getId());
                startActivity(intent);
            }
        });

if you want you can serialize Hospital object and attach it to the instance of Intent before launching next Activity.

This will help you get the hold of your Hospital object which would be a lot better than dealing with String individually

Upvotes: 1

Kostas Drak
Kostas Drak

Reputation: 3260

Since you only want to show hopital name in the ListView then all you have to do is to modify your listview_row_item.xml file to have only 1 TextView which will be the Hospital Name. Then you can send the data through Intent in the SingleActivity and then display them...

Upvotes: 0

Related Questions