Volley is not pulling Json data from my URL - android

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

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

Convert Json object to an array

I need help in modifying my android studio code for converting Json object to an array. Bellow is the error in my log cat and the actual code.
This is the error message I am getting in the logcat:
04-03 12:01:16.727 19993-19993/com.errandit E/Volley: com.android.volley.ParseError: org.json.JSONException: Value {"data":[{"errand":"Shopping","charges":"500"},{"errand":"House Assistance","charges":"7000"},{"errand":"Pick - Up","charges":"2500"}],"success":1,"message":" 0 records found"} of type org.json.JSONObject cannot be converted to JSONArray
**I am trying to fetch the json array from my wamp server using the method below. **
private void getData(){
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading");
progressDialog.show();
final JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = response.getJSONObject(i);
Service service = new Service();
service.setName(jsonObject.getString("errand"));
service.setCharges(jsonObject.getInt("charges"));
serviceList.add(service);
} catch (JSONException e) {
e.printStackTrace();
progressDialog.dismiss();
}
}
adapter.notifyDataSetChanged();
progressDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley",error.toString());
progressDialog.dismiss();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
Change like below as You are getting JSONObject and inside it there is JSONArray named "data".
JsonObjectRequest jsonObjRequest = new JsonObjectRequest
(Request.Method.POST, url, jsonObj, new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject mResponse)
{
JSONArray response=mResponse.optJSONArray("data")
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = response.getJSONObject(i);
Service service = new Service();
service.setName(jsonObject.getString("errand"));
service.setCharges(jsonObject.getInt("charges"));
serviceList.add(service);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_SHORT).show();
}
});
// Add the request to the RequestQueue.
queue.add(jsonObjRequest);

Android Volley Not Updating URL data

When i run URL in browser its show with updated data but with Volley request URL data not update.
protected void getImagesArray() {
arrayList.clear();
final ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setCancelable(false);
progressDialog.show();
String url = "https://aditibendi3.000webhostapp.com/test_img/testarray.php";
JsonArrayRequest jsonObjectRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
progressDialog.dismiss();
Log.e(TAG, "onResponse: " + response.toString());
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = (JSONObject) response.get(i);
String image = jsonObject.getString("image");
model = new Model(image);
arrayList.add(model);
} catch (JSONException e) {
e.printStackTrace();
}
}
gridAdapter = new GridAdapter(MainActivity.this, arrayList);
gridAdapter.notifyDataSetChanged();
gridView.setAdapter(gridAdapter);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Log.e(TAG, "onErrorResponse: " + error.getMessage());
}
});
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
}
This is url response
[{"id":"11","image":"11.png"},{"id":"10","image":"10.png"},{"id":"9","image":"9.png"},{"id":"8","image":"8.png"},{"id":"7","image":"7.png"},{"id":"6","image":"6.png"},{"id":"5","image":"5.png"},{"id":"4","image":"4.jpg"},{"id":"3","image":"3.png"},{"id":"2","image":"2.png"},{"id":"1","image":"1.png"}]
and this is volley response
E/MainActivity: onResponse:
[{"id":"9","image":"9.png"},{"id":"8","image":"8.png"},{"id":"7","image":"7.png"},{"id":"6","image":"6.png"},{"id":"5","image":"5.png"},{"id":"4","image":"4.jpg"},{"id":"3","image":"3.png"},{"id":"2","image":"2.png"},{"id":"1","image":"1.png"}]
I have solved this issue by using this line
AppController.getInstance().getRequestQueue().getCache().remove(url);

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.

Consuming APIs with volley?

I am trying to consume APIs with the library volley, but i can't because it doesn't show me anything when I run the app.
I think the problem is that the URL API has that in it (json):
{"books":[{"book":{PARAMETERS...}}]}
so I can't access my parameters. Then my URL API doesn't have .json at the end of the URL but I don't think that's the problem.
public class MainActivity extends Activity {
private static final String TAG = MainActivity.class.getSimpleName();
private static final String url = "http://############";
private ProgressDialog pDialog;
private List<Books> booksList = new ArrayList<Books>();
private ListView listView;
private Adapter adapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list);
adapter = new Adapter(this, booksList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
// changing action bar color
//getActionBar().setBackgroundDrawable(
// new ColorDrawable(Color.parseColor("#1b1b1b")));
JsonArrayRequest booksReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Books books = new Books();
Books.setTitle(obj.getString("title"));
Books.setPhoto_url(obj.getString("image"));
booksList.add(books);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
Controller.getInstance().addToRequestQueue(booksReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
My json in the URL API:
{
"books": [
{
"book": {
"title": "namebook",
"photo_url": {
"src": "http://######",
"alt": ""
}
}
}
]
}
So how can I get to show them?
Try using
JsonObjectRequest(int method, String url, JSONObject jsonRequest, Listener<JSONObject> listener, ErrorListener errorListener) instead of JsonArrayRequest as your response seems to be JSONObject
Also, there is no such key image in your response
Books.setPhoto_url(obj.getString("image"));
Looking at your JSON response, if you try following code, it should work:
JsonObjectRequest artistReq = new JsonObjectRequest(Method.GET, url, null, new Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
hidePDialog();
try {
if (response.optJSONArray("books") != null) {
JSONArray books = response.getJSONArray("books");
for (int i = 0; i < books.length(); i++) {
JSONObject book = books.getJSONObject(i);
String title = book.getString("title");
// next K,V pair consist of JSONObject photo_url
JSONObject photoUrl = book.getJSONObject("photo_url");
String photoSrc = photoUrl.getString("src");
String photoAlt = photoUrl.getString("alt");
// use extracted values in your Book object
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
Hope it would help!

Categories

Resources