i use this json url : https://www.theaudiodb.com/api/v1/json/1/search.php?s=coldplay
{
"artists": [
{
"idArtist": "111239",
"strArtist": "Coldplay",
"strArtistStripped": null,
"strArtistAlternate": "",
"strLabel": "Parlophone",
"idLabel": "45114",
"intFormedYear": "1996",
"intBornYear": "1996",
"intDiedYear": null,
"strDisbanded": null,
"strStyle": "Rock/Pop",
"strGenre": "Alternative Rock",
etc
}
and this is my android java code :
void syncToUrl() {
AsyncHttpClient client = new AsyncHttpClient();
String url = "https://www.theaudiodb.com/api/v1/json/1/search.php?s=coldplay";
client.get(url, new TextHttpResponseHandler() {
@Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
@Override
public void onSuccess(int statusCode, Header[] headers, String responseString) {
parseAndShow(responseString);
}
});
}
void parseAndShow(String responce) {
try {
JSONObject artistBio = new JSONObject(responce);
artistNickname.setText(artistBio.getString("strArtist"));
} catch (Exception e) {
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_SHORT).show();
Error.setText(e.toString());
}
}
But I still get this Error: org.json.jsonexception no value for strArtist.
The strArtist has this value "Coldplay", but why do I get this error?
You can get the value of strArtist
as follows:
JSONObject artistBio = new JSONObject(responce);
JSONArray artists = artistBio.getJSONArray("artists");
for (int i=0; i < artists.length(); i++) {
JSONObject object = artists.getJSONObject(i);
String name = actor.getString("strArtist");
artistNickname.setText(artistBio.getString("strArtist"));
}
EDIT
Since your json has only one object inside the array, you can skip the for loop implementation and directly use as follows:
JSONObject object = artists.getJSONObject(0);
String name = actor.getString("strArtist");
artistNickname.setText(artistBio.getString("strArtist"));