W/System.err: .MainActivity$1.onResponse - android

I am trying to parse Json it will show error
final StringRequest request = new StringRequest(Request.Method.GET, URL_DATA, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Log.d(TAG, response);
try {
JSONObject jobj = new JSONObject(response);
Log.d(TAG, jobj.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue reQueue = Volley.newRequestQueue(this);
reQueue.add(request);
}
Here is my api
http://159.65.89.76/userApi/categories

Related

volley android the list size in my code return Zero

please anyone help me the list size in my code return Zero
note:- list is global variable when get the size is return zero
public void getdata(String cities) {
String url = "http://api.openweathermap.org/data/2.5/weather?q=" + cities + "&APPID=8072ed7ede0fc9bcb8591a2a2eb90cfd";
StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
CityWeather cityWeather = new CityWeather();
JSONObject object = new JSONObject(response);
cityWeather.setLonitude(String.valueOf(object.getJSONObject("coord").getDouble("lon")));
cityWeather.setLatitude(String.valueOf(object.getJSONObject("coord").getDouble("lat")));
cityWeather.setCityName(object.getString("name"));
cityWeather.setCurrentTemp(String.valueOf(object.getJSONObject("main").getDouble("temp")));
cityWeather.setPressure(String.valueOf(object.getJSONObject("main").getInt("pressure")));
cityWeather.setHumidity(String.valueOf(object.getJSONObject("main").getInt("humidity")));
cityWeather.setMinTemp(String.valueOf(object.getJSONObject("main").getDouble("temp_min")));
cityWeather.setMaxTemp(String.valueOf(object.getJSONObject("main").getDouble("temp_max")));
cityWeather.setWindSpeed(String.valueOf(object.getJSONObject("wind").getDouble("speed")));
cityWeather.setWindDegree(String.valueOf(object.getJSONObject("wind").getInt("deg")));
list.add(cityWeather);
} catch (JSONException e) {
Toast.makeText(MainActivity.this, e.getMessage().toString(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
});
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(request);
}
Thanks for all
Volley is not synchronous, it takes the request and give you the callback when the request is completed. If you check the size after onResponse is called you will get the desired result
String url = "http://api.openweathermap.org/data/2.5/weather?q=" + cities + "&APPID=8072ed7ede0fc9bcb8591a2a2eb90cfd";
StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
CityWeather cityWeather = new CityWeather();
JSONObject object = new JSONObject(response);
cityWeather.setLonitude(String.valueOf(object.getJSONObject("coord").getDouble("lon")));
cityWeather.setLatitude(String.valueOf(object.getJSONObject("coord").getDouble("lat")));
cityWeather.setCityName(object.getString("name"));
cityWeather.setCurrentTemp(String.valueOf(object.getJSONObject("main").getDouble("temp")));
cityWeather.setPressure(String.valueOf(object.getJSONObject("main").getInt("pressure")));
cityWeather.setHumidity(String.valueOf(object.getJSONObject("main").getInt("humidity")));
cityWeather.setMinTemp(String.valueOf(object.getJSONObject("main").getDouble("temp_min")));
cityWeather.setMaxTemp(String.valueOf(object.getJSONObject("main").getDouble("temp_max")));
cityWeather.setWindSpeed(String.valueOf(object.getJSONObject("wind").getDouble("speed")));
cityWeather.setWindDegree(String.valueOf(object.getJSONObject("wind").getInt("deg")));
list.add(cityWeather);
//Check list size here and do whatever you want with the list
} catch (JSONException e) {
Toast.makeText(MainActivity.this, e.getMessage().toString(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
});
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(request);

String to jsonObject

On the below code i want to use Response but it throws JSONException
StringRequest strReq = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.v(TAG, "Response: " + response);//output {"error":false}
try {
JSONObject jo = new JSONObject(response); // java.lang.String cannot be converted to JSONObject
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
Sample JSON string:
{
"error": false,
"uid": "5b081af13eb974.69226352",
"user": {
"name": "66699",
"created_at": "2018-05-25 18:47:21"
}
}
How i should solve this?
Well, to retrieve the content of your response you don't need to use JSON while using POST request. Instead do something like this :
if (response.equalsIgnoreCase("yourResponseFromTheWebService")) {
...
Toast
} else if (response.equalsIgnoreCase("OtherPossibleResponse")){
....
Toast
} else{
....
Toast
}
in case of GET request you should do something like this :
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, URL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// display response
try {
//put response into string
JSONArray Jresult = response.getJSONArray("user");
for (int i = 0; i < Jresult.length(); i++) {
JSONObject json_data = Jresult.getJSONObject(i);
String lName = json_data.getString("name");
String lCreatedAt = json_data.getString("created_at");
//create a model class with your user info like name and created_at and for every user found create a new user object and store its info.
_myUser.add(new User(lName, lCreatedAt));
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("Response", response.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
}
}
);
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(getRequest);

How to combine the two request in which one give response for another api key which pass for request

I want to parse two api at the same time in which one api get a response of key that key has api link and pass in another StringRequest forget response.
This is my function for parsing in which I want to parse firstly one api and get a response in response href name of key use for another api parse link.
please help me as soon as.
I searched and I got this link but it is not proper code.
https://www.versti.eu/TranslateProxy/https/stackoverflow.com/questions/37584001/how-to-combine-the-two-request-url-from-json-to-get-output-in-volley
private void parseSmartPhone()
{
StringRequest stringRequest= new
StringRequest(com.android.volley.Request.Method.GET,
Config.HOMECTEGORY, new Response.Listener<String>() {
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onResponse(String response) {
try {
//getting the whole json Array from the response
// JSONObject jsonObject= new JSONObject(response);
JSONArray jsonArray = new JSONArray(response);
mylist=new ArrayList<>();
for (int i = 0;i<=2;i++)
{
latestsphone= new LatestSmartPhoneModel();
JSONObject jsonObject = jsonArray.getJSONObject(i);
JSONObject objtitle=jsonObject.getJSONObject("title");
title=objtitle.getString("rendered");
objtitle=jsonObject.getJSONObject("_links");
JSONArray imgJsonArray=objtitle.getJSONArray("wp:featuredmedia");
JSONObject objJsonImg=imgJsonArray.getJSONObject(0);
StringRequest request1= new StringRequest(com.android.volley.Request.Method.GET,objJsonImg.getString("href"), new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject= new JSONObject(response);
JSONObject imggild=jsonObject.getJSONObject("guid");
String rendered=imggild.getString("rendered");
latestsphone.setLink(rendered);
latestsphone.setTitle(title);
mylist.add(latestsphone);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue= Volley.newRequestQueue(getActivity());
requestQueue.add(request1);
request1.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}
UpcomingAdapter imgAdapter=new UpcomingAdapter(getActivity(),mylist);
recyclerUpcoming.setAdapter(imgAdapter);
recyclerUpcoming.setLayoutManager(new GridLayoutManager(getActivity(),2));
recyclerUpcoming.setHasFixedSize(true);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
stringRequest.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}
This is your proper code, i corrected your posted code, Use these as global parameter.
ArrayList<LatestSmartPhoneModel> mylist = new ArrayList<>();
String title,link;
private void parseSmartPhone() {
final RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.GET, Config.HOMECTEGORY, new Response.Listener<String>() {
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onResponse(String response) {
try {
//getting the whole json Array from the response
// JSONObject jsonObject= new JSONObject(response);
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i <= 3; i++) {
if (i==3)
{
i=4;
}
JSONObject jsonObject = jsonArray.getJSONObject(i);
JSONObject objtitle = jsonObject.getJSONObject("title");
title = objtitle.getString("rendered");
link=jsonObject.getString("link");
objtitle = jsonObject.getJSONObject("_links");
final LatestSmartPhoneModel latestsphone = new LatestSmartPhoneModel();
latestsphone.setTitle(title);
latestsphone.setLink(link);
JSONArray imgJsonArray = objtitle.getJSONArray("wp:featuredmedia");
JSONObject objJsonImg = imgJsonArray.getJSONObject(0);
StringRequest request1 = new StringRequest(com.android.volley.Request.Method.GET, objJsonImg.getString("href"), new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONObject imggild = jsonObject.getJSONObject("guid");
String rendered = imggild.getString("rendered");
latestsphone.set_links(rendered);
mylist.add(latestsphone);
UpcomingAdapter imgAdapter = new UpcomingAdapter(getActivity(), mylist);
recyclerUpcoming.setAdapter(imgAdapter);
recyclerUpcoming.setLayoutManager(new GridLayoutManager(getActivity(), 2));
recyclerUpcoming.setHasFixedSize(true);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(request1);
request1.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(stringRequest);
stringRequest.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}

Could not allocate JNI Env

I'm updating my API every 2seconds,
but I am receiving this error and my application closes.
FATAL EXCEPTION: main
Process: com.application.toweeloasep, PID: 6681
java.lang.OutOfMemoryError: Could not allocate JNI Env
at java.lang.Thread.nativeCreate(Native Method)
at java.lang.Thread.start(Thread.java:730)
at com.android.volley.RequestQueue.start(RequestQueue.java:145)
at com.android.volley.toolbox.Volley.newRequestQueue(Volley.java:66)
at com.android.volley.toolbox.Volley.newRequestQueue(Volley.java:78)
at com.application.toweeloasep.fragments.Jobs$5$1.run(Jobs.java:260)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
After about a minute, it starts to crash and receives that error.
Am I overdoing things with Volley?
private void setRepeatingAsyncTask() {
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask task = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
if (checkRequests) {
RequestQueue mRequestQueue = Volley.newRequestQueue(getActivity());
StringRequest mStringRequest = new StringRequest(Request.Method.POST, "http://api.000.com/booking/track", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("RESPONSE:TRACK", response);
try {
JSONObject json = new JSONObject(response);
String mStatus = json.getString("status");
if (mStatus.equalsIgnoreCase("0")) {
Log.e("STATUS", mStatus);
} else if (mStatus.equalsIgnoreCase("1")) {
JSONArray infos = json.getJSONArray("data");
booking_id = infos.getJSONObject(0).getString("id");
user_address_location = infos.getJSONObject(0).getString("user_address_location");
mTxtBatteryInfo.setText(infos.getJSONObject(0).getJSONObject("battery").getString("model"));
mTxtUserLocation.setText(user_address_location);
checkRequests = false;
mJobsHome.setVisibility(View.GONE);
mJobRequest.setVisibility(View.VISIBLE);
if (!onTick) {
mCountDownTimer.start();
onTick = true;
}
}
} catch (Exception e) {
Log.e("ERR", e.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("ERR", error.toString());
}
});
mRequestQueue.add(mStringRequest);
} else {
RequestQueue requestPlaceInfo = Volley.newRequestQueue(getActivity());
StringRequest request2 = new StringRequest(Request.Method.POST, "http://api.000.com/booking/track", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("RESPONSE", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), error.toString(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("booking_id", booking_id);
params.put("rider_long", String.valueOf(lng));
params.put("rider_lat", String.valueOf(lat));
return params;
}
};
requestPlaceInfo.add(request2);
}
} catch (Exception e) {
// error, do something
}
}
});
}
};
timer.schedule(task, 0, 2000); // interval of one minute
}
OutOfMemoryError ... at com.android.volley.toolbox.Volley.newRequestQueue
Why do you need to create a new RequestQueue or StringRequest every two seconds?
Try making only one of each.
private final Response.ErrorListener errorListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("ERR", String.valueOf(error));
}
};
private void setRepeatingVolleyTask() {
final RequestQueue mRequestQueue = Volley.newRequestQueue(getActivity());
final StringRequest trackRequest = new StringRequest(Request.Method.POST, "http://api.toweelo.com/booking/track", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("RESPONSE:TRACK", response);
try {
JSONObject json = new JSONObject(response);
String mStatus = json.getString("status");
if (mStatus.equalsIgnoreCase("0")) {
Log.d("STATUS", mStatus);
} else if (mStatus.equalsIgnoreCase("1")) {
JSONArray infos = json.getJSONArray("data");
booking_id = infos.getJSONObject(0).getString("id");
user_address_location = infos.getJSONObject(0).getString("user_address_location");
mTxtBatteryInfo.setText(infos.getJSONObject(0).getJSONObject("battery").getString("model"));
mTxtUserLocation.setText(user_address_location);
checkRequests = false;
mJobsHome.setVisibility(View.GONE);
mJobRequest.setVisibility(View.VISIBLE);
if (!onTick) {
mCountDownTimer.start();
onTick = true;
}
}
} catch (Exception e) {
Log.e("ERR", e.toString());
}
}
}, errorListener );
final StringRequest trackRequest2 = new StringRequest(Request.Method.POST, "http://api.toweelo.com/booking/track", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("RESPONSE", response);
}
}, errorListener) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("booking_id", booking_id);
params.put("rider_long", String.valueOf(lng));
params.put("rider_lat", String.valueOf(lat));
return params;
}
};
Timer timer = new Timer();
TimerTask task = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
// What are you trying to catch here??
try {
if (checkRequests) {
mRequestQueue.add(trackRequest);
} else {
mRequestQueue.add(trackRequest2);
} catch ( ... ) {
....
}
Note: You can use JsonObjectRequest instead of parsing JSON from a StringRequest

Not execute Volley JSON onResponse function

When I call getData.It seems that it is hard to get the result out from the onResponse. I know it cannot work in this current way. Could anyone help me to settle this problem?
getData()
private void getData(){
//Creating a string request
StringRequest stringRequest = new StringRequest(SPINNER_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Log.d("Country_name","hi");
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
result = j.getJSONArray(JSON_ARRAY);
Log.v("xxxxx",result.toString());
String mysh=result.toString().substring(1, result.toString().length()-1);
JSONArray jsonArray = new JSONArray(mysh);
//Calling method getCountry to get the country from the JSON Array
getCountry(jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
Try this i think it should work
private void getData(){
//Creating a string request
StringRequest stringRequest = new StringRequest(SPINNER_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
getCountry(jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
Try that, this will help.
private void getData() {
String tag_string_req = "req_name";
spotsDialog.show();
StringRequest strReq = new StringRequest(Method.POST,
YOUR URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Response: " + response.toString());
try {
JSONObject object = new JSONObject(response);
JSONArray array = object.getJSONArray("YOUR ARRAY NAME");
for (int i=0;i<array.length();i++){
String result = array.getString(i).toString();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error: " + error.getMessage());
}
});
strReq.setRetryPolicy(new RetryPolicy() {
#Override
public void retry(VolleyError arg0) throws VolleyError {
}
#Override
public int getCurrentTimeout() {
return 0;
}
#Override
public int getCurrentRetryCount() {
return 0;
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
Happy To Help.

Categories

Resources