Android Create A String[] From A Json Feed
i have a lazy list that loads in a list of images at the moment the urls are hard coded in a String[] and i'm wanting to load them via a json feed. so my question is how can i crea
Solution 1:
This is how I add values to a String[] using an ArrayList from a JSONObject. My example uses a JSONArray, but you can always change that to fit your code.
ArrayList<String> arrayName = newArrayList<String>();
ArrayList<String> arrayPicture = newArrayList<String>();
Bundle extras = getIntent().getExtras();
apiResponse = extras.getString("API_RESPONSE");
try {
JSONArrayJAFriends = newJSONArray(apiResponse);
for (int i = 0; i < JAFriends.length(); i++) {
json_data = JAFriends.getJSONObject(i);
if (json_data.has("name")) {
String getFriendName = json_data.getString("name").toUpperCase();
arrayName.add(getFriendName);
} else {
String getFriendName = null;
arrayName.add(getFriendName);
}
if (json_data.has("pic_square")) {
String getFriendPhoto = json_data.getString("pic_square");
arrayPicture.add(getFriendPhoto);
} else {
String getFriendPhoto = null;
arrayPicture.add(getFriendPhoto);
}
}
} catch (JSONException e) {
return;
}
stringName = newString[arrayName.size()];
stringName = arrayName.toArray(stringName);
stringPicture = newString[arrayPicture.size()];
stringPicture = arrayPicture.toArray(stringPicture);
listofFriends = (ListView)findViewById(R.id.list);
adapter = newFriendsAdapter(this, stringName, stringPicture);
listofFriends.setAdapter(adapter);
In he for
loop, using if statements to ensure no errors creep in, the returned values are added to their respective ArrayLists and 6 lines of code before the adapter
is set, the values from the ArrayLists are added to the String[].
Hope this helps solve your question.
Post a Comment for "Android Create A String[] From A Json Feed"