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));
}
-
I'm honestly not understanding your question, but looking at your code it looks strange to me that you are building your adapter in post execute. You should build outside and in post execute just invoke adapter.notifyDataSetChanged for having new items on bottom of the list.andrea.petreri– andrea.petreri2016年01月23日 12:26:14 +00:00Commented Jan 23, 2016 at 12:26
-
@thetonrifles, Please check the question once. I added comments in the code. After the for loop the (ArrayList<HotelGetSetter> hotelList) has the last value for data.length() times.Abish R– Abish R2016年01月23日 12:37:10 +00:00Commented Jan 23, 2016 at 12:37
-
you initialize variable hgs=new HotelGetSetter(); out of for loop and then you are always editing the same instance.andrea.petreri– andrea.petreri2016年01月23日 12:42:56 +00:00Commented Jan 23, 2016 at 12:42
2 Answers 2
you initialize variable hgs=new HotelGetSetter(); out of for loop and then you are always editing the same instance
1 Comment
You are changing the values for the same object hsg
through the loop instead of creating different objects for each set of values. Therefore the 200 same objects.
Just move the hgs=new HotelGetSetter();
into the loop and it should work.
Comments
Explore related questions
See similar questions with these tags.