自定义 ListView 显示最后一个值

Custom ListView Displaying Last value

我有一个自定义 listView,其中包含来自 Cloud DB 的 200 个值。所有值都被正确接收并添加到 ArrayList(hotelList) 中。当我将 ArrayList(hotelList) 传递给自定义适配器 class 时,将所有值显示为最后一个元素。在这里发现的许多 Whosebug 问题都与此相关,我也试过了。 None 对我有用。我应该如何解决这个问题? 代码是,

@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));
}

您正在通过循环更改同一对象 hsg 的值,而不是为每组值创建不同的对象。因此 200 个相同的对象。

只需将 hgs=new HotelGetSetter(); 移动到循环中即可。

你初始化变量 hgs=new HotelGetSetter();退出 for 循环,然后你总是在编辑同一个实例