我正在使用Picasso将图像加载到应用程序中。我从服务获取图像的空值。如何处理空值。
我的代码:
if(reviewdata.get(position).user.getPhotoUrl().isEmpty() || reviewdata.get(position).user.getPhotoUrl() == null){
Picasso.with(getApplicationContext()).load(R.drawable.profile)
.into(viewHolder.user_image);
}else if(reviewdata.get(position).user.getPhotoUrl() != null){
Picasso.with(getApplicationContext()).load(reviewdata.get(position).user.getPhotoUrl()).placeholder(R.drawable.profile)
.into(viewHolder.user_image);}
错误:
10-04 08:42:43.653 23300-23300/ E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.restosapp.restoss, PID: 23300
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.isEmpty()' on a null object reference
at .listing.DetailpageActivtiy$Reviewpageadapter.onBindViewHolder(DetailpageActivtiy.java:1198)
at cooss.listing.DetailpageActivtiy$Reviewpageadapter.onBindViewHolder(DetailpageActivtiy.java:1172)
at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6673)
答案 0 :(得分:2)
第一个优先级如果条件为真,则执行以下操作:
if(reviewdata.get(position).user.getPhotoUrl()!=null && !reviewdata.get(position).user.getPhotoUrl().isEmpty())
{
Picasso.with(getApplicationContext()).load(reviewdata.get(position).user.getPhotoUrl()).placeholder(R.drawable.profile)
.into(viewHolder.user_image);}
}
else
{
Picasso.with(getApplicationContext()).load(R.drawable.profile)
.into(viewHolder.user_image);
}
它将解决您的问题
答案 1 :(得分:1)
在if
if(reviewdata.get(position).user.getPhotoUrl() == null || reviewdata.get(position).user.getPhotoUrl().isEmpty() )
答案 2 :(得分:0)
尝试一下:
public boolean isEmpty(String s) { return s.trim().equals("") || s == null || s.isEmpty() || s.equals("null"); }
if(!isEmpty(reviewdata.get(position).user.getPhotoUrl())){
Picasso.with(getApplicationContext()).load(reviewdata.get(position).user.getPhotoUrl()).placeholder(R.drawable.profile)
.into(viewHolder.user_image);
}
else{
Picasso.with(getApplicationContext()).load(R.drawable.profile)
.into(viewHolder.user_image);
}
答案 3 :(得分:0)
无需使用Picasso检查空值。毕加索足够聪明,它将处理空值。
Picasso.with(getApplicationContext()).load(reviewdata.get(position).user.getPhotoUrl()).placeholder(R.drawable.profile).into(viewHolder.user_image);}
如果URL为空或为空,它将显示placeholder
图片。