Search code examples
androidlistviewonitemclicklisteneronitemclick

Android: OnItemClickListener returns the value of the last item


the code bellow was working so fine with me but now i don't know what's wrong with it!! whenever i click to an item it put the value of the last item to the intent! any idea?

 protected void onPostExecute(List<HashMap<String, String>> result) {
        customList=new ArrayList<>();
        for (int i = 0; i < result.size(); i++) {
            HashMap<String, String> appointement = result.get(i);
            String fromT = appointement.get("fromT");
            String toT = appointement.get("toT");
            String date = appointement.get("date");
            //int doctorid=Integer.parseInt(id.replaceAll("[\\D]",""));
            addAvailableAppoint(fromT, toT, date);
        }
        updateListView();
    }
}

private void addAvailableAppoint(final String fromT, final String toT, final String date) {
    customList.add(new AvailabilityList(fromT));
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Log.i("items", "fromt " + fromT + "tot: " + toT);
            Intent intent = new Intent(MakeAppointementActivity.this, AppointementActivity.class);
            intent.putExtra("Doctor's name", DoctorName);
            intent.putExtra("Doctor's infos", DoctorInfos);
            intent.putExtra("fromT", fromT);
            intent.putExtra("toT", toT);
            intent.putExtra("date", date);
            startActivity(intent);
        }
    });

}

// split new function for update listview
private void updateListView(){
    ArrayAdapter adapter=new DoctorAvailabilityAdapter(MakeAppointementActivity.this,R.layout.list_items,customList);
    adapter.notifyDataSetChanged();
    lv.setAdapter(adapter);

Solution

  • 1) You don't need to set the click listener for each new item in your list. Just set it once, outside the for-loop.

    2) Try to use a Model class for your adapter that contains all the data: fromT , toT and date. Because as i see, your AvailabilityList contains only fromT.

    3) As mentioned in @CommonsWare answer, in onItemClick try to find the appropriate object using position or id in parameters.

    eg:

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
           AvailabilityList item = (AvailabilityList)parent.getItem(position);
           //Then from your item you can get the data: fromT , toT and date
        }