Search code examples
androidlistviewandroid-arrayadaptercustom-lists

Custom ListView Displaying Last value


I have a custom listView with 200 values coming from Cloud DB. All the values are received properly and added in ArrayList(hotelList). When I am passing to the ArrayList(hotelList) to Custom Adapter class, showing all the values as last element. Many stackOverflow questions found here related to this I tried them too. None worked for me. How should I fix this? The code is,

@Override
    protected void onPostExecute(String result) {
        try {
            Log.d("Inside Post", "message");
            root = new JSONObject(result);
            validation = root.getInt("response");
            message = root.getString("message");
            JSONArray data=root.getJSONArray("data");
            data.length();
            if(validation==1) {
                hgs=new HotelGetSetter();//Getting and setting class
                for(int i=0;i<data.length();i++){
                    hgs.setName(data.getJSONObject(i).getString("hotel_name"));
                    hgs.setPlace(data.getJSONObject(i).getString("city"));
                    hotelList.add(hgs);//While Debugging, all the 200 values from db received and added in the ArrayList(hotelList) values also there correctly
                }
                //But after the loop all the values here changed to last element value(debugged).
               mainMethod();
            }
        }
        catch (JSONException e) {
            e.printStackTrace();
    }
 }
 public void mainMethod(){
    HotelCustomAdapter hca=new HotelCustomAdapter(HotelMaster.this,hotelList);
    list_hotel.setAdapter(hca);
    //list_hotel.setAdapter(new HotelCustomAdapter(this, hotel_id1,hotel_name1,hotel_place1));
}

Solution

  • you initialize variable hgs=new HotelGetSetter(); out of for loop and then you are always editing the same instance