I am currently using Volley to extract JSON contents using the following code.
JsonArrayRequest servicesStatus = new JsonArrayRequest(url1,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
// Having obj to process further
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
Now, I want one more JSON handler for the new URL and the dialog to be closed once it has successfully downloaded from both the URLs.
I tried to copy paste the above thing with url1 replaced by url2 and different jsonarrayrequest name. And added the hideDialog() in the second one. But the second one is not being called at all.
If you want make multiple request then you will have to add your Request to Queue. You can do it like this:
RequestQueue request = Volley.newRequestQueue(Context);
request.add(FirstRequest);
request.add(SecondRequest);
This should help you to add multiple request in Volley.
Related
The jason array request code goes like this:
JsonArrayRequest arrayRequest = new JsonArrayRequest(Request.Method.GET,url, (JSONArray) null , new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
Log.d("Response:", String.valueOf(response.getJSONObject(0)));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "Response not recieved", Toast.LENGTH_SHORT).show();
}
});
And I've used a singleton instance of a request queue, to fetch the data,
AppController.getInstance(context.getApplicationContext()).addToRequestQueue(arrayRequest);
I'm using an api service that supplies a bunch of questions (The api generates a url, which returns a collection of JSON Objects, An Array (Just try and Open the url link, the json array will be seen)
But when I run the app, the request is not even getting a response,the progam flow is going into the error listner block.
Can someone explain this behaviour? Is it because the JSON array supplied by the url, has nested arrays? Why?
I tried reading and anlyzing other questions here, which might have the same issue, But i found nothing.
You want to just change JsonArrayRequest to JsonObjectRequest:
Please copy and paste below code:
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("TAG", response.toString());
try {
JSONArray jsonArray = response.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String category = jsonObject.getString("category");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("TAG", "Error: " + error.getMessage());
// hide the progress dialog
}
});
AppController.getInstance().addToRequestQueue(jsonObjReq, "TAG");
Follow this link for learn other request: Androidhive
I was working on parsing the nested JSON objects using Volley and I got the answer from the stackoverflow itself.
Parsing Nested JSON Objects using Volley
But I think the code can be optimized without the if else and also I have to display a text "No Data" if the volley request is null or no data received. I tried to check using adapter.isEmpty, adapter.getCount()
None of it worked.
This is my code
datalist=false;
progressBar.setVisibility(View.VISIBLE);
StringRequest stringRequest = new StringRequest(Request.Method.GET, JSON_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
schemeslist=false;
progressBar.setVisibility(View.INVISIBLE);
try {
JSONObject obj = new JSONObject(response);
JSONObject one = obj.getJSONObject("getProjectDetailsResult");
JSONObject two = one.getJSONObject("NewDataSet");
if(two.get("Rec") instanceof JSONArray) {
datalist=true;
JSONArray heroArray = two.getJSONArray("Rec");
for (int i = 0; i < heroArray.length(); i++) {
JSONObject heroObject = heroArray.getJSONObject(i);
APIModel hero = new APIModel(heroObject.getString("decProjectID"),
heroObject.getString("intProjectSlNo"),
heroObject.getString("chvProjectName"),
heroObject.getString("chvProjectNameEng"),
heroObject.getString("chrProjCatCode"),
heroObject.getString("chvEngProjCategory"),
heroObject.getString("nchvSecType"),
heroObject.getString("chvEngSecType"),
heroObject.getString("chvImplOfficerDesg"),
heroObject.getString("chvImplOfficerDesgEng"),
heroObject.getString("singleYrAmt"),
heroObject.getString("TotExp"),
heroObject.getString("percentage"));
heroList.add(hero);
}
} else {
datalist=true;
JSONObject heroObject = two.getJSONObject("Rec");
APIModel hero = new APIModel(heroObject.getString("decProjectID"),
heroObject.getString("intProjectSlNo"),
heroObject.getString("chvProjectName"),
heroObject.getString("chvProjectNameEng"),
heroObject.getString("chrProjCatCode"),
heroObject.getString("chvEngProjCategory"),
heroObject.getString("nchvSecType"),
heroObject.getString("chvEngSecType"),
heroObject.getString("chvImplOfficerDesg"),
heroObject.getString("chvImplOfficerDesgEng"),
heroObject.getString("singleYrAmt"),
heroObject.getString("TotExp"),
heroObject.getString("percentage"));
heroList.add(hero);
}
ListViewAdapter adapter = new ListViewAdapter(heroList, getApplicationContext());
//adding the adapter to listview
listView.setAdapter(adapter);
// Toast.makeText(getApplicationContext(), " " + listView.getAdapter().getCount(),Toast.LENGTH_SHORT).show();
if(!datalist){
txtNoData.setVisibility(View.VISIBLE);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//displaying the error in toast if occurrs
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
//creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//adding the string request to request queue
requestQueue.add(stringRequest);
Can anyone tell me where should I put the if condition to work?
I checked with a toast for getting item count, but if there is no data, it is displaying blank and not 0. So I am not able to check
You can check size() of data list(heroList), size() is zero means you have no data.
try this
if(heroList.size() == 0){
txtNoData.setVisibility(View.VISIBLE);
}
I am using volley for this .
this is my code for fetching data from sqlite .Help me to send this json data to server....Thanks in advance
code : List<ConstTempPlaceorederProduct> contactss = db.getAllContactsPlaceorder();
JSONObject objProduct = new JSONObject();
JSONArray productData = new JSONArray();
for (ConstTempPlaceorederProduct cn : contactss) {
prod_id=cn.getPid();
prod_ref_placeorder_id=cn.getRef_pid();
prod_comp_name=cn.getProd_comp_name();
prod_cat_name=cn.getProd_cat_name();
prod_brand_name=cn.getProd_brand_name();
prod_size=cn.getProd_size();
prod_unit=cn.getProd_unit();
prod_mrp=cn.getProd_mrp();
prod_quantity=cn.getProd_quantity();
prod_name=cn.getProd_name();
prod_total=cn.getProd_total();
JSONObject prodData = new JSONObject();
prodData.put("id", prod_id);
prodData.put("name", prod_brand_name);
productData.put(prodData);
}
objProduct.put("all product", productData);
String result = objProduct.toString();
This is simple sketch. Try this
// Creating the JsonArrayRequest class called arrayreq, passing the required parameters
//JsonURL is the URL to be fetched from
JsonArrayRequest arrayreq = new JsonArrayRequest(JsonURL,
// The second parameter Listener overrides the method onResponse() and passes
//JSONArray as a parameter
new Response.Listener<JSONArray>() {
// Takes the response from the JSON request
#Override
public void onResponse(JSONArray response) {
try {
// Retrieves first JSON object in outer array
JSONObject jsonResponseObj = response.getJSONObject(0);
}
// Try and catch are included to handle any errors due to JSON
catch (JSONException e) {
// If an error occurs, this prints the error to the log
e.printStackTrace();
}
}
},
// The final parameter overrides the method onErrorResponse() and passes VolleyError
//as a parameter
new Response.ErrorListener() {
#Override
// Handles errors that occur due to Volley
public void onErrorResponse(VolleyError error) {
Log.e("Volley", "Error");
}
}
);
// Adds the JSON array to the request queue
requestQueue.add(productData);
}
}
I want to ask, I have session data and I want to post the session data to server.. I am using JsonArrayRequest..
Below is my code:
// untuk menampilkan semua data pada listview
private void callVolley(){
itemList.clear();
adapter.notifyDataSetChanged();
swipe.setRefreshing(true);
session.getLocalSession(LocalSession.KEY_USERNAME);
// membuat request JSON
JsonArrayRequest jArr = new JsonArrayRequest(url_select, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Data item = new Data();
item.setId(obj.getString(TAG_ID));
item.setNama(obj.getString(TAG_NAMA));
item.setAlamat(obj.getString(TAG_ALAMAT));
// menambah item ke array
itemList.add(item);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifikasi adanya perubahan data pada adapter
adapter.notifyDataSetChanged();
swipe.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
swipe.setRefreshing(false);
}
});
// menambah request ke request queue
AppController.getInstance().addToRequestQueue(jArr);
}
Please somebody help me, where I can post the data....
this session in android:
session.getLocalSession(LocalSession.KEY_USERNAME);
I am using this code and showing all the data, I mean I just want to show some data with parameter session
JsonArrayRequest jArr = new JsonArrayRequest(url_select, new Response.Listener()
Any help will be appreciated, Thanks.
As i can see you are using volley and creating instance of JsonArrayRequest, so you direct pass your array with JsonArrayReuest constructor please see the below code snippet.
public JsonArrayRequest(int method, String url, JSONArray yourArray,
Listener<JSONArray> listener, ErrorListener errorListener) {
super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener,
errorListener);
}
I have to create an android application which shows some reports and images in Recycler view using json volley request it works when internet is available i also need to show the once loaded data in recycler view when internet is not available here is the code i used to select data when internet is available
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.GET, Config.DATA_URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String str = response.toString();
loading.hide();
JSONArray arr = response.getJSONArray("Stock_Report");
parseData(arr);
} catch (JSONException e) {
e.printStackTrace();
}
// now you have the array. in this array you have the jsonObjects
// iterate on this array using a for loop and parse like you did before
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
//Adding request to the queue
requestQueue.add(jsObjRequest);
}
please help me to find better solution to show this data when internet is not available also thanks in advance