我正在使用毕加索在我的应用程序中加载图像。我从服务中获得图像的空值。如何处理空值。
我的代码:
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)
第一优先级 如果条件为 true,请执行以下操作:
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);
}
它会解决你的问题
更改条件顺序if
if(reviewdata.get(position).user.getPhotoUrl() == null || reviewdata.get(position).user.getPhotoUrl().isEmpty() )
试试这个:
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);
}
无需使用 Picasso 检查空值。毕加索足够聪明,它会处理空值。
Picasso.with(getApplicationContext()).load(reviewdata.get(position).user.getPhotoUrl()).placeholder(R.drawable.profile).into(viewHolder.user_image);}
如果 URL 为空或为空,则会显示placeholder
图像。