I have a JSON response and I'm stuck on using it - java

My json is:
{"status":"ok","result":
{"provider":"instagram","title":"lovely_songs_14u","link":
[{"link_name":"Download
Video","video_link":"https:\/\/scontent.cdninstagram.com\/v\/t50.2886-
16\/71650124_386743795596239_6119869649307488549_n.mp4?_nc_ht=scontent.cdninstagram.com&_nc_cat=111&oe=5D907D5B&oh=36ad5ad325cce7926307dfb730583b70"}]}}
Android Side:
StringRequest stringRequest = new StringRequest(Request.Method.GET, hp,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//hiding the progressbar after completion
Log.e("Response", response);
try {
JSONObject obj = new JSONObject(response);
categoryGetSet temp;
JSONArray ja_video = obj.getJSONArray("link");
for (int i = 0; i < ja_video.length(); i++) {
temp = new categoryGetSet();
JSONObject jo_data = ja_video.getJSONObject(i);
String txt_title = jo_data.getString("title");
String txt_link_name = jo_data.getString("link_name");
String txt_image = jo_data.getString("img_link");
String txt_video = jo_data.getString("video_link");
temp.setTitle(txt_title);
temp.setLinkName(txt_link_name);
temp.setImage(txt_image);
temp.setVideo(txt_video);
categoryGetSets.add(temp);
Log.e("dwnld", txt_link_name);
}
Log.e("try", "try");
} catch (JSONException e) {
e.printStackTrace();
Log.e("catch", "catch");
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
if (networkResponse != null) {
Log.e("Status code", String.valueOf(networkResponse.statusCode));
Toast.makeText(getActivity().getApplicationContext(), String.valueOf(networkResponse.statusCode), Toast.LENGTH_SHORT).show();
}
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
requestQueue.add(stringRequest);
But it goes everytime into catch case, please let me know where i am doing it wrong

Your JSON is valid.
Use below code to parse your JSON.
try {
JSONObject obj = new JSONObject(json);
categoryGetSet temp;
JSONObject resultObject = (JSONObject) obj.get("result");
String txt_title = resultObject.getString("title");
String txt_provider = resultObject.getString("provider");
JSONArray ja_video = resultObject.getJSONArray("link");
for (int i = 0; i < ja_video.length(); ++i) {
temp = new categoryGetSet();
JSONObject jo_data = ja_video.getJSONObject(i);
String txt_link_name = jo_data.getString("link_name");
String txt_video = jo_data.getString("video_link");
temp.setTitle(txt_title);
temp.setLinkName(txt_link_name);
temp.setImage(txt_provider);
temp.setVideo(txt_video);
Log.e("jsonResponse: ", "txt_title" + txt_title);
Log.e("jsonResponse: ", "txt_link_name" + txt_link_name);
Log.e("jsonResponse: ", "txt_provider" + txt_provider);
Log.e("jsonResponse: ", "txt_video" + txt_video);
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("catch", e.getLocalizedMessage());
}

Because link array is inside result object but you are trying to get from outer object.so you are getting exception.
Try to parse like this
JSONObject obj = new JSONObject(response);
JSONObject resultObj=obj.getJSONObject("result");
JSONArray ja_video = resultObj.getJSONArray("link");

It's going in catch because you are trying to parse in the wrong way,
You need to pass every JSON object and array sequence by sequence, Bellow is your structure
Main Json Object
result Object
link Array
Sub Object with Data
And another wrong thing is you are trying some key which is not exist
Try Bellow code it will help you
StringRequest stringRequest = new StringRequest(Request.Method.GET, hp,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//hiding the progressbar after completion
Log.e("Response", response);
try {
JSONObject mainObject = new JSONObject(response);
JSONObject resultObj=mainObject.getJSONObject("result");
JSONArray linkJsonArrya = resultObj.getJSONArray("link");
categoryGetSet temp;
for (int i = 0; i < linkJsonArrya.length(); i++) {
temp = new categoryGetSet();
JSONObject jo_data = linkJsonArrya.getJSONObject(i);
if(jo_data.has("title")){
temp.setTitle(jo_data.getString("title"));
}else {
temp.setTitle(jo_data.getString(""));
}
if(jo_data.has("link_name")){
temp.setLinkName(jo_data.getString("link_name"));
}else {
temp.setLinkName(jo_data.getString(""));
}
if(jo_data.has("img_link")){
temp.setImage(jo_data.getString("img_link"));
}else {
temp.setImage(jo_data.getString(""));
}
if(jo_data.has("video_link")){
temp.setVideo(jo_data.getString("video_link"));
}else {
temp.setVideo(jo_data.getString(""));
}
categoryGetSets.add(temp);
}
Log.e("try", "try");
} catch (JSONException e) {
e.printStackTrace();
Log.e("catch", "catch");
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
if (networkResponse != null) {
Log.e("Status code", String.valueOf(networkResponse.statusCode));
Toast.makeText(getActivity().getApplicationContext(), String.valueOf(networkResponse.statusCode), Toast.LENGTH_SHORT).show();
}
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
requestQueue.add(stringRequest);
}

Related

How to return single integer value from Volley in Android?

I am trying to get a single integer value with Volley.
In this example the number is 14
In the debugger I get the correct value 14 and assign it to vNumber while in the try/catch block but then when I try to return the vNumber I get value 0 as returned number.
This is the JSON result.
{"result":[{"version":"14"}]}
Here is the code for this function:
int vNumber;
public int getVersionNumber() {
StringRequest stringRequest = new StringRequest(Request.Method.POST, GET_VERSION_NUMBER,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject object = new JSONObject(response);
JSONArray jsonArray = object.getJSONArray("result");
JSONObject jsonObject = jsonArray.getJSONObject(0);
vNumber = jsonObject.getInt("version");
} catch (JSONException e) {
e.printStackTrace();
Log.d(TAG, "JSONException: " + e);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "VolleyError: " + error);
}
});
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(stringRequest);
return vNumber;
}
I already tried using sharedPreferences and putting the value inside a textView (the value is correct when I set it in a textView) and then getting it from it but it's still not working. I could create a new table inside my local DB and save the data but it is not necessary in this use case.
Do you have any suggestions on how the return the correct value, and what am I doing wrong here?
Cheers
public void fetchVersionNumber() {
StringRequest stringRequest = new StringRequest(Request.Method.POST, GET_VERSION_NUMBER,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject object = new JSONObject(response);
JSONArray jsonArray = object.getJSONArray("result");
JSONObject jsonObject = jsonArray.getJSONObject(0);
vNumber = jsonObject.getInt("version");
compareAndUpdate(vNumber)
} catch (JSONException e) {
e.printStackTrace();
Log.d(TAG, "JSONException: " + e);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "VolleyError: " + error);
}
});
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(stringRequest);
}
public void compareAndUpdate(int vNumber){
//compare and do your operation
// Get from sharedPref and compare
}

i got error about java.lang.String cannot be converted to JSONarray

In my code, I am trying to populate value spinner from a MySQL database, but I can't get the value.
What's wrong on my jsonArray?
java.lang.String cannot be converted to JSONObject
JsonArrayRequest jsonSpinnerObjectRequest = new JsonArrayRequest(fetch_city_url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
JSONObject jsonObject = null;
JSONArray jsonArray = jsonObject.getJSONArray("result");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject city = jsonArray.getJSONObject(i);
Log.i("onResponseSpinner", city.getString("kd_kelas") + " " + city.getString("kelas"));
kelasList.add(city.getString("kelas"));
}
spinnerAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY","ERROR in response"+error.getMessage());
}
});
Here you set a JSON object to null then try to get JSON Array from it:
JSONObject jsonObject = null;
JSONArray jsonArray = jsonObject.getJSONArray("result");
I think you are wanting something like this:
public void onResponse(JSONObject response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray = jsonArray = new jsonObject.getJSONArray("result");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject city = jsonArray.getJSONObject(i);
Log.i("onResponseSpinner", city.getString("kd_kelas") + " " + city.getString("kelas"));
kelasList.add(city.getString("kelas"));
}
spinnerAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
Looking at your code, i think you are already getting the JSON array in response so just get the values from this JSON array only, please go through the following code
JsonArrayRequest jsonSpinnerObjectRequest = new JsonArrayRequest(fetch_city_url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject city = response.getJSONObject(i);
Log.i("onResponseSpinner", city.getString("kd_kelas") + " " + city.getString("kelas"));
kelasList.add(city.getString("kelas"));
}
spinnerAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY","ERROR in response"+error.getMessage());
}
});

setShouldCache(false) not working

i have log in code who connecting to my php file on my host using volley
everything works great but when i log off and log in again, saved cache memory remember my old information even if i changed it.
i tried to use:
requestQueue.getCache().clear();
stringRequest.setShouldCache(false);
not clearing my cache
this is my code:
private void sendRequest(){
StringRequest stringRequest = new StringRequest(Request.Method.GET,DBConstants.LOG_IN_USER + mEmail + "&password=" + mPassword,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONArray user = null;
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(response);
user = jsonObject.getJSONArray(JSON_ARRAY);
JSONObject jo = user.getJSONObject(0);
gates = new ArrayList<String>(5);
gateData = new ArrayList<String>();
mEmail = jo.getString(DBConstants.KEY_LOGIN_EMAIL);
mPassword = jo.getString(DBConstants.KEY_LOGIN_PASSWORD);
name = jo.getString(DBConstants.KEY_LOGIN_NAME);
if(!mEmail.equals("null")) {
level = Integer.parseInt(jo.getString(DBConstants.KEY_LOGIN_LEVEL));
for (int i = 1; i < 6; i++) {
gates.add(jo.getString(DBConstants.KEY_LOGIN_GATE + i));
if(!gates.get(i-1).equals("null")) {
for (String dataString : gates.get(i-1).split(";")) {
gateData.add(dataString);
}
newGate = new Gate(gateData.get(0),gateData.get(1),gateData.get(2),
Integer.parseInt(gateData.get(3)),Integer.parseInt(gateData.get(4)),gateData.get(5));
myHandler.addNewGate(newGate);
getAuthorizedList(newGate);
gateData.clear();
}
}
login = true;
} else {
login = false;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
login = false;
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this.getApplicationContext());
requestQueue.getCache().clear();
stringRequest.setShouldCache(false);
requestQueue.add(stringRequest);
}
sorry you can close
on my hosting account i had cache manager, i turned it off and it works great!

Geting null from ArrayList in Android when extract JSONArray

I'm using Volley to get information from an SQL database, from server, and I get it in a JSONArray. When I extract values from the JSONArray so I can save values to an ArrayList, in the return statement I get null in my ArrayList. Can anyone help with the return statement?
#Override
public List<WorkItem> getWorkItem() {
final String url = "http://10.0.2.2:8080/items/all/items";
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("Response", response.toString());
try {
arrayList = new ArrayList<>();
response = new JSONArray(response.toString());
for (int i = 0; i < response.length(); i++) {
JSONObject jsonobject = response.getJSONObject(i);
String title = jsonobject.getString("title");
String description = jsonobject.getString("description");
String state = jsonobject.getString("status");
String assignee = jsonobject.getString("assignee");
arrayList.add(new WorkItem(title, description, state, assignee));
arrayList.size();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error", error.getMessage());
}
});
jsonArrayRequest.setTag(REQUEST_TAG);
mQueue.add(jsonArrayRequest);
return arrayList;
}

Return array from external function and get the result

I'm having a problem in Java.
I have this function "fillArray()" and I need this function return an array. The arrays values are get by JSON.
The code of this function is the next:
public String[] fillArray(){
requestQueue = Volley.newRequestQueue(getActivity());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "http://api.mysite.com/v1/countries",
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("data");
final String[] countries = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++){
JSONObject country = jsonArray.getJSONObject(i);
String country_name = country.getString("country_name");
countries[i] = country_name;
Log.v("NAME:", country_name);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
Log.e("VOLLEY", "ERROR");
}
}
);
requestQueue.add(jsonObjectRequest);
return countries;
}
I can return the array, I get the error "Cannot resolver symbol countries".
Any idea? Thanks in advance!

Categories