我会从我的api json响应中创建一些listview,但是我在代码中停留了此LinkedTreeMap错误。谁能帮我解决这个问题?
public class KategoriListAdapter extends BaseAdapter {
Context context;
ArrayList<Barang> barang;
public KategoriListAdapter(Context context, ArrayList<Barang> barang) {
this.context = context;
this.barang = barang;
}
@Override
public int getCount() {
return barang.size();
}
@Override
public Barang getItem(int i) {
return this.barang.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@TargetApi(Build.VERSION_CODES.KITKAT)
@Override
public View getView(final int i, View view, ViewGroup viewGroup) {
if (view == null) {
view = LayoutInflater.from(context).inflate(R.layout.custom_list_view_kategori, viewGroup, false);
}
TextView tvNama = (TextView) view.findViewById(R.id.tv_nama);
TextView tvHarga = (TextView) view.findViewById(R.id.tv_harga);
TextView tvUsername = (TextView) view.findViewById(R.id.tv_username);
Object getrow = this.barang.get(i);
LinkedTreeMap<Object, Object> rowmap = (LinkedTreeMap) getrow;
String nama = rowmap.get("nama").toString();
String harga = rowmap.get("harga").toString();
String username = rowmap.get("username").toString();
tvNama.setText(nama);
tvHarga.setText(harga);
tvUsername.setText(username);
return view;
}
}
public class Barang {
@SerializedName("id")
@Expose
private Integer id;
@SerializedName("username")
@Expose
private String username;
@SerializedName("nama")
@Expose
private String nama;
@SerializedName("harga")
@Expose
private String harga;
@SerializedName("gambar")
@Expose
private String gambar;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getNama() {
return nama;
}
public void setNama(String nama) {
this.nama = nama;
}
public String getHarga() {
return harga;
}
public void setHarga(String harga) {
this.harga = harga;
}
public String getGambar() {
return gambar;
}
public void setGambar(String gambar) {
this.gambar = gambar;
}
}
我运行活动时的日志结果是
java.lang.ClassCastException: com.example.barangkoz.model.Barang cannot be
cast to com.google.gson.internal.LinkedTreeMap
at com.example.barangkoz.activities.KategoriListAdapter.getView(KategoriListAdapter.java:57)`
最佳答案
您正在适配器构造函数中传递“ Barang”对象的ArrayList,这意味着您的适配器中已经有了对象Barang的列表,您可以直接使用它而无需转换为TreeMap。
在适配器的getView方法中更改此
Object getrow = this.barang.get(i);
至
Barang barang = barang.get(i);
它将使Barang对象位于Barang列表中i的位置。
这样您就可以使用在对象Barang内部定义的getters方法从该对象获取数据。
String harga = barang.getHarga();
String nama = barang.getNama();
String userName = barang.getUsername();
并将其设置为您的TextView或
您可以将数据直接从Barang对象设置为TextView(在设置为TextView之前无需执行其他步骤即可将其设置为变量),就像这样
tvHarga.setText(barang.getHarga());
tvNama.setText(barang.getNama());
tvUsername.setText(barang.getUsername());