使用毕加索将图像加载到Recycler View中。回收者视图不显示

时间:2018-12-19 06:26:21

标签: android json parsing android-recyclerview picasso

我有一个解析JSON数据并将其显示在回收者视图中的应用程序。回收者视图中的每个项目都是Reps类的对象,并且包含在卡片布局中。当我仅尝试解析字符串变量时,代码可以正常工作。 enter image description here

当我尝试将Image URL解析为ImageView时,没有显示回收站视图,并且活动为空白。我正在使用Picasso将图像加载到适配器类中的onBinfViewHolder方法中。这是相关代码

代表:

public class Reps {
private String officeName;
private String officialName;
private String party;
private String photoUrl;

//continue to develop this with other values such as phone, photo, address etc.


public Reps(String officeName, String officialName, String party, String photoUrl) {
    this.officeName = officeName;
    this.officialName = officialName;
    this.party = party;
    this.photoUrl = photoUrl;
}



public Reps(String officeName, String officialName, String party) {
    this.officeName = officeName;
    this.officialName = officialName;
    this.party = party;
}

public Reps(String officeName) {
    this.officeName = officeName;
}

public Reps(String name, String party) {
    this.officialName = name;
    this.party = party;
}


public String getOfficeName() {
    return officeName;
}

public void setOfficeName(String officeName) {
    this.officeName = officeName;
}

public String getOfficialName() {
    return officialName;
}

public void setOfficialName(String officialName) {
    this.officialName = officialName;
}

public String getParty() {
    return party;
}

public void setParty(String party) {
    this.party = party;
}

public String getPhotoUrl() {
    return photoUrl;
}

public void setPhotoUrl(String photoUrl) {
    this.photoUrl = photoUrl;
}

}

RepRvAdapter:

public class RepRvAdapter extends 
RecyclerView.Adapter<RepRvAdapter.MyViewHolder> {

private Context context;
private List<Reps> repsList;
RequestOptions option;

public RepRvAdapter() {

}

public RepRvAdapter(List<Reps> repList, Context applicationContext) {
    this.repsList = repList;
    this.context = applicationContext;

}


@NonNull
@Override
public RepRvAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
    View view;
    LayoutInflater mInflater = LayoutInflater.from(context);
    view = mInflater.inflate(R.layout.card, viewGroup, false);         //Inflate view to card.xml
    return new MyViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull RepRvAdapter.MyViewHolder myViewHolder, int i) {
    myViewHolder.officeName.setText(repsList.get(i).getOfficeName());               //Display these three elements in the card view
    myViewHolder.officialName.setText(repsList.get(i).getOfficialName());
    myViewHolder.party.setText(repsList.get(i).getParty());
    //load image into card view
    Picasso.get()
            .load(repsList.get(i).getPhotoUrl())
            .centerCrop()
            .transform(new CircleTransform(50, 0))
            .fit()
            .into(myViewHolder.photoUrl);
}

@Override
public int getItemCount() {
    return repsList.size();
}

public static class MyViewHolder extends RecyclerView.ViewHolder {
    //Variables
    TextView officeName, officialName, party;         //Only the Referendum title and type will be in the recycler view
    ImageView photoUrl;
    public MyViewHolder(View itemView){
        super(itemView);
        officeName = itemView.findViewById(R.id.office_name);
        officialName = itemView.findViewById(R.id.official_name);
        party = itemView.findViewById(R.id.party);
        photoUrl = itemView.findViewById(R.id.photo_url);
    }
}

}

解析JSON数据的方法:

 //fetch json data from Civic API
private void getData(){
    final ProgressDialog progressDialog = new ProgressDialog(this);
    progressDialog.setMessage("Loading...");
    progressDialog.show();

    StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            progressDialog.dismiss();
            try{
                JSONObject jsonObject = new JSONObject(response);
                //first loop through offices array. Retrieve officeName value
                JSONArray officesArray = jsonObject.getJSONArray("offices");        //One array for offices
                JSONArray officialsArray = jsonObject.getJSONArray("officials");    //one array for officials
                for (int i = 0; i < officesArray.length(); i++){
                    JSONObject jsonOffices = officesArray.getJSONObject(i);
                    JSONObject jsonOfficials = officialsArray.getJSONObject(i);
                    Reps reps = new Reps (jsonOfficials.getString("name"),
                            jsonOfficials.getString("party"),
                            //jsonOfficials.getString("photoUrl")
                            jsonOffices.getString("name"));
                    repList.add(reps);
                }
                adapter = new RepRvAdapter(repList, getApplicationContext());
                myrv.setAdapter(adapter);
            }catch (JSONException e){
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("Volley", error.toString());
            progressDialog.dismiss();
        }
    });
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
}

现在,我有注释掉图像URL的代码行。取消注释该行后,将不再显示活动。如何获取要解析的图像URL并显示在ImageView中?我认为这可能与JSON数据有关。在JSON数组中,未设置所有的photoUrl字段。 API可能不会为数组中的每个代表返回图像数据,而“聚会”,“姓名”和“办公室”字段始终具有值。这可能会阻止回收器视图显示吗?这是相关的JSON数据块:

"officials": [
  {
   "name": "Donald J. Trump",
   "address": [
    {
     "line1": "The White House",
     "line2": "1600 Pennsylvania Avenue NW",
     "city": "Washington",
     "state": "DC",
     "zip": "20500"
    }
   ],
   "party": "Republican",
   "phones": [
    "(202) 456-1111"
   ],    
    "photoUrl":"https://www.whitehouse.gov/sites/whitehouse.gov/files/images/45/PE%20Color.jpg",
   "channels": [
    {
     "type": "GooglePlus",
     "id": "+whitehouse"
    },
    {
     "type": "Facebook",
     "id": "whitehouse"
    },
    {
     "type": "Twitter",
     "id": "potus"
    },
    {
     "type": "YouTube",
     "id": "whitehouse"
    }
   ]
  },
  {
   "name": "Mike Pence",
   "address": [
    {
     "line1": "The White House",
     "line2": "1600 Pennsylvania Avenue NW",
     "city": "Washington",
     "state": "DC",
     "zip": "20500"
    }
   ],
   "party": "Republican",
   "phones": [
    "(202) 456-1111"
   ],
   "photoUrl":"https://www.whitehouse.gov/sites/whitehouse.gov/files/images/45/VPE%20Color.jpg",
   "channels": [
    {
     "type": "GooglePlus",
     "id": "+whitehouse"
    },
    {
     "type": "Facebook",
     "id": "whitehouse"
    },
    {
     "type": "Twitter",
     "id": "VP"
    }
   ]
  },
  {
   "name": "Dianne Feinstein",
   "address": [
    {
     "line1": "331 Hart Senate Office Building",
     "city": "Washington",
     "state": "DC",
     "zip": "20510"
    }
   ],
   "party": "Democratic",
   "phones": [
    "(202) 224-3841"
   ],
   "photoUrl": "http://bioguide.congress.gov/bioguide/photo/F/F000062.jpg",
   "channels": [
    {
     "type": "Facebook",
     "id": "SenatorFeinstein"
    },
    {
     "type": "Twitter",
     "id": "SenFeinstein"
    },
    {
     "type": "YouTube",
     "id": "SenatorFeinstein"
    }
   ]
  },
  {
   "name": "Kamala D. Harris",
   "address": [
    {
     "line1": "112 Hart Senate Office Building",
     "city": "Washington",
     "state": "DC",
     "zip": "20510"
    }
   ],
   "party": "Democratic",
   "phones": [
    "(202) 224-3553"
   ],
   "channels": [
    {
     "type": "Twitter",
     "id": "KamalaHarris"
    },
    {
     "type": "YouTube",
     "id": "UC0XBsJpPhOLg0k4x9ZwrWzw"
    }
   ]

如您所见,所有代表都有姓名,政党和职务,但并非所有代表都有图像URL。日志猫就此返回它。 enter image description here

我愿意尝试其他图书馆。让我知道是否需要查看更多代码。感谢您的帮助!

我向jsonParse方法添加了以下条件,以说明没有photoUrl字段的对象。

try{
                JSONObject jsonObject = new JSONObject(response);
                //first loop through offices array. Retrieve officeName value
                JSONArray officesArray = jsonObject.getJSONArray("offices");        //One array for offices
                JSONArray officialsArray = jsonObject.getJSONArray("officials");    //one array for officials
                for (int i = 0; i < officesArray.length(); i++){
                    JSONObject jsonOffices = officesArray.getJSONObject(i);
                    JSONObject jsonOfficials = officialsArray.getJSONObject(i);
                   if(jsonOfficials.has("photoUrl")){
                        Reps reps = new Reps (jsonOfficials.getString("name"),
                                jsonOfficials.getString("party"),
                                jsonOfficials.getString("photoUrl"),
                                jsonOffices.getString("name"));
                        repList.add(reps);
                    }else{
                       Reps reps = new Reps(jsonOfficials.getString("name"),
                               jsonOfficials.getString("party"),
                               jsonOffices.getString("name"));
                       repList.add(reps);
                   }
                }
                adapter = new RepRvAdapter(repList, getApplicationContext());
                myrv.setAdapter(adapter);

使用此代码,显示回收者视图,但是图像URL字符串显示在officeName文本视图中,而不是ImageView中的图像。 enter image description here

由于最后一位官员没有可用的图像,因此其数据可以正确显示。

2 个答案:

答案 0 :(得分:1)

问题#1:发生JSON异常当您尝试解析“ photoUrl”时,由于在最后一个正式对象中不存在名为“ photoUrl”的字段。

{
      "name": "Kamala D. Harris",
      "address": [
        {
          "line1": "112 Hart Senate Office Building",
          "city": "Washington",
          "state": "DC",
          "zip": "20510"
        }
      ],
      "party": "Democratic",
      "phones": [
        "(202) 224-3553"
      ],
      "channels": [
        {
          "type": "Twitter",
          "id": "KamalaHarris"
        },
        {
          "type": "YouTube",
          "id": "UC0XBsJpPhOLg0k4x9ZwrWzw"
        }
      ]
    }

解决方案#1::只需将代码放入类似的条件内即可:

String photoUrl = "";
if (jsonOfficials.has("photoUrl")) {
   photoUrl = jsonOfficials.getString("photoUrl");
}

问题2:,请检查“ Reps”类的第一个构造函数。在这里,您将“ photoUrl”字段作为第四个参数,但是当您创建“ Reps”类的对象时,您会将“ photoUrl”字段作为第三个参数。

解决方案2:

Reps reps = new Reps (jsonOfficials.getString("name"),
    jsonOfficials.getString("party"),
    jsonOffices.getString("name"),
    jsonOfficials.getString("photoUrl"));

答案 1 :(得分:0)

JSON响应中有一个错误。试试这个

    [{
        "name": "Donald J. Trump",
        "address": [{
            "line1": "The White House",
            "line2": "1600 Pennsylvania Avenue NW",
            "city": "Washington",
            "state": "DC",
            "zip": "20500"
        }],
        "party": "Republican",
        "phones": [
            "(202) 456-1111"
        ],
        "photoUrl": "https://www.whitehouse.gov/sites/whitehouse.gov/files/images/45/PE%20Color.jpg",
        "channels": [{
                "type": "GooglePlus",
                "id": "+whitehouse"
            },
            {
                "type": "Facebook",
                "id": "whitehouse"
            },
            {
                "type": "Twitter",
                "id": "potus"
            },
            {
                "type": "YouTube",
                "id": "whitehouse"
            }
        ]
    },
{
   "name": "Mike Pence",
   "address": [
    {
     "line1": "The White House",
     "line2": "1600 Pennsylvania Avenue NW",
     "city": "Washington",
     "state": "DC",
     "zip": "20500"
    }
   ],
   "party": "Republican",
   "phones": [
    "(202) 456-1111"
   ],
   "photoUrl":"https://www.whitehouse.gov/sites/whitehouse.gov/files/images/45/VPE%20Color.jpg",
   "channels": [
    {
     "type": "GooglePlus",
     "id": "+whitehouse"
    },
    {
     "type": "Facebook",
     "id": "whitehouse"
    },
    {
     "type": "Twitter",
     "id": "VP"
    }
   ]
  },
  {
   "name": "Dianne Feinstein",
   "address": [
    {
     "line1": "331 Hart Senate Office Building",
     "city": "Washington",
     "state": "DC",
     "zip": "20510"
    }
   ],
   "party": "Democratic",
   "phones": [
    "(202) 224-3841"
   ],
   "photoUrl": "http://bioguide.congress.gov/bioguide/photo/F/F000062.jpg",
   "channels": [
    {
     "type": "Facebook",
     "id": "SenatorFeinstein"
    },
    {
     "type": "Twitter",
     "id": "SenFeinstein"
    },
    {
     "type": "YouTube",
     "id": "SenatorFeinstein"
    }
   ]
  },
  {
   "name": "Kamala D. Harris",
   "address": [
    {
     "line1": "112 Hart Senate Office Building",
     "city": "Washington",
     "state": "DC",
     "zip": "20510"
    }
   ],
   "party": "Democratic",
   "phones": [
    "(202) 224-3553"
   ],
   "channels": [
    {
     "type": "Twitter",
     "id": "KamalaHarris"
    },
    {
     "type": "YouTube",
     "id": "UC0XBsJpPhOLg0k4x9ZwrWzw"
    }
]
}
]