Not execute Volley JSON onResponse function - android

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.

Related

Volley JsonObjectRequest not fetching data

I am trying to work on volley with gridview. JsonObjectRequest does not fetch any response. I looked up for links on stackoverflow abt JsonObjectRequest passing null as parameter and changing volley version but nothing works as the error was Volley - Cannot Resolve Constructor "JSONObjectRequest. Now no error but no response also. Any help appreciated! Below example link : http://hemanthsomaraju.blogspot.com/2019/03/android-grid-view-using-volley-api.html and volley version: implementation 'com.mcxiaoke.volley:library:1.0.19'. Links referred: Volley - Cannot Resolve Constructor "JSONObjectRequest
public class OutputActivity extends AppCompatActivity {
GridView ListView;
VolleyListViewAdapter adapter;
private List<CommonBean> VolleyList = new ArrayList<CommonBean>();
private ProgressDialog mprocessingdialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_output);
ListView = (GridView) findViewById(R.id.ListView);
adapter = new VolleyListViewAdapter(OutputActivity.this, VolleyList);
ListView.setAdapter(adapter);
new OutputActivity.GetListAsync().execute();
}
private class GetListAsync extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
mprocessingdialog = new ProgressDialog(OutputActivity.this);
mprocessingdialog.setTitle("Please Wait..");
mprocessingdialog.setMessage("Loading");
mprocessingdialog.setIndeterminate(false);
mprocessingdialog.setCancelable(false);
mprocessingdialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
JSONObject jsonObject = null;
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
"https://api.fnpplus.com/productapi/api/rest/v1.2/productList?catalogId=india",
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("rlog", response.toString());
try {
JSONObject jsonObj = new JSONObject(response.toString());
JSONObject jsonObject = jsonObj.getJSONObject("data");
JSONArray jsonArray = jsonObject.getJSONArray("productResults");
Log.d("rlog", jsonArray.toString());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
CommonBean commonBean = new CommonBean();
commonBean.setTextView1(obj.optString("productName"));
JSONObject jsonObject2 = obj.getJSONObject("price");
Log.d("rlog1", jsonObject2.toString());
commonBean.setTextView2(jsonObject2.optString("price"));
Log.d("rlog12", jsonObject2.optString("price"));
JSONObject jsonObject1 = obj.getJSONObject("productImage");
Log.d("rlog1", jsonObject1.toString());
commonBean.setImageView(jsonObject1.optString("path"));
Log.d("rlog12", jsonObject1.optString("path"));
VolleyList.add(commonBean);
}
mprocessingdialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("rlog", "Error: " + error.getMessage());
}
});
jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(0, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(OutputActivity.this);
requestQueue.add(jsonObjReq);
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
new Timer().schedule(new TimerTask() {
#Override
public void run() {
mprocessingdialog.dismiss();
}
}, 30000);
}
}
}
Go with the StringRequest and add your data as per your expected conditions
No Need to use AsyncTask and you can add loader in code also.
RequestQueue queue;
String URL = "https://api.fnpplus.com/productapi/api/rest/v1.2/productList?catalogId=india";
queue = Volley.newRequestQueue(this);
StringRequest request = new StringRequest(Request.Method.GET, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONObject dataJsonObject = jsonObject.getJSONObject("data");
JSONArray jsonArray = dataJsonObject.getJSONArray("productResults");
Log.d("rlog", jsonArray.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("error", error.toString());
}
});
request.setRetryPolicy(new DefaultRetryPolicy(5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(request);
}

POST Request in Volley(using JSON instead of String)

I am developing an app in which i find the origin and destination of a car and send it to a server.
I know how to use volley to send an string however i am finding it hard to send data in JSON format.
Part of the code is given below:
b
tnFindPath.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RequestQueue queue = Volley.newRequestQueue(MapsActivity.this);
String url = "http://192.168.43.162:8080/";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
//adding parameters to the request
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("origin", etOrigin.getText().toString());
params.put("destination", etDestination.getText().toString());
return params;
}
};
// Add the request to the RequestQueue.
queue.add(stringRequest);
try this
final String httpUrl = //your url
try {
JSONArray parameters = new JSONArray();
JSONObject jsonObject = new JSONObject();
jsonObject.put(Key,value);
jsonObject.put(Key,value);
parameters.put(jsonObject);
Log.i(TAG,parameters.toString());
JsonArrayRequest arrayRequest = new JsonArrayRequest(Request.Method.POST, httpUrl, parametersForPhp,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG,response.toString());
try {
//your code
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
RequestQueueSingleton.getInstance(getApplicationContext()).addToRequestQueue(arrayRequest);
}catch (Exception e){
e.printStackTrace();
}
}

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);

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

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

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));
}

Categories

Resources