Error while parsing json data in android - android

I am trying to display data received from a json data source. But I am getting an error when I try to parse the data. I am not able to figure out how to solve it.
The json data looks something like this:
click here to view
Here is the function I wrote for parsing :
public void makeJSONRequest() {
JsonArrayRequest req = new JsonArrayRequest(endpoint_final,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
// UI
swipeRefreshLayout.setRefreshing(false);
for (int i = 0; i < response.length(); i++) {
try {
JSONObject object = response.getJSONObject(i);
JSONObject newsItems = object.getJSONObject("newsItems");
for (int j = 0; j < newsItems.length(); j++) {
titles[j] = newsItems.getString("title");
snips[j] = newsItems.getString("snip");
links[j] = newsItems.getString("link");
}
} catch (JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
Toast.makeText(getActivity(), "JSON Parsing error", Toast.LENGTH_LONG).show();
}
}
mAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error: " + error.getMessage());
Toast.makeText(getContext(), "Error Receiving News", Toast.LENGTH_LONG).show();
}
});
// Adding request to request queue
InitializeVolley.getInstance().addToRequestQueue(req);
}
The error I am getting is :
Error: org.json.JSONException: Value {"newsItems":[{"link":"http://www.srmuniv.ac.in/announcement/special-training-details","snip":"Dear Students,Those who are interested in Placements must follow certain guidelines.You have to clear the tests conducted by CDC and only those...","title":"CDC: Special Training - Updated"}....
Any help will be appreciated.
Thank you!

First of all this json is not an array, it is an object. You should use JsonObjectRequest instead of JsonArrayRequest. You were parsing the json wrongly.
public void makeJSONRequest() {
JsonObjectRequest req = new JsonObjectRequest(endpoint_final,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
// UI
swipeRefreshLayout.setRefreshing(false);
JSONArray newsAr = response.getJsonArray("news");
for (int i = 0; i < newsAr.length(); i++) {
try {
JSONObject newsItem = newsAr.getJSONObject(i);
titles[j] = newsItem.getString("title");
snips[j] = newsItem.getString("snip");
links[j] = newsItem.getString("link");
} catch (JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
Toast.makeText(getActivity(), "JSON Parsing error", Toast.LENGTH_LONG).show();
}
}
mAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error: " + error.getMessage());
Toast.makeText(getContext(), "Error Receiving News", Toast.LENGTH_LONG).show();
}
});
// Adding request to request queue
InitializeVolley.getInstance().addToRequestQueue(req);
}

JSONObject newsItems = object.getJSONObject("newsItems");
replace with
JSONArray newsItems = object.getJSONArray("newsItems");

Instead of writing your own parsing function you could (and definitely should) use a library which does the heavy lifting for you. One example would be Google's Gson library, check it out: https://github.com/google/gson

Parse like :
try {
JSONObject objResponse = new JSONObject(response.toString());
JsonArray arrResponse = objResponse.getJSONArray("newsItems");
for (int i = 0; i < arrResponse.size(); i++) {
JSONObject objItems = arrResponse.get(i);
String link = objItems.getString("link");
}
}catch (Exception e){
e.printStackTrace();
}

JSONObject object =new JSONObject[response];
JSONArray newsItems = object.getJSONArray("newsItems");
for (int j = 0; j < newsItems.length(); j++) {
JsonObject internal=newsItems.getJsonObject(j);
titles[j] = internal.getString("title");
snips[j] = internal.getString("snip");
links[j] = internal.getString("link");
}
Use JSONArray instead of JSONObject class as newsItems is JsonArray.

Try with this:
public void makeJSONRequest() {
JsonArrayRequest req = new JsonArrayRequest(endpoint_final,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
// UI
swipeRefreshLayout.setRefreshing(false);
jo = new JSONObject(response);;
JSONArray array = jo.getJSONArray("newsItems");
for (int x = 0; x < array.length(); x++) {
try {
titles[j] = array.getJSONObject(x).optString("title");
snips[j]= array.getJSONObject(x).optString("snip");
links[j] = array.getJSONObject(x).optString("link");
} catch (JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
Toast.makeText(getActivity(), "JSON Parsing error", Toast.LENGTH_LONG).show();
}
}
mAdapter.notifyDataSetChanged();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error: " + error.getMessage());
Toast.makeText(getContext(), "Error Receiving News", Toast.LENGTH_LONG).show();
}
}
);
// Adding request to request queue
InitializeVolley.getInstance().addToRequestQueue(req);
}

Related

How to implement Nested JsonObject /JsonArrey in One Json Value?

I have a Json Format
Json Url
http://inter.youdao.com/intersearch?tag=simple-eh&from=en&to=hi&q=spin
I need only first i
first i - n. घुमाव; चक्रण; झुकाव
second i. v. घूमना; कातना
Is it possible that first i + second i word only first word = n. घुमाव, v. घूमना
The problem was showing result in android no eh velue.
How to get hindi word.
Json Result
{
"data": {
"eh": {
"": "spɪn",
"ukphone": "spɪn",
"ukspeech": "spin&type=1",
"trs": [
{
"i": "n. घुमाव; चक्रण; झुकाव"
},
{
"i": "v. घूमना; कातना"
}
],
Android Implement :
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
urlJsonObj, null, new Response.Listener<JSONObject>() { #Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
try {
// Parsing json object response
// response will be a json object
JSONObject result = response.getJSONObject("data");
String eh= result.getString("eh");
JSONObject result1 = response.getJSONObject("eh");
String hindi= result1.getString("trs");
jsonResponse = "";
jsonResponse += "Hindi: " + hindi ;
txtResponse.setText(jsonResponse);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
// hide the progress dialog
hidepDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
finally fix the Problem
Thanks
here is code :
try {
// Parsing json object response
// response will be a json object
String syncresponse = response.getString("data");
JSONObject object2 = new JSONObject(syncresponse);
String synckey = object2.getString("eh");
JSONObject object3 = new JSONObject(synckey);
JSONArray jArray1 = object3.getJSONArray("trs");
for(int i = 0; i < jArray1 .length(); i++)
{
JSONObject object4 = jArray1.getJSONObject(i);
String comp_id = object4.getString("i");
String replace = object4.getString( "i" ).replace( ";", "," );
translate.setText(mWord + "=" + comp_id);
}

Volley JSON Exception with Bing Search API

I have implementing Bing Images Search API with Volley I need to request for the JSONArray values to request all the thumbnail urls. Here is the JSON format for the Bing Image Search:
[
{
"_type":"Images",
"instrumentation":{
},
"readLink":"https:\/\/api.cognitive.microsoft.com\/api\/v7\/images\/search?q=puppies",
"webSearchUrl":"https:\/\/www.bing.com\/images\/search?q=puppies&FORM=OIIARP",
"totalEstimatedMatches":995,
"nextOffset":37,
"value":[
{
"webSearchUrl":"https:\/\/www.bing.com\/images\/search?view=detailv2&FORM=OIIRPO&q=puppies&id=01FB7631BE5F833B1851922E2AE55143A9DDA195&simid=608039673288263152",
"name":"Cute Golden Retriever Puppies Photos ~ Cute Puppies Pictures, Puppy Photos",
"thumbnailUrl":"https:\/\/tse3.mm.bing.net\/th?id=OIP.sa4AFBPcfVJbIx1MEkakmgHaFj&pid=Api",
"datePublished":"2018-02-04T22:46:00.0000000Z",
"contentUrl":"http:\/\/1.bp.blogspot.com\/-NnDHYuLcDbE\/ToJ6Rd6Dl5I\/AAAAAAAACa4\/NzFAKfIV_CQ\/s1600\/golden_retriever_puppies.jpg",
"hostPageUrl":"http:\/\/puppiesphotos.blogspot.com\/2013\/01\/cute-golden-retriever-puppies-photos.html",
"contentSize":"376369 B",
"encodingFormat":"jpeg",
"hostPageDisplayUrl":"puppiesphotos.blogspot.com\/2013\/01\/cute-golden-retriever-puppies...",
"width":1600,
"height":1200,
"thumbnail":{
"width":474,
"height":355
},
"imageInsightsToken":"ccid_sa4AFBPc*mid_01FB7631BE5F833B1851922E2AE55143A9DDA195*simid_608039673288263152*thid_OIP.sa4AFBPcfVJbIx1MEkakmgHaFj",
"insightsMetadata":{
"recipeSourcesCount":0,
"bestRepresentativeQuery":{
"text":"Cute Golden Retriever Puppies",
"displayText":"Cute Golden Retriever Puppies",
"webSearchUrl":"https:\/\/www.bing.com\/images\/search?q=Cute+Golden+Retriever+Puppies&id=01FB7631BE5F833B1851922E2AE55143A9DDA195&FORM=IDBQDM"
},
"pagesIncludingCount":1238,
"availableSizesCount":240
},
"imageId":"01FB7631BE5F833B1851922E2AE55143A9DDA195",
"accentColor":"AA6F21"
}
]
}
]
This is my Volley Request for JSON Array.
private void requestedTrendingImages(String url) {
Log.d("Query URL: ", url);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
for (int i = 0; i < response.length(); i++) {
JSONObject images = response.getJSONObject(i);
jsonResponse = images.getString("thumbnailUrl");
Log.d(TAG, jsonResponse);
}
Log.d(TAG, jsonResponse);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
HolaApp.getInstance().addToRequestQueue(jsonArrayRequest);
}
My String URL is correct I am new to Volley could anyone help me with parsing JSON Array.
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
try {
JSONArray jsonArray = response.getJSONArray("value");
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject Image = (JSONObject) jsonArray.get(i);
urls = Image.getString("thumbnailUrl");
Log.d(TAG, "onResponse: "+urls);
}
Log.d(TAG, jsonResponse);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
try this
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
try {
JSONArray values = response.getJSONArray("value")
for (int i = 0; i < values.length(); i++) {
String url = values.getJSONObject(i).getString("thumbnailUrl");
//do something with the url
Log.d(TAG, url);
}
Log.d(TAG, jsonResponse);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
Well I found out the answer final which worked for me. I should have used JSONObject instead of JSONArray!
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
newRequestSearchImages(Constants.BING_ENDPOINT_SEARCH + Constants.QUERY + "puppies" + Constants.API_KEY);
}
private void newRequestSearchImages(String url){
JsonObjectRequest jsonObjectRequest = 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("value");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
jsonResponse = object.getString("thumbnailUrl");
Log.d(TAG, jsonResponse);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, error.getMessage());
}
});
HolaApp.getInstance().addToRequestQueue(jsonObjectRequest);
}

JSONArray response with Volley for Android

I am posting some data into the database using Volley and I get the following jsonarray response.
[
{
"nickname":"panikos",
"username":"panikos#gmail.com",
"user_type":"LEADER",
"latest_steps":"0"
}
]
This is a sample of my code that unfortunately doesn't log out or debug the variable of "nickname" object:(.
final JsonArrayRequest jsonObjReq1 = new
JsonArrayRequest(AppConfig.URL_GET_TEAM, jsonObject,
new com.android.volley.Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("TAG", response.toString());
try {
JSONArray jsonArray = new JSONArray(response);
for(int i=0;i<jsonArray.length();i++){
JSONObject jresponse =
jsonArray.getJSONObject(i);
String nickname =
jresponse.getString("nickname");
Log.d("nickname",nickname);
}
} catch (JSONException e) {
e.printStackTrace();
}
//pDialog.dismiss();
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("TAG", "Error: " + error.getMessage());
//pDialog.dismiss();
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
};
Any ideas? Am I missing something?
Thanks.
I the problem might be - you are already getting response as a JSONArray.
So, you can Call
JSONObject jresponse = response.getJSONObject(0);
and if you have more than 1 object in response, then
for(int i = 0; i < response.length(); i++){
JSONObject jresponse = response.getJSONObject(i);
String nickname = jresponse.getString("nickname");
Log.d("nickname", nickname);
}
Remove this :
try {
JSONArray jsonArray = new JSONArray(response);
for(int i=0;i<jsonArray.length();i++){
JSONObject jresponse =
jsonArray.getJSONObject(i);
String nickname =
jresponse.getString("nickname");
Log.d("nickname",nickname);
}
} catch (JSONException e) {
e.printStackTrace();
}
and add :
try {
JSONObject jresponse = response.getJSONObject(0);
String nickname = jresponse.getString("nickname");
Log.d("nickname",nickname);
}catch (JSONException e) {
e.printStackTrace();
}
The Code looks good, however i think you might be missing a call to add jsonObjReq1 in the request queue. I would suggest to use Singleton Pattern.
Fixed!!!
#Override
public void onResponse(JSONArray response) {
Log.d("TAG", response.toString());
try {
Log.d("JsonArray",response.toString());
for(int i=0;i<response.length();i++){
JSONObject jresponse = response.getJSONObject(i);
String nickname = jresponse.getString("nickname");
Log.d("nickname",nickname);
}
} catch (JSONException e) {
e.printStackTrace();
}
//pDialog.dismiss();
}
There was no need to create a new JSONArray. It was created inside the onResponse() method. The next project I am assigned to do is going to have more complicate webservices.omg!!!

volley library displaying the data not stored in the json data

I am having problem with volley library. I dont understand where i am getting all the values from in the application even the internet is not accessible and the data is not available in the api itself. I tried to clear the cache but nothing is working. Any suggestion would be appreciated. Thanks
private void makeJsonObjReq() {
//Log.e("makeJsonobjReq method", "inside");
pinfo = new PostsInfo();
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
Const.URL_JSON_ARRAY, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONArray jArray;
Log.e(TAG +"", " rrr "+ response.toString());
try {
Log.e(TAG, "" + response.getInt("count") + " " + response.getInt("pages") + " " + response.getInt("page"));
for (int i = response.getInt("page"); i <= response.getInt("pages"); i++) {
jArray = response.getJSONArray("results");
for (int j = 0; j < response.getInt("count"); j++) {
try {
a_fetch_data.open();
JSONObject json = jArray.getJSONObject(i);
Log.e(TAG +" no of count in array", "i = "+ json.getString("id"));
//jsonObjectValue(json);
}
catch (JSONException e) {
e.printStackTrace();
}
}
Log.e(TAG, "Array "+ " Completed ");
}
}
catch (JSONException e1) {
e1.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
/*Adding request to request queue*/
ApplicationController.getInstance().addToRequestQueue(jsonObjReq,
"jobj_req");
ApplicationController.getInstance().getRequestQueue().getCache().remove("jobj_req");
}
api :http://bumpintomums.com.au/wp-content/themes/bumpii/API/get_data.php
The problem is, this method returns a response even though i am not connected to internet and i have not instantiated any cache work here.

Android JSON request populating array

I have followed this tutorial.
The author directly uses the data in the callback by setting the textview within the callback. What I would like to do is populate an array with the response I'm getting from my request, and then be able to use that array elsewhere (as the response listener is an anonymous inner class, I can't figure out how to get data from it; any attempt to assign to an array inside the listener has proved fruitless.
Thanks, please bear with me as I'm still a beginner.
The listener:
JsonArrayRequest req = new JsonArrayRequest(urlJsonArry,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
// Parsing json array response
// loop through each json object
jsonResponse = "";
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response
.get(i);
String name = person.getString("name");
String email = person.getString("email");
JSONObject phone = person
.getJSONObject("phone");
String home = phone.getString("home");
String mobile = phone.getString("mobile");
jsonResponse += "Name: " + name + "\n\n";
jsonResponse += "Email: " + email + "\n\n";
jsonResponse += "Home: " + home + "\n\n";
jsonResponse += "Mobile: " + mobile + "\n\n\n";
}
txtResponse.setText(jsonResponse);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
hidepDialog();
}
});
EDIT: The code below outlines the problem I'm having. I'm aware this is probably due to misunderstanding or misapplication on my part but still.
private void makeJsonArrayRequest(String url){
//ONLY WAY TO ACCESS INSIDE LISTENER IS TO MAKE FINAL
final ArrayList<String> string = new ArrayList<>();
showpDialog();
JsonArrayRequest req = new JsonArrayRequest(
url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject field = (JSONObject) response.get(i);
string.add(i, field.getString("title"));
//THIS PRINTS OUT ALL MY TITLES CORRECTLY, SHOWING THAT
//THE STRINGS ARRAY IS POPULATED IN THIS SCOPE
Log.d(AppController.TAG, string.get(i));
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(context,
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(AppController.TAG, "Error: " + error.getMessage());
Toast.makeText(context,
error.getMessage(), Toast.LENGTH_SHORT).show();
hidepDialog();
}
}
);
AppController.getInstance().addToRequestQueue(req);
//THIS CAUSES AN OUT OF BOUNDS EXCEPTION, AS IT THINKS THE ARRAY HAS NOT BEEN POPULATED
Log.d(AppController.TAG, string.get(3));
}
I think the problem is using variable string as a copy of actual string inside OnResponse(..).
Try adding static to this variable :
final static ArrayList<String> string = new ArrayList<>();

Categories

Resources