我正在从网络中获取数据,并根据如下所示的响应创建了我的模型类:
{"batch_details":[{"batch_name":"batch ","batch_id":"49"},{"batch_name":"batch one","batch_id":"50"}],"status":1,"message":"success"}
我的活动有一个回收站视图,并且设置如下(仅响应部分):
if (response != null) {
Log.d(TAG, "Batches Response:\t" + response.toString());
try {
JSONObject object = new JSONObject(response.toString());
message = object.getString("message");
JSONArray array = object.getJSONArray("batch_details");
for (int m = 0; m < array.length(); m++) {
JSONObject jsonObject = array.getJSONObject(m);
name_batch = jsonObject.getString("batch_name");
id_batch = jsonObject.getString("batch_id");
batch = new Batch();
batch.setBatchId(id_batch);
batch.setBatchName(name_batch);
batch.save();
Log.d(TAG, "BN local:\t" + batch.getBatchName() + "BN n/w:\t" + name_batch); //NW is from network that is jsonObj whereas local is from model getters
list.add(batch);
BatchFooter footer = new BatchFooter();
list.add(footer.getButton());
Log.d(TAG, "List size:\t" + list.size());
adapter = new BatchAdapter(ChooseBatchActivity.this, list);
adapter.setMessageValue(message);
batchRV.setAdapter(adapter);
在适配器的onBindViewHolder
中,我试图从模型类中获取值并绑定到ui元素,如下所示:
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof BatchItemsViewHolder){
BatchItemsViewHolder viewHolder = (BatchItemsViewHolder) holder;
final Batch batch = (Batch) itemsList.get(position);
viewHolder.batchNameTV.setText(batch.getBatchName());
}
}
但是抛出NPE:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String sportsapp.sashi.in.sportsapp.models.app.Batch.getBatchName()' on a null object reference
at sportsapp.sashi.in.sportsapp.adapters.BatchAdapter.onBindViewHolder(BatchAdapter.java:60)
at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6673)
at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6714)
at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5647)
有人可以帮助我了解为什么现在不起作用。我已经做过几次了,并且有效,问题仅在于模型类而不是recyclerview。谢谢。
我已经检查了batch.getBatchName()
的值,您可以在记录它的行中看到,即使在设置了响应值后,它仍然为null。这说明了NPE,但没有解决方法。