Volley JsonObjectRequest not fetching data - android

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

Related

Volley is not pulling Json data from my URL

people so I have a valid URL with JSON data in it, I pull the data with volley but it's not working for some reason, when I change the URL it works. But I need to use this URL with this data in my project. I think the structure of the URL is the problem, but I don't know how to fix it, Please help. Thank you!
The URL I am using is https://zlatnakopacka.mk/api/TopOfferPreview_feed?source=zk
public class TestOne extends AppCompatActivity {
String url = "https://zlatnakopacka.mk/api/TopOfferPreview_feed?source=zk";
RecyclerView recyclerView;
PonudiAdapter adaptor;
ArrayList<Ponudi> ponudis;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_one);
switchSve = findViewById(R.id.switch1);
recyclerView = findViewById(R.id.testRecycler);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adaptor = new PonudiAdapter(getApplicationContext());
recyclerView.setAdapter(adaptor);
ponudis = new ArrayList<>();
getData("1");
switchSve.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked == true) {
getData("sve");
} else {
getData("1");
}
}
});
private void getData(final String Sport) {
// final ProgressDialog progressDialog = new ProgressDialog(this);
// progressDialog.setMessage("Се вчитува...");
// progressDialog.show();
ponudis.clear();
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
Ponudi ponudi = new Ponudi();
ponudi.setSh_sport_id(jsonObject.getString("sh_sport_id"));
ponudi.setTim1(jsonObject.getString("tim1"));
ponudi.setTim2(jsonObject.getString("tim2"));
ponudi.setLiga_header(jsonObject.getString("liga_header"));
ponudi.setDatum_vreme(jsonObject.getString("datum_vreme"));
ponudi.setKh1(jsonObject.getString("kh1"));
ponudi.setKhx(jsonObject.getString("khx"));
ponudi.setKh2(jsonObject.getString("kh2"));
ponudi.setKod(jsonObject.getString("broj"));
if (ponudi.getSh_sport_id().equals(Sport)) {
ponudis.add(ponudi);
} if (Sport.equals("sve")) {
ponudis.add(ponudi);
}
}
} catch (JSONException e) {
Toast.makeText(TestOne.this, "Json is not valid", Toast.LENGTH_SHORT).show();
}
adaptor.setData(ponudis);
adaptor.notifyDataSetChanged();
// progressDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// progressDialog.dismiss();
Toast.makeText(TestOne.this, "Error", Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
}
In response you are getting below error.
"javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found."
I found some answers here is reference that will help you.
Trusting all certificates using HttpClient over HTTPS
Replace getData() Method
Write This method -
private void getData() {
// final ProgressDialog progressDialog = new ProgressDialog(this);
// progressDialog.setMessage("Се вчитува...");
// progressDialog.show();
ponudis.clear();
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
Ponudi ponudi = new Ponudi();
ponudi.setSh_sport_id(jsonObject.getString("sh_sport_id"));
ponudi.setTim1(jsonObject.getString("tim1"));
ponudi.setTim2(jsonObject.getString("tim2"));
ponudi.setLiga_header(jsonObject.getString("liga_header"));
ponudi.setDatum_vreme(jsonObject.getString("datum_vreme"));
ponudi.setKh1(jsonObject.getString("kh1"));
ponudi.setKhx(jsonObject.getString("khx"));
ponudi.setKh2(jsonObject.getString("kh2"));
ponudi.setKod(jsonObject.getString("broj"));
if (ponudi.getSh_sport_id().equals("1")) {
ponudis.add(ponudi);
} else if(ponudi.getSh_sport_id().equals("sve")) {
ponudis.add(ponudi);
}
}
} catch (JSONException e) {
Toast.makeText(TestOne.this, "Json is not valid", Toast.LENGTH_SHORT).show();
}
adaptor.setData(ponudis);
adaptor.notifyDataSetChanged();
// progressDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// progressDialog.dismiss();
Toast.makeText(TestOne.this, "Error", Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}

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

i want send json file to my server from android what should i do in doInBackground method?

my backend is laravel and i want to send json file to a specific rout
i already create my json plz help
public class MainActivity extends AppCompatActivity {
EditText usernameview;
EditText passwordview;
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
usernameview = (EditText)findViewById(R.id.username) ;
passwordview = (EditText)findViewById(R.id.password) ;
Button login = (Button) findViewById(R.id.loginid);
}
public void senddatatoserver(View v) {
String username= usernameview.getText().toString();
String password = passwordview.getText().toString();
JSONObject login = new JSONObject();
try {
login.put("username",username);
login.put("password",password);
} catch (JSONException e) {
e.printStackTrace();
}
if (login.length() > 0) {
new SendDataToServer().execute(String.valueOf(login));
}
}
here is my class to send data i just wanna know what i should write in doinbackground methode
class SendDataToServer extends AsyncTask<String,String,String> {
#Override
protected String doInBackground(String... params) {
}
#Override
protected void onPostExecute(String s) {
}
}
you can use volley to send request
StringRequest stringRequest = new StringRequest(Request.Method.POST, YOUR_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
for (int i = 0; i < response.length(); i++) {
JSONObject json; // convert String to JSONObject
try {
json = new JSONObject(response);
JSONArray jsonArray = json.getJSONArray("data");
lyric_string = jsonArray.getJSONObject(0).getString("song_lyric");
artist_string = jsonArray.getJSONObject(0).getString("song_artist");
//album_string = jsonArray.getJSONObject(0).getString("song_album");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//error message
dismissDialog();
lyric.setText("Sorry No Lyric Found");
lyric.setVisibility(View.VISIBLE);
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("song_name", "A song Name");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);

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

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