我正在使用Picasso在我的Android App中显示来自服务器的图像。我从服务器获取5个图像URL(HTTP形式)并将其存储在String值中。如果我向Picasso(.jpg形式)发送正确的链接,正确运行并在imageview中显示我的图像,如果以(.pdf格式)发送错误的链接,则在Image View中显示错误,但是当我从服务器传递null值或空值以字符串显示时,我的应用程序崩溃了,如果即使它的值为null或为空,也要先声明该语句,否则else语句未运行,我应该在代码中更新什么,以便从服务器获取null值时,我的imageview应该显示,并且错误和文本视图的值也应该更改。
//仅在我的If / Else开头的代码:
if (image_fourth != null && image_fourth != ""){
Picasso.get().load(image_fourth).resize(200, 200).placeholder(R.drawable.placeholder).error(R.drawable.error).into(image1);
image1.setVisibility(View.VISIBLE);
buttons.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (image_second == null){
image_2t.setText("Image Not Found");
image_2t.setVisibility(View.GONE);
}
else if (image_second != null){
Picasso.get().load(image_second).resize(200, 200).placeholder(R.drawable.placeholder).error(R.drawable.error).into(image2);
image2.setVisibility(View.VISIBLE);
image_2t.setText("Image 2");
image_2t.setVisibility(View.VISIBLE);
}
}
});
}
else{
image_1t.setText("Image Not Found");
}
您可以尝试反转if / else语句。据我所知,毕加索不能在load()中使用空字符串或空字符串。在您的情况下,如果字符串/ URL源为null,则if语句可以覆盖您可以加载占位符:
if (url == null || url.isEmpty()) {
Picasso.with(context).load(placeholder).transform(transformation).into(this)
} else {
Picasso.with(context).load(url).error(placeholder).transform(transformation)
.placeholder(placeholder).into(this)
}
另一种选择可能是保持if语句不变,但是将其添加到else语句中:
else
image_fourth.setImageResources(R.mipmap.ic_launcher);
我已经对Glide使用了类似的技术。那对我有用。有关更多信息,您可以检查以下stackoverflow答案:Picasso doesn't tolerate empty String URL?