简体   繁体   中英

HashMap data to listView using custom adapter

I am new to Android development and am trying to get JSON data including two text pieces of data and one image piece of data into LISTVIEW and NOT imageView. I came to realize all data is being stored in caridList which is a HashMap.

Any suggestions as to how to fix these errors along with a description are greatly appreciated. Thanks.

You made few mistakes in this snippet.

First there is no need to use Map for storing your data

You should create POJO or other object for storing your data.

So create class called

public class CarData {

    public String carId;
    public String carVin;
    public String modelImg;

    public CarData(String carId, String carVin, String modelImg) {
        this.carId = carId;
        this.carVin = carVin;
        this.modelImg = modelImg;
    }
}

Next instead of having field:

//Hashmap for ListView
ArrayList<HashMap<String, Object>> caridList;

use

List<CarData> carDataList = new ArrayList<CarData>();

in instead of putting Strings to Map, you should create new and add to list 而不是将Strings放入Map中,您应该创建新的并将其添加到列表中

CarData carData = new CarData(car_id, car_vin, model_img);
carDataList.add(carData);

Your ArrayAdapter class declaration should look like:

public class CustomListViewAdapter extends ArrayAdapter<CarData> 

Keep your data into list:

private List<CarData> list;

In :

CarData item = getItem(position);

....

holder.car_id.setText(item.carId);
holder.car_vin.setText(item.carVin);

To load image into ImageView check Picasso or Glide

EDIT

Replace this:

  for (int i = 0; i < carid.length(); i++) {
      JSONObject c = carid.getJSONObject(i);
      String car_id = c.getString(TAG_CARID);
      Log.d("car_id", car_id);

      String car_vin = c.getString(TAG_CARVIN);
      Log.d("car_vin", car_vin);

      String model_img = c.getString(TAG_IMG);
      Log.d("model_img", model_img);

      //Hashmap for single match
      HashMap<String, Object> matchGetCars = new HashMap<String, Object>();
      //Log.v("Item 3", item.toString());
      //Adds each child node to HashMap key => value
      matchGetCars.put(TAG_CARID, car_id);
      matchGetCars.put(TAG_CARVIN, car_vin);
      matchGetCars.put(TAG_IMG, model_img);
      caridList.add(matchGetCars);
      Log.v("CaridList", caridList.toString());
}

with this:

for (int i = 0; i < carid.length(); i++) {
    JSONObject c = carid.getJSONObject(i);
    String car_id = c.getString(TAG_CARID);
    String car_vin = c.getString(TAG_CARVIN);
    String model_img = c.getString(TAG_IMG);
    CarData carData = new CarData(car_id, car_vin, model_img);
    carDataList.add(carData);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM