Android App Crashing While Trying To Parse Json Object Using Volley - android

requestQueue = Volley.newRequestQueue(Home.this);
JsonObjectRequest objectRequest = new JsonObjectRequest(com.android.volley.Request.Method.GET ,"http://www.omdbapi.com/?t=avengers",null,new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String Title = response.getString("Title");
String Year = response.getString("Year");
String Released = response.getString("Released");
String Genre = response.getString("Genre");
String Metascore = response.getString("Metascore");
String imdbRating = response.getString("imdbRating");
String Poster = response.getString("Poster");
moviesData = new String[]{Title, Year, Released, Genre, Metascore, imdbRating, Poster};
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(objectRequest);
I am trying to fetch data from the site and store its content using json parsing and volley i was doing it with HttpUrlConnection and it was working fine when i tried to do it using volley I got stuck
I don't know where I am going wrong or missing something don't know why App is crashing.

That was my own fault I was writing this code in the wrong method.

Related

Not able to fetch JSON data [using volley Library] in Android

The jason array request code goes like this:
JsonArrayRequest arrayRequest = new JsonArrayRequest(Request.Method.GET,url, (JSONArray) null , new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
Log.d("Response:", String.valueOf(response.getJSONObject(0)));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "Response not recieved", Toast.LENGTH_SHORT).show();
}
});
And I've used a singleton instance of a request queue, to fetch the data,
AppController.getInstance(context.getApplicationContext()).addToRequestQueue(arrayRequest);
I'm using an api service that supplies a bunch of questions (The api generates a url, which returns a collection of JSON Objects, An Array (Just try and Open the url link, the json array will be seen)
But when I run the app, the request is not even getting a response,the progam flow is going into the error listner block.
Can someone explain this behaviour? Is it because the JSON array supplied by the url, has nested arrays? Why?
I tried reading and anlyzing other questions here, which might have the same issue, But i found nothing.
You want to just change JsonArrayRequest to JsonObjectRequest:
Please copy and paste below code:
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("TAG", response.toString());
try {
JSONArray jsonArray = response.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String category = jsonObject.getString("category");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("TAG", "Error: " + error.getMessage());
// hide the progress dialog
}
});
AppController.getInstance().addToRequestQueue(jsonObjReq, "TAG");
Follow this link for learn other request: Androidhive

How i can can parse JSON Object ? just a simple object I am new [duplicate]

This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 4 years ago.
I want to get string values on this one
{"response":"success","Message":"Product Created Successfully"}
final JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject JO = response.getJSONObject();
String respond = JO.getString("response");
String message = JO.getString("Message");
Toast.makeText(MainActivity.this, respon + message,Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
you must write this code in your try{...} block
String respond = response.getString("response");
String message = response.getString("Message");
Toast.makeText(MainActivity.this, respond + message,Toast.LENGTH_SHORT).show();
As a new programmer I recommend you:
A. Read some how you work with Jason.
http://www.vogella.com/tutorials/AndroidJSON/article.html
B. Use the Jason library to make it easy for you down the road.
I'll give you an example of the right use for your needs now.
Build a class that fits your json:
public class MyObject {
private String response;
private String Message;
public MyObject() {
}
public String getResponse() {
return response;
}
public void setResponse(String response) {
this.response = response;
}
public String getMessage() {
return Message;
}
public void setMessage(String message) {
Message = message;
}
}
Add Gson library to your project:
dependencies {
implementation 'com.google.code.gson:gson:2.8.5'
}
Sync your project and now you can cast your json easily to class object:
String json = "{response:success,Message\":Product Created Successfully}";
MyObject myObject = new Gson().fromJson(json, MyObject.class);
String a = myObject.getResponse();
String b = myObject.getMessage();

Android SharedPreference JSON not being accessed

I am using volley to send a http request to yahoo's weather API like this:
public Object requestData(String url) {
final RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest objectRequest = new JsonObjectRequest(
Request.Method.GET,
url,
null,
new Response.Listener < JSONObject > () {
#Override
public void onResponse(JSONObject response) {
String responseList = response.toString();
cityList.edit().putString(String.valueOf(i), responseList);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
requestQueue.add(objectRequest);
return null;
}
As you can see, I am putting the response to this inside a sharedpreference I declared as "citylist"
:
cityList = getSharedPreferences(String.valueOf(i), MODE_PRIVATE);
I then access this response inside the sharedpreference like this:
String mResponse = cityList.getString(String.valueOf(i), "");
Log.d("log", mResponse);
try {
JSONObject jsonObj = new JSONObject(mResponse);
JSONObject response = jsonObj.getJSONObject("query");
createdCity.temperature = response.optJSONObject("results").optJSONObject("channel").optJSONObject("item").optJSONObject("condition").getInt("temp");
createdCity.conditions = response.optJSONObject("results").optJSONObject("channel").optJSONObject("item").optJSONObject("condition").getString("text");
createdCity.town = response.optJSONObject("results").optJSONObject("channel").optJSONObject("location").getString("city");
createdCity.country = response.optJSONObject("results").optJSONObject("channel").optJSONObject("location").getString("country");
createdCity.state = response.optJSONObject("results").optJSONObject("channel").optJSONObject("location").getString("region");
Log.d("log", String.valueOf(createdCity.town));
cities.add(createdCity);
addMenuItemInNavMenuDrawer();
} catch (JSONException e) {
e.printStackTrace();
}
The problem is that "log" isn't outputting anything. The only information I'm getting from the logcat is:
org.json.JSONException: End of input at character 0 of
How can I go about fixing my issue? Is there a better way of doing this?
Are you committing after editing the preference? Based on your response, you might as well use apply() as it does things asynchronously.
If you are sure that the commit won't affect the main thread, you can use cityList.commit() or safely use cityList.apply(). But you need to do either of these two or else the changes are not written to the disk which is the reason you are not able to retrieve the data.
This link should help:
https://developer.android.com/training/data-storage/shared-preferences#java

How to change URL from JSON parsing

hi guys i am making an Android app which enlarge the Instagram profile pictures
i have done everything correctly now what i want is to modifiy the output url that i am getting from instagram server for example when i run my json script it give me this
https://instagram.fkhi6-1.fna.fbcdn.net/t51.2885-19/s320x320/20766978_110444579680760_4754914132547862528_a.jpg
and i want to convert this to that
https://instagram.fkhi6-1.fna.fbcdn.net/t51.2885-19/s800x800/20766978_110444579680760_4754914132547862528_a.jpg
here is my code that i am using
final JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.GET, finalURL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject user = response.getJSONObject("user");
String profilePicture = user.getString("profile_pic_url_hd");
Log.v("JSON", "User: " + profilePicture);
} catch (JSONException e) {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.v("FUN", "Error " + error.toString());
}
});
Thanks.
Try this:
String imageUrl=originalUrl.replaceAll("[s][0-9]+[x][0-9]+","s"+desiredWidth+"x"+desiredHeight);
Try this code and see if it works:
String smallImageUrl = "https://instagram.fkhi6-1.fna.fbcdn.net/t51.2885-19/s320x320/20766978_110444579680760_4754914132547862528_a.jpg";
String largeImageURL = smallImageUrl.replace("s320x320", "s800x800");

Android JSON VOlley

Good Day, I would like to get data from this url, and I have problems with onResponse method implementation:
I have something like this:
public void onClick(View v) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "http://horoscope-api.herokuapp.com/",
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
//The Problem is here
JSONArray jsonArray = response.getJSONArray("");
String author = jsonArray.getString(0);
textView.setText(author);
}catch(JSONException e){
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
requestQueue.add(jsonObjectRequest);
}
I don`t understand how to implement onResponse method correctly, I know that I must to get string from array or object, but data from link make me problems to understand what is it object or array, can you write me how to get author field from this url.
Thank you
Since the response in your link is JSONObject, you only need to do the following inside onResponse:
String author = response.getString("author");
textView.setText(author);
Hope this helps!
The response that you are getting is not a JSONArray but is a JSONObject. You could try the below code and see if you are able to get the author.
public void onClick(View v) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "http://horoscope-api.herokuapp.com/",
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String author = response.get("author");
textView.setText(author);
}catch(JSONException e){
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
requestQueue.add(jsonObjectRequest);
}
Hope this helps.
The data from link is JSONObject not JSONArray. Call response.getString("author"); to get author string.
try{
String author = response.getString("author");
} catch(JSONException e) {
e.printStackTrace();
}

Categories

Resources