How to fetch JSONArray values - android

In my program, I am able to fetch all my text. But In my JSOn in a JSON Array there is another JSONArray which have image url. I am getting all my URL in JSON Array when I am using
JSONArray attachments = post.getJSONArray("itemimage");
but when loop is finished, I am getting nothing in my response. How can I replace my ImageView with URLs which is store in attatchment. My Code is here
private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONArray posts = response.optJSONArray("items");
GridItem item;
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.optJSONObject(i);
String title = post.optString("itemname");
item = new GridItem();
item.setTitle(title);
JSONArray attachments = post.getJSONArray("itemimage");
if (null != attachments && attachments.length() > 0) {
JSONObject attachment = attachments.getJSONObject(0);
if (attachment != null)
item.setImage(attachment.getString(""));
}
mGridData.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}

Um,i am 2 mins late post it out...cuz writing the demo for u.
The parse method you need is below,and you can use framework like Universal Image Loader to load the url to your imageView.
private String parseaaa(String jsonString) {
String imgUrl = "";
try {
JSONObject mJsonObject = new JSONObject(jsonString);
JSONArray mArray = mJsonObject.getJSONArray("items");
for (int i = 0; i < mArray.length(); i++) {
JSONObject object=mArray.getJSONObject(i);
imgUrl+=object.getString("itemimage")+"\n";
Log.i(TAG, imgUrl);
}
} catch (Exception e) {
// TODO: handle exception
}
return imgUrl;
}
BTW,just use JSONArray to load things between [] and JSONObject to load the obj... It's easy to do.

As I can see your JSON you should get JSONException at
JSONObject attachment = attachments.getJSONObject(0);
because your are creating object which is not present there, So I would suggest to simply extract String from your JSONArray and do your setImage stuff..
if (null != attachments && attachments.length() > 0) {
String image= (String) attachments.get(0);
//--- set your image here--//
}

Related

why can't I parsing value 'fields' in my code?

When I run my app, In logcat, "Problem parsing the earthquake Json results
org.json.JSONException: No value for fields"
Could you check my JSON code..? I'm beginner of JSON Parsing, So I searched a lot inf But I'm not sure about my code.
public class Utils {
private static List<News> extractFromJson(String newsJSON) {
if (TextUtils.isEmpty(newsJSON)) {
return null;
}
List<News> news = new ArrayList<>();
try {
// Create a JSONObject from the JSON response string
JSONObject baseJsonResponse = new JSONObject(newsJSON);
JSONObject response = baseJsonResponse.getJSONObject("response");
JSONArray jsonArray = response.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject currentNews = jsonArray.getJSONObject(i);
JSONObject fields = currentNews.getJSONObject("fields");
Drawable thumbnail = LoadImageFromUrl (fields.getString("thumbnail"));
String section = currentNews.getString("sectionName");
String title = currentNews.getString("webTitle");
String url = currentNews.getString("webUrl");
String date = currentNews.getString("webPublicationDate");
news.add(new News( section, title, url, date,thumbnail));
}
return news;
} catch (JSONException e) {
Log.e("Utils", "Problem parsing the news Json results", e);
}
return null;
}
private static Drawable LoadImageFromUrl(String imageurl) {
Drawable drawable = null;
InputStream inputStream = null;
try {
inputStream = new URL(imageurl).openStream();
drawable = Drawable.createFromStream(inputStream, null);
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return drawable;
}
}
Try this to validate
Problem occur may be you dont have a field jsonobject in your json list. It may be not present in the some of other jsonobjects. So check if jsonobject has actual field jsonobject before parsing.
Use this condition whenever your json value might give null sometimes.
if(currentNews.has("fields"))
{
JSONObject fields = currentNews.getJSONObject("fields");
}
else
{
Log.d("JSON_TAG","NO FIELD JSON OBJECT");
}

How to parse a JSONArray and assign it to different TextViews?

I have a JSONArray and when I try to parse it, an NPE shows and the logcat shows W/System.err: org.json.JSONException: Value at 0 is null. Please help. I have provided my codes below.
JSON Array
[
{
"student_number":"201411870",
"full_name":"Miranda , Andrew Matthew Matera",
"year":"4",
"course":"BSIT"
}
]
Code Snippet
ArrayList<User> userArrayList = new JsonConverter<User>().toArrayList(response, User.class);
JSONArray jsonArray = new JSONArray(userArrayList);
try {
int regStudentNumber = jsonArray.getJSONObject(0).getInt("student_number");
String regFullName = jsonArray.getJSONObject(1).getString("full_name");
int regYear = jsonArray.getJSONObject(2).getInt("year");
String regCourse = jsonArray.getJSONObject(3).getString("course");
tvStudentNumber.setText(String.valueOf(regStudentNumber));
tvFullName.setText(regFullName);
tvYear.setText(String.valueOf(regYear));
tvCourse.setText(regCourse);
} catch (JSONException e) {
e.printStackTrace();
}
Solved it on my own. Sorry for the unclear question.
try {
JSONArray jsonArray = new JSONArray(response);
if(jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int regStudentNumber = jsonObject.getInt("student_number");
String regFullName = jsonObject.getString("full_name");
int regYear = jsonObject.getInt("year");
String regCourse = jsonObject.getString("course");
tvStudentNumber.setText(String.valueOf(regStudentNumber));
tvFullName.setText(regFullName);
tvYear.setText(String.valueOf(regYear));
tvCourse.setText(regCourse);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
First of all parse JSON array to object to make clear it is for a particular value then fetch things from it based on need.
To parse json array to object use code
try {
JSONArray jsonArray = new JSONArray(response);
if(jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
}
}
} catch (JSONException e) {
e.printStackTrace();
}

Regd : getting value from json url

I want to get the id ^& content value in http://rest-service.guides.spring.io/greeting
What i tried is,
try {
JSONObject jsonObj = new JSONObject(parsingUrl);
// If you have array
JSONArray resultArray = jsonObj.getJSONArray("id"); // Here you will get the Array
// Iterate the loop
for (int i = 0; i < resultArray.length(); i++) {
// get value with the NODE key
JSONObject obj = resultArray.getJSONObject(i);
String name = obj.getString("content");
}
// If you have object
//String result1 = jsonObj.getString("result");
} catch (Exception e) {
e.printStackTrace();
}
Thanks
The url that your mentioned dont have json arrays, parsing will be like
try {
JSONObject jsonObj = new JSONObject(resultfromUrl);
int id = jsonObj.getInt("id");
String name = jsonObj.getString("content");
} catch (JSONException e) {
e.printStackTrace();
}

Parsing images in Json

I am trying to parse Json data from this link a link
And I parse all of it but now I want to parse images. When I try to parse it I am parsing all images in the json, but I want just the image of the item.
This is my response code:
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONObject("feed").getJSONArray("entry");
for (int i = 0; i < jsonArray.length(); i++) {
JSONArray imageArray = response.getJSONObject("feed").getJSONArray("entry").getJSONObject(i).getJSONArray("im:image");
for (int j =0; j < imageArray.length(); j++) {
String image = response.getJSONObject("feed").getJSONArray("entry").getJSONObject(i).getJSONArray("im:image").getJSONObject(j).getString("label").toString();
ImagesModule imagesModule = new ImagesModule();
imagesModule.setImageUrl(image);
imagesModules.add(imagesModule);
}}
imageRecyclerViewadapter = new ImageViewAdapter(imagesModules,getContext());
AppRecyclerView.setAdapter(imageRecyclerViewadapter);
} catch (JSONException e) {e.printStackTrace();
I'm not really understand if your one is the question or answer to the problem. But if you want parse it by url, instead ImageModule you can try and getting image by image also:
let img = UIImage()
if let url = NSURL(string: image) {
if let data = NSData(contentsOfURL: url) {
img = UIImage(data: data)!
// array.append(img)
}
}
That for iOS!

how to connect app using json

I am trying to connect my app using json but when I run my app it gets crashed. I think the problem is in the following code:
protected void onPostExecute(ArrayList result)
{
if (result == null)
{
Toast.makeText(MainActivity.this, "Failed to download Movies", Toast.LENGTH_LONG).show();
return;
}
JSONObject jsono = null;
// gridView gv = (GridView)findViewById(R.id.main_gridview);
ArrayList<Movie> l = new ArrayList<>();
try
{
jsono = new JSONObject((java.util.Map) result);
JSONArray jarray = jsono.getJSONArray("result");
for (int i = 0; i < jarray.length(); i++)
{
JSONObject object = jarray.getJSONObject(i);
String posterPath = object.getString("poster_path");
String title = object.getString("original_title");
String id = object.getString("id");
Movie m = new Movie(id, title, posterPath);
l.add(m);
}
}
catch (JSONException e)
{
e.printStackTrace();
}
MainAdapter adapter = new MainAdapter(MainActivity.this, result);
}
Someone kindly help me.
jsono = new JSONObject((java.util.Map) result);
Cast ArrayList to Map?
I think that you should read more basic knowledge about casting types in java, Maps, ArrayList and JSON.

Categories

Resources