Arash Fathi
Arash Fathi

Reputation: 13

android-Get id of item in listView

i'm reading data from mysql with JSON and php and put them in a listView with AsyncTask and i'm trying to get item id with setOnItemClickListener and toast it but it shows me the wrong id for example when i click on item id 4 it shows me 2 thanks if you help me.

public class ActivityList extends AppCompatActivity {

private String TAG = ActivityList.class.getSimpleName();

private ProgressDialog pDialog;
private ListView lv;

private String[] items ;

// URL to get contacts JSON
private static String url = "My URL";

ArrayList<HashMap<String, String>> contactList;


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

    contactList = new ArrayList<>();

    lv = (ListView) findViewById(R.id.listItems);

    new GetContacts().execute();
}

/**
 * Async task class to get json by making HTTP call
 */
private class GetContacts extends AsyncTask<Void, Void, Void> {

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

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        HttpHandler sh = new HttpHandler();

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

        Log.e(TAG, "Response from url: " + jsonStr);

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

                // Getting JSON Array node
                JSONArray contacts = jsonObj.getJSONArray("houseDB");

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

                    String name = c.getString("name");
                    String address = c.getString("address");
                    String telephone = c.getString("telephone");
                    String option = c.getString("option");
                    String ID = c.getString("ID");

                    // tmp hash map for single contact
                    HashMap<String, String> contact = new HashMap<>();

                    // adding each child node to HashMap key => value
                    contact.put("name", name);
                    contact.put("address", address);
                    contact.put("telephone", telephone);
                    contact.put("option", option);
                    contact.put("ID", ID);

                    //put id row in array
                    items = new String[]{ID};

                    // adding contact to contact list
                    contactList.add(contact);
                }
            } catch (final JSONException e) {
                Log.e(TAG, "Json parsing error: " + e.getMessage());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Json parsing error: " + e.getMessage(),
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }
        } else {
            Log.e(TAG, "Couldn't get json from server.");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),
                            "Couldn't get json from server. Check LogCat for possible errors!",
                            Toast.LENGTH_LONG)
                            .show();
                }
            });



        }

        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(
                ActivityList.this, contactList,
                R.layout.list_item, new String[]{"name", "address",
                "telephone", "option", "ID"}, new int[]{R.id.txtName,
                R.id.txtAddress, R.id.txtTelephone, R.id.txtOption, R.id.txtID});

        lv.setAdapter(adapter);

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

                //get item id
                TextView itemID = (TextView) findViewById(R.id.txtID);
                String text = itemID.getText().toString();
                Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();

            }
        });

    }

}

}

Upvotes: 1

Views: 2813

Answers (4)

杜咸鱼
杜咸鱼

Reputation: 19

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

            //get item id
            TextView itemID = (TextView) parent.findViewById(R.id.txtID);
            String text = itemID.getText().toString();
            Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();

        }
    });

Upvotes: 0

phpdroid
phpdroid

Reputation: 1663

use like this

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

            //get item id
            TextView ids = (TextView) findViewById(R.id.txtID);
            Contactlistyourclass co=new Contactlistyourclass();
            co=contactList.get(i)
            String d = co.getId(); // or what ever you have in your contactlist class as getter method!
            Toast.makeText(getApplicationContext(), d, Toast.LENGTH_SHORT).show();

        }
    });

}

Upvotes: 0

Samuel Robert
Samuel Robert

Reputation: 11062

Since txtID will have several views associated with the adapter, You have to find the txtID of the currently clicked item.

TextView itemID = (TextView) view.findViewById(R.id.txtID);

Upvotes: 0

Hareshkumar Chhelana
Hareshkumar Chhelana

Reputation: 24848

Try to get id from Contact HashMap using list item position of Contact List instead of getting id from TextView text as below :

lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
      @Override
      public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Toast.makeText(getApplicationContext(), contactList.get(position).get("ID"), Toast.LENGTH_SHORT).show();
      }
 });

Upvotes: 2

Related Questions