Hello friends I am new in android I want play online mp3 file from url I used it async task for playing online mp3 file but problem is that it takes too much time for processing request I heard volley is best for this purpose now I used volley but when request send to server it block my main Ui thread while I heard volley itself manage aysc task and faster performance but in my case I did see anything like that please help how play audio from url faster and second without block main thread with help of volley here audio url and my code
"http://wpaorg.wordproject.com/bibles/app/audio/21/1/1.mp3"
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://wpaorg.wordproject.com/bibles/app/audio/21/"+booknumber+"/"+chapternumber+".mp3";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
Toast.makeText(ALLVERSE.this, ""+response, Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ALLVERSE.this, ""+error, Toast.LENGTH_SHORT).show();
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
when i tried send request it takes to much time and second block ui thread why?
Related
I wrote android app to read json using volley.
If i use example URL from internet - i don't have problem, the data is read. But when i try to read data from local host, I am getting an error.
The same data i can see in web browser in my emulator.
my URL: "http://10.0.2.2/volley_sample/get_data.php"
my code:
private void sendGetRequest() {
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
String url = "http://10.0.2.2/volley_sample/get_data.php"; //it doesn't work
//String url ="https://reqres.in/api/users/2"; //it works
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 10 characters of the response string.
get_response_text.setText("Response is: " + response.substring(0, 10));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
get_response_text.setText("That didn't work!");
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
adres "http://10.0.2.2/volley_sample/get_data.php" works in web browser in my emulator.
I tried also "http://192.168....", "127.0.0.1....", "localhost/volley_sample...." etc., and neither works.
adres "https://reqres.in/api/users/2" (example from internet) work without problem.
ofc. i added "<uses-permission android:name="android.permission.INTERNET"/>"
I have no idea what I am doing wrong :(
I'm building a tracking app for exercise. As the gps updates every 1 second, the latitude and longitude is added to an array. At the end of the exercise, when you press save, below method is executed, sending all co-ordinates to a database. Because it's an asynchronous request, the co-ordinates don't get loaded into the database in correct order. How can I fix this so it will wait until each iteration of loop is complete or something like that. Thanks
/* Inserts the latitude and longitude points from the latitudeAndLongitudePoints ArrayList
into the latitudeandlongitudepoints table in db*/
private void insertLatitudeAndLongitudePoints(){
//iterates though array of co-ordinates, and adds to database
for(int loop=0; loop<latitudeAndLongitudePoints.size();loop++) {
final int index = loop;
StringRequest stringRequest = new StringRequest(Request.Method.POST,
"http://rrush01.lampt.eeecs.qub.ac.uk/insertLatitudeAndLongitudePoints.php",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Error: " + error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Latitude", String.valueOf(latitudeAndLongitudePoints.get(index).latitude));
params.put("Longitude", String.valueOf(latitudeAndLongitudePoints.get(index).longitude));
params.put("User", AccountInfo.accountEmail);
return params;
}
};
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(stringRequest);
}
}
Add dependency for Volley library in your build.gradle.
compile 'com.android.volley:volley:1.0.0'
Volley is a network library which makes fast and easier to make HTTP Request for android application. Using Volley library we don’t need to create AsyncTask to make multiple API calls in volley there is RequestQueue where we can enqueue each request. Here in this example, We used Google place autocomplete API. We are going to make synchronous HTTP Request using volley. To make synchronous HTTP request make a RequestFuture object. And make JsonObjectRequest pass this parameter RequestMethod, URL, pass object of type Json and pass RequestFuture instance.
RequestFuture<JSONObject> requestFuture=RequestFuture.newFuture();
final String mURL = "https://maps.googleapis.com/maps/api/place/
autocomplete/json?key="+KEY+"&input=" + input;
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST,
mURL,new JSONObject(),requestFuture,requestFuture);
MySingleton.getInstance(mContext).addToRequestQueue(request);
Add your request in RequestQueue. Now, whenever the user makes an HTTP request each request added to RequestQueue.To get response object from the requestFuture we call get() method. And we also set a timeout of let’s say 10 seconds so we don’t block the UI thread indefinitely in case our request times out.
try {
JSONObject object= requestFuture.get(10,TimeUnit.SECONDS);
} catch (InterruptedException e|ExecutionException e|TimeoutException e) {
e.printStackTrace();
}
Hope this helps you to understand how we can use volley used to make the synchronous HTTP request
I am working with an API for the first time.
My need is that I need to form an URL with certain parameters out of which one parameter cannot be formed in the Main UI thread and has to be formed in the Background thread.
I am planning to use to volley library to post the GET request.
I am using the Needle library which helps in running background tasks. This is What I have tried till now.
Needle.onBackgroundThread().execute(new UiRelatedTask<String>() {
#Override
protected String doWork() {
return url = GetUrl();
}
#Override
protected void thenDoUiRelatedWork(String result1) {
Log.e("JSON", url);
final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener() {
#Override
public void onResponse(Object response) {
Log.e("JSON", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("JSON", error.toString());
}
});
RequestQueue queue = VolleyController.getInstance(Activity.this.getApplicationContext()).getRequestQueue();
queue.start();
queue.add(jsonObjectRequest);
}
});
But the Main problem is that After the GetUrl() method immediately the thenDoUiRelatedWork method is called hence the request is made using an Invalid URL as the URL will still be loading in the background and then when the loading of the URL is over I am logging the URL Which is right.
I cannot use an AysncTask as my app is already using three AsyncTaks and additionally two more could be activated by the user based on the feature he is using. And also the API request has to be done in various places (3-4 places) hence using an AsyncTask will not be suitable.
Can anyone help me to first form the URL fully in the Background and the use volley to post the GET request.
The server returns a "Last Modified" header based on when the data changes. Need to use this to cache the response in volley.
My Volley request looks something like this:
StringRequest req = new StringRequest(Request.Method.GET, requestUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray result = new JSONArray(response);
callback.onSuccess(result);
} catch (JSONException je) {
callback.onSuccess(new JSONArray());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Error: " + error.getMessage());
}
});
Can find examples to cache based on a fixed time - say cache for 5 mins:
Android Setup Volley to use from Cache
But this doesnt solve my purpose. The server response has to be invalidated based on the "Last Modified" header. So I'm expecting volley to make the request and get a 304 Not Modified response and hence serve the content from the cache.
Even tried a custom header parser something like this:
https://github.com/mcxiaoke/android-volley/blob/master/src/main/java/com/android/volley/toolbox/HttpHeaderParser.java
But this doesnt seem to do the trick either.
I am working on an Android App, in which I need to make a lot of http queries. Since Android has a constrain to prevent program making http request on UI thread, I have to use a lot of Async methods to get response from the server. I am not a guru of using callbacks, there's a code design problem I am facing now:
Basically, I have a activity to display. I want the app to make a HttpRequest to server when the activity is created, so I can prepare the content of the activity based on the query response.
Since I am using the Google Volley library to make http requests, my code design is:
// in the Activity
OnCreate(Bundle b){
String response = RequestManager.makeRequest(args);
// other works based on the response in this activity.
}
// RequestManager Class
public static String makeRequest(args){
String url = getUrl();
// response callback
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Don't know what to do here
}
};
// error callback
Response.ErrorListener errorListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// deal with errors
}
};
BuildRequestAndPushToQueue(url, responseListener, errorListener);
// No way to return the response!
}
I know my design is totally incorrect, because String response = RequestManager.makeRequest(args); is intent to wait for a blocking call, but the call is actually async.
My ultimate goal is to let the response String returned to some code in the activity, so it can use the activity context to do the rest works (like access to a imageview, etc). But I am not sure how to design the code flow to make this happen.