How to execute web request in its own thread?
I am creating an android application which has to execute web requests in the background and then handle the received data and modify the user interface according to the server response.
The goal of posting requests and handling data in the background is to avoid the freezing of user interface. Currently however I notice that the user interface is freezing so I am not sure the logic is working as it is supposed to.
Here is the part of code which is supposed to post requests and handle responses in its own thread and then pass the data to GUI:
public class ServerConnection {
Queue<String> requests;
...
DefaultHttpClient httpClient;
HttpHost targetHost;
Handler handler;
ServerResponseHandler responseHandler;
Activity activity;
public ServerConnection(Activity activity){
this.activity = activity;
this.responseHandler = (ServerResponseHandler) activity;
httpClient = new DefaultHttpClient();
targetHost = new HttpHost(TARGET_DOMAIN, 80, "http");
requests = new LinkedList<String>();
}
private Runnable requestSender = new Runnable(){
@Override
public void run() {
if(!requests.isEmpty()){
String requestString = requests.remove();
HttpGet httpGet = new HttpGet(requestString);
httpGet.addHeader("Accept", "text/xml");
String encodingString = "testuser:testpass";
String sEncodedString = Base64Coder.encodeString(encodingString);
try{
String sContent = fetchURL(requestString, sEncodedString);
XMLParser xmlParser = new XMLParser();
List <Product> products = xmlParser.getProducts(sContent);
responseHandler.onProductsResponse(products);
}
catch(Exception ex){
Log.e(TAG, ex.getMessage());
}
}
}
};
public void sendRequest(String requestString){
requests.add(requestString);
handler = new Handler();
handler.post(requestSender);
}
The method sendRequest() is called from the main activity which implements ServerResponseHandler. I guess the request is executed in its own thread and by calling
responseHandler.onProductsResponse(products);
the list of products (data from the web) is passed to main activity. Anyway due to poor performance I would appreciate if anyone could correct any possible issue in the logic above or suggest any other (better) option.
Asked by: Patrick725 | Posted: 20-01-2022
Answer 1
I'd suggest you take a look at ASyncTask class (available since Android 1.5).
It simplifies the process of creating a background Thread that synchronizes with the GUI thread once it's complete.
You should be able to achieve what you're trying using code something list this
private class DownloadFilesTask extends AsyncTask<String, List<Product>, Integer> {
protected List<Products> doInBackground(String... requestStrings) {
int count = requestStrings.length;
int results = 0;
for (int i = 0; i < count; i++) {
String requestString = requestStrings[i];
HttpGet httpGet = new HttpGet(requestString);
httpGet.addHeader("Accept", "text/xml");
String encodingString = "testuser:testpass";
String sEncodedString = Base64Coder.encodeString(encodingString);
try{
String sContent = fetchURL(requestString, sEncodedString);
XMLParser xmlParser = new XMLParser();
List <Product> products = xmlParser.getProducts(sContent);
results++;
publishProgress(products);
}
catch(Exception ex){
Log.e(TAG, ex.getMessage());
}
}
return results;
}
protected void onProgressUpdate(Integer... progress) {
// TODO You are on the GUI thread, and the first element in
// the progress parameter contains the last progress
// published from doInBackground, so update your GUI
}
protected void onPostExecute(int result) {
// Processing is complete, result contains the number of
// results you processed
}
}
And execute by calling
new DownloadFilesTask().execute(url1, url2, url3);
Answered by: Julia975 | Posted: 21-02-2022
Answer 2
According to the handler javadoc, I don't think the post()
method create any threads. If I'm right it execute the Runnable
on the thread to which the handler is attached. So in this case this is the activity thread so the UI thread ! That's why you have poor performance.
You have to implement a Thread
which execute your Runnable
. But by doing that, you won't be able to update your activity like you currently do by calling :
responseHandler.onProductsResponse(products);
This is because you are not any more in the UI thread, and only the UI thread is authorized to interact with the UI (so the activity).
So you have to replace this call by accessing your Handler
.
Message msg = handler.obtainMessage();
Bundle bundle = new Bundle();
bundle.putSerializable( "products", products ); //not sure it will pass here
msg.setData( bundle );
handler.sendMessage( msg );
And implementing the handleMessage()
method for your Handler
:
@Override
public void handleMessage( Message msg )
{
List <Product> products = msg.getData().getSerializable( "products" );
responseHandler.onProductsResponse(products);
}
Last but not least : the Handler
has to still be created in the activity thread.
Similar questions
android - Is it possible to execute more than one http request in a queue?
I want to add more than one HTML requests to a queue. These requests must be executed one by one automatically and I need to handle responses of each request separately. How can I do this?
how to execute PUT request in Android Volley?
I am currently using GsonRequest to issue rest GET requests. Not clear on what to use for PUT requests where I need to send over a whole JSon object to be updated. The Request object will accept PUT but I'm not sure how place the JSon object that is expected.
Here is my json to be PUT:
{
prop1 : true,
prop2 : false,
prop4 : true
}
Here is how its submitted in apiary.io f...
android - execute request without adding listner
In DataDroid Library, for executing request we use
execute(request, listner)
Is there any method for executing request without using listner?
I need to send Information to server and for which the response is not related to user.So, I will handle error and success case in Operation.
I dont want to override methods :
onRequestFinished(),
onRequestConnectionError(),
...
How to execute a http request when device is about to close in android
When a user want to exit my app an asynk task is executed before my app is closed.My problem is that when my app runs in background and the user decide to close his device this asynk is not executed.How can i solve this problem?
Android cant execute POST request after GET
My problem is this: after the GET request authorization and save cookies trying to perform a POST request to add data, but the server responds with 500 code. What's funny, because if POST query string form in a browser, it is executed correctly. The code below.
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(site + "/admin/users/login_do/?login=admin&password=demo")...
mysql - how to execute HTTP POST request in android without using Json
I have made this code where i am to send the data to a MYSQL Database using POST request. I have made the following code using POST request. So,just wanted to ask first IF THIS CODE WOULD RUN WELL OR NOT
And i would b very grateful to that person if someone could just tell m what specifically is the setRequestProperty("Key","Value") method used for and what is meant by this KEY and VALUE in it.
I have provi...
android - Anko's execute the sqlite request but don't execute the next lines
I want to make a request on my internal database on Android but when my request Anko is done, the lines present in the UiThread are not done immediately.
To explain what happens, the line "Log.d" is execute before the UiThread
Can you help me?
for(i in 0 until jsonArrayM.length()) {
val json = jsonArrayM.getJSONObject(i)
doAsync {
val carteByName = bdd.getDatasByN...
android - How to execute a remote service
I have a service MyService.java in Application "ServiceDemo". The manifest of this application looks like this
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.moto.dev"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
...
In Android, how to execute a service as a different user?
For example, is there any way to define a service to run as 'system' UID or GID?
Or any way to add your app to the 'system' group?
java - Can android execute string as code?
So basically I would like my app to read info from a database, this info would be a string that is valid java code. Once read, I would like my app to execute this string as if it were code. Is there any functionality packaged with the android sdk that supports this?
Essentially I want the phone to populate some data with information queried from a database. One of these pieces of information would be a statement li...
Android - Execute action when phone is locked
I want to know how I can execute some action, or continue listening to sensor or battery change events when the phone is locked. (When the phone is locked it stops listening to sensor changes.)
I've tried with wakelocks but I it doesn't work (maybe I'm using it wrong).
Any help would be appreciated.
java - How can I execute some code while a view is pressed (held down) Android
I'm writing a small app and I need to run some code while the user holds down a screen button, an ImageView to be more precise. I have tried with onTouchEvent, but the code only executes in an actual event (down, up or move).
I would like my code to execute while I hold the button down. Any idea on how to do this?
This is what I tried
myImageView.setOnLongClickListener (new OnLongClickListener()
...
linux - How to get a script in init.d to execute on boot in Android?
Part of my android app's functionality it to place a script I have written in init.d, so that it will be executed on every startup. (obviously my app is for root users only)
Here's what I am doing:
busybox mount -o rw,remount /system"
busybox cp -f /sdcard/*******/script /system/etc/init.d/script
busybox chmod +x /etc/init.d/script
update-rc.d script 99
The "update-...
Execute Javascript in HTML file from within Android
I am using Android and I have an HTML file which contains some Javascript. However, I am not able to get the Javascript code to execute. What do I need to do in order to run this code? Thanks in advance for any help.
java - How to execute some code when new email arrives in Android?
I am new in Android.
How can I execute some code when new email arrives (gmail) in Android? Is there a way to do that?
execute service at particular time android
I am making GPS tracker application, and after 1 hrs I got the updated data and store into data base.
then at 12AM I want to send all data to particular email ID.
So what I have to use so it send email at 12AM only
How to execute Android 2.3 Source code?
I downloaded the Android 2.3 source code. My question is how can i execute individual code from that source code?
can any one help me....?
Thanks and Regards
Shiva
Still can't find your answer? Check out these communities...
Android Google Support | Android Community | Android Community (Facebook) | Dev.io Android