Reputation: 111
I am passing data to a recycler view using JSON, which works perfectly.
The problem is this, I want to alter the fetched json data. Let's say the user doesn't upload a profile image, that means the database field for image would be blank and our json wont parse any data for data.
So I want to set to a deafault url string if image == null
Heres what ive tried
//traversing through all the object
for (int i = 0; i < array.length(); i++) {
//getting product object from json array
JSONObject allTime = array.getJSONObject(i);
//adding the product to product list
allTimeEarnersList.add(new LeaderProfile(
allTime.getInt("id"),
allTime.getString("image"),
allTime.getString("username"),
allTime.getInt("earnings")
));
//My attempt to set a default value
if(allTime.getString("image").equals(null)){
allTime.put("image", "https://10.0.0.0/uploads/blank.png");
}
}
This doesn't work, it doesn't alter the output at all.
It is obvious i'm not doing this right.
Please how can I go about this? what is the best way to achieve this?
Upvotes: 1
Views: 5225
Reputation: 1028
You can just use get
and the elvis operator ?:
.
The get will return back an Any
object, which we optionally cast as a String. The elvis operator will ensure any null value will be defaulted to string parameter.
allTime.get("image") as? String ?: "https://10.0.0.0/uploads/blank.png"`
Upvotes: -1
Reputation: 761
You can use optString
allTime.optString("image", "https://10.0.0.0/uploads/blank.png")
The optString method is used to retrieve the value for the non-existing key with a default value, which is returned instead of null.
Upvotes: 1
Reputation: 2799
Try this code block
if(allTime.getString("image") != null){
//set imageview glide or picasso
}else{
//set image view glide or picasso but R.drawable.empty_avatar
}
Upvotes: -1
Reputation: 1205
You aren't putting the value back into the object after you use the .put in the JSON, to avoid blanks/null in an object it's recommended to have a default value in case of nulls in your initializer.
public LeaderProfile(int id, String image, String username, int earnings) {
this.id = id;
if(image.equals("") || image.equals(null) ){
this.image = "defaulturl.png";
}else{
this.image = image;
}
this.username = username;
this.earnings = earnings;
}
Upvotes: 0