I have used Android Volley library for loading and caching of data coming from a server. The following is the simple code I used.
// Creating volley request queue
RequestQueue queue = Volley.newRequestQueue(getActivity());
// Creating volley request obj
JsonArrayRequest mReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
progressBar.setVisibility(View.GONE);
// update the data fetched from server
if(mList != null)
{
mList.clear();
}
parseVolleyResponse(response);
// notifying list adapter about data changes
// so that it renders the list view with updated data
rAdapter.notifyDataSetChanged();
Log.d("notifyDataSetChanged", "notifyDataSetChanged");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding volley request to the queue
queue.add(mReq);
The loading and caching are working fine. Now, I want to display a message like "15 new data available. Tap to load." at the top of my layout whenever new data is available at server end i.e. I want to notify whenever new data is available along with its length. How can I do that? Should I use this Entry entry = queue.getCache().get(url); to check the difference between cache and network? Please help with the coding.
Related
I am trying to fetch a JSON response from OpenWeatherAPI to incorporate the current weather in my app. I have used volley to make a simple request to fetch the JSON response, but every time, I do not get the response. Instead, it always triggers the onErrorResponse method. What do I change to make this work?
I have added the uses Internet Permission in my manifest.
I have tried the solution to fetch JSON responses from many sources including the Official Android Developers Documentation, Other Questions from Stack Overflow, etc, but all of them failed.
I first used JSONObjectRequest instead of StringRequest, but even that did not provide me the results I required.
/*
Create a request queue to fetch the JSONObject response.
*/
RequestQueue queue = Volley.newRequestQueue(Objects.requireNonNull(getContext()));
/*
JSON Object request.
*/
StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(getContext(), response, Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(), "No JSON", Toast.LENGTH_SHORT).show();
}
});
queue.add(request);
I expect the Toast to show the response, but The Toast shows "No JSON".
Add "https://" before your URL. You will get a response on your browser, but will not in Android.
I want to use Volley to get a JSON response from some website, so I started testing it. Here is my code plain and simple:
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.GET, "http://api.androidhive.info/volley/person_object.json", null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
json = response;
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
error.printStackTrace();
}
});
int x = json.length();
After the request is made the response is always null. Neither an error is raised neither the request succeeds. Which is really confusing. As you can see I am assigning the value of the response to a variable named json which is of the same type. When I debug the application by putting a breakpoint on the onResponse method, onErrorResponse method and on the last line, the debugger only hits the last line the variables watches indicate that the value of the response is null.
I have tried more than one URL
http://simplifiedcoding.16mb.com/UserRegistration/json.php
https://androidtutorialpoint.com/api/volleyString
I have added Volley via gradle
compile 'com.android.volley:volley:1.0.0'
Put it in a RequestQueue
RequestQueue queue = Volley.newRequestQueue(this);
Then
queue.add(jsObjRequest);
Or
ApplicationController.getInstance().addToRequestQueue(jsObjRequest);
You need to add the request to the queue for the asynchronous request to work.
RequestQueue requestQueue= Volley.newRequestQueue(this)
requestQueue.add(jsObjRequest);
I have url that has a json Array which contains a large amount of data.
I call the url with volly jsonArrayRequest like this
public void makeJsonArrayReq(){
showProgressDialog();
JsonArrayRequest req = new JsonArrayRequest(Const.URL_IPD_ADMITED,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("response ================", response.toString());
textView.setText(response.toString());
hideProgressDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Error", "Error: " + error.getMessage());
textView.setText("Error Occurs ");
hideProgressDialog();
}
});
AppController.getInstance().addToRequestQueue(req, "array");
}
My devise shows progressDialog for some time after that time it hang out the app then after a few minute it shows the response in the texview but it very lengthy process and it same when internet connection off and extract from volley cache. How can I handle the URL in my apps?
You need to change your api a bit to support pagination. There are several pagination techniques available, you have to choose one that suites your case.
In Android you can save the last fetched pageNumber(if that is what your API returns as page identifier) and your api should accept this variable in request (mostly through query params)
http://43.255.22.123:3000/android/mis/get/ipdAdmitPatMd?pageId=1
And in the next request it should update the pageId to 2.
Since the question is too broad hence providing exact code solution is not possible therefore I have explained the concept.
I tried to update database on server with calling API by using Google Volley. But somehow the database won't updated. The issue doesn't exist while retrieving data (Method.GET)
Here my snipet code :
HashMap<String, String> params = new HashMap<>();
params.put(.....);
JsonObjectRequest postReq = new JsonObjectRequest(Request.Method.POST,
Api.URL_POST_DATA, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
progressDialog.setVisibility(View.GONE);
if (response.toString().equalsIgnoreCase("{\"result\":\"OK\"}")) {
Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.setVisibility(View.GONE);
Toast.makeText(MainActivity.this, "Check internet connection", Toast.LENGTH_SHORT).show();
}
});
postReq.setRetryPolicy(new DefaultRetryPolicy(10000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
postReq.setShouldCache(false);
VolleyHelper.getInstance(this).addToRequestQueue(postReq);
VolleyHelper.getInstance(this).getRequestQueue().getCache().invalidate(Api.URL_POST_DATA, true);
Then i tried update database manually by using PostMan to make sure that the problem not on my API side and my database successfully updated.
Did i doing wrong on my code ? Any helps will be really appreciated.
Thanks
Set the Content-Type value of your request header to "application/json". This may be the issue.
In order to do that, you need to override the getHeaders() method on your request object.
Thanks guys for the clue, i did wrong. I sent the HashMap but on my request i sent the JsonObjectRequest. So i used StringObject instead of JsonObjectRequest.
What I want to achieve is to be able to observe changes in my web service and then update my textview if there is any change. I am currently using timer to achieve this by running it every x second. The problem though, is that the memory leaks so it's not a good solution. Now I stumbled upon this rxjava/rxjava but I'm confused on how to use it. The documentation is confusing to me and I can't find alot of tutorials about this. I am using volley to get data from my web service by the way.
this is the Observable that someone on answered on my other question but I'm getting an error which is "Incompatible types" on return sendRequest.
Observable.interval(500, TimeUnit.MILLISECONDS, Schedulers.io()).map(new Func1<Long, Object>() {
#Override
public Object call(Long tick) {
return sendRequest();
}
}).observeOn(AndroidSchedulers.mainThread()).subscribe();
here is my volley request code
public void sendRequest(){
//While the app fetched data we are displaying a progress dialog
//final ProgressDialog loading = ProgressDialog.show(this,"Fetching Data","Please wait...",false,false);
StringRequest stringRequest = new StringRequest(JSON_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//text.setText(response);
//loading.dismiss();
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
requestQueue.add(stringRequest);
}
private void showJSON(String json){
ParseJson pj = new ParseJson(json);
pj.parseJSON();
text.setText(ParseJson.playing[0]);
}
Your method sendRequest doesn't return anything(void). You can either return null or something.
#Override
public Object call(Long tick) {
sendRequest();
return null;
}
I would suggest you firstly read Java basics instead of writing Android app.
Use push notifications to send messages from the server to the users when data is updated and avoid sending unwanted requests to the server.
Then you can send the request for new data only when notified and update the Observer someway, maybe use a rx subject, or better store the data in SQLite table and observe changes from the DB.
Recommend this to create a rx stream from sqlite
https://github.com/square/sqlbrite
GCM: https://developers.google.com/cloud-messaging/