How to extract HttpResponse into a separate thread? - android

I have in Android:
HttpResponse httpGetResponse = client.execute(request);
...
Log.e("HEADER: ", httpGetResponse.getStatusLine().toString() );
i.e. I execute a HttpGet request and then do something with the response. Yet I want to somehow place it into a separate thread, so that the UI thread won't freeze while the server responds. What do you think would be the best way to do that?
Thansk!

Wrap your request into an AsyncTask and do the actual request in the doInBackground. As you probably have to use the output on the UI thread you probably should return the data you need from within the doInBackground and use the postExecute option in AsyncTask.

The simplest way is to use an AsyncTask.

Related

Android: Send JSON String created by Gson library with HttpURLConnection API to the localhost

I have JSON string created by Gson library and I want to send this string with HttpURLConnection API "GET" to the localhost server(wamp). I will run the app on my S4 device that is connected with my laptop vie the USB cabel.
I appreciate any help.
I have this JSON string:
{
"latitude":80.86907321,
"longitude":15.66542435,
"formatted":"22.04.2015 11:11:00",
"route":4
}
I have this method in the inner class "MyLocationListener":
private String convertToJSON(double pLong, double pLat, String formatted) {
//envelop the data in JSON format.
Data d = new Data(pLat, pLong, formatted,route_number);
Gson gson = new GsonBuilder().registerTypeAdapter(Data.class, new DataSerializer()).create();
return gson.toJson(d);
}
First, you have to understand the AsyncTask.
AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent package such as Executor, ThreadPoolExecutor and FutureTask.
An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.
Here a link to AndroidDevelopper AsyncTask page
Second, you should creating a class dedicate to DB operations. Personnaly, I prefer HttpClient from Apache, but if you prefer HttpURLConnection, check this page. Both HttpClient & HttpURLConnection are defined (and some examples)
And, why not using POST if you want sending JSON datas?
Last thing : if you are using wamp with your localhost on a device, your url should be : http://192.168.X.X, but on emulator http://127.0.0.1
Hope this helps.

Get value for volley request to finish before proceeding with method? Android Java

its my first time asking a question here, so please tell me if I missed to include something.
I have a method that prints returns a String. Inside it, is an asychronous volley request that retrieves a specific value to be added to the String. The problem is that the request is made, but since it's an asynchronous request, the method still proceeds and returns the String even if it still doesn't have the value from the request. The request completes afterwards. So the question is, is there a way to make the method wait for a specific variable to have a value before proceeding, without freezing the UI? Should I create a new thread instead?
Code below is not the actual codes I have but it shows the outline.
public String getStr{
StringBuilder sb = new StringBuilder();
String strOne;
// code here..
// asynchronous request here..
// code here..
sb.append(strOne)
// code here..
return sb.toString();
}
The asychronous request refers to the volley request.
Any help is appreciated. Thanks in advance!
You should handle the response in onResponse (#Override) method. Take a look in this tutorial:
Asynchronous HTTP Requests in Android Using Volley
If you want to return the response to another class to handle it there, I suggest you to implement an interface. I could post the code for this here, but I aswered a question like this here:
Volley , Wait for response to return wait until use flag - answer

Android socket programming approach

I am making a client socket program in Android, it sends and receive data correctly, but my problem is the client is running in the "doInBackground" of the Asyntask. I need the info the client receives from the server in order to continue with rest the processes, and there is my question and the approach I need, how I make the program wait until the client socket method receives the data before calling the others methods?
Example :
1)
MyClientTask myClientTask = new MyClientTask(server, port);
myClientTask.execute();
2) Do_something_with _data_received();
3) Do_something_else_with _data_received();
The point 2 will run with the client socket at the same time in this approach.
Thanks in advance.
If you are working with a fragment pass the fragment to the asynctask.
Do the logic in doInBackground() then fragment.method() in onPostExecute().
onPreexecute and onPostExecute run on the UI thread, doInBackground() runs on a separate thread.
Hint: you could replace the view with a progress(circular) untill asynctask is done,
onPostExecute(){
if(fragment.isAdded()){
fragment.drawUI();
}
}
where the drawUI() is the logic that makes your layoutView and makes it visible.
onPostExecute(){
2) Do_something_with _data_received();
3) Do_something_else_with _data_received();
}
TIP : Don't call .get() of asynctask because it will freeze UI thread.

What is the relationship between AsyncTask and Activity? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I have been given an assignment to develop an application that send server request and get response and then using JSON parsing, display the data content into a ListView.
I don't understand about AsyncTask and how to integrate all classes. Hope you will accommodate.
regards
What should you do?
The first, send a request to server
The second, get response
The thirds, Parse data from InputStream which you got from Response
The fourth, show on ListView
Oh, done.
Right now,
Look into the first step.
How to send a request to server?
You can use HttpURLConnection or HttpClient
So, What's problem when you send a request to server?
I think you know when you send a request to server, you will get some problem: Network bad, InputStream from Server too large, ...
And how to resolve?
With single statement, you can't take along time to do. So with task which will takes along time to do, you have to handle in other thread. That's reason why we should use Thread or AsyncTask.
What's AsyncTask?
You can read more by search on Google. I just tell you: How to use AsyncTask to solve your spec.
What does AsyncTask do?
When you create an instance of AsyncTask,
It's will follow:
-> Create -> PreExecute -> Execute (DoInBackground) - PostExecute
Ok.
Right now, I will answer your question:
Create an object which extends AsyncTask.
public class DownloadFile extends AsyncTask<String, Void, InputStream> {
#Override
public void onPreExecute() {
// You can implement this method if you want to prepare something before start execute (Send request to server)
// Example, you can show Dialog, or something,...
}
#Override
public InputStream doInBackground(String... strings) {
// This is the important method in AsyncTask. You have to implements this method.
// Demo: Using HttpClient
InputStream mInputStream = null;
try {
String uri = strings[0];
HttpClient mClient = new DefaultHttpClient();
HttpGet mGet = new HttpGet(uri);
HttpResponse mResponse = mClient.execute(mGet);
// There are 2 methods: getStatusCode & getContent.
// I dont' remember exactly what are they. You can find in HttpResponse document.
mInputStream = mReponse.getEntity().getContent();
} catch (Exception e) {
Log.e("TAG", "error: " + e.getMessage());
}
return mInputStream;
}
#Override
public void onPostExecute(InputStream result) {
//After doInBackground, this method will be invoked if you implemented.
// You can do anything with the result which you get from Result.
}
}
Ok. Now we have to use this class
In your MainActivity or where you want to invoke this class, create an instance of this class
DownloadFile mDownloader = new DownloadFile();
mDownloader.execute("your_url");
Using method mDownloader.get(); to get InputStream if you want to get. But you have to surround by try-catch
I know, if you want to use Dialog, you will search on Google how to show Dialog while download file from server.
And I suggest you that you should remember, you nead runOnUiThread if you want to Update UI.
Because an AsyncTask is Thread. So you can not Update UI if you are in another Thread which is not MainThread.
AsyncTask
AsyncTask enables proper and easy use of the UI thread. It is used when you want to perform long awaited task in background.
It publish result on the UI thread(display result to the UI) without having to manipulate any threads or handlers.It means that user doesn’t bother about Thread management, everything is managed by itself. And thats why it is known as Painless Threading, see below point.
It is also known as Painless Threading.
The result of AsyncTask operation is published on UI thread. It has basically 4 methods to override: onPreExecute, doInBackground, onProgressUpdate and onPostExecute
Never expect to be a programmer by referring short notes, study deep..
Look here for more detail.

How to kill a AsyncTack thread properly in Android?

I subclass an AsyncTask in my Android project.
I want to implement a feature that allow user to cancel the current AsyncTack and start a new one if the current task take too much time.
MyAsyncTask mat = new MyAsyncTask();
When the user click the cancel button, I will implement the following code and then start a new task.
mat.cancel(true);
However, I realize later that the new task doesn't start until the old task is finish. The old task tread is still executing.
I check the official document on google. It seems that I should call the following statement in doInBackGroud(Params... params).
if (isCancelled()) break;
The problem is I found that the code below is responsible for taking long time.
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
But how can I check whether the task is cancelled or not while httpClient.execute(httpPost) is executing?
Is there some method like onProgressChanged(int progress) that I can override in DefaultHttpClient?
I want to implement a feature that allow user to cancel the current
AsyncTack and start a new one if the current task take too much time.
Since you cannot start a new task until the old task is finish, you can create a new instance of the Asyntask. In fact, its a bad idea to use a instance of AsyncTask multiple times.
After your
HttpResponse httpResponse = httpClient.execute(httpPost);
You can check if it was canceled
if(!isCanceled()){
}
Look in the docs, last line under Threading Rules.
Update
as comment pointed out. Depends on your platform , so check the platform version before execute.
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB) {
myTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
else {
myTask.execute();
}
You need to abort your request by calling abort on your httpPost object. This will cause the execute method to return immediately and to stop blocking your thread.
I would actually avoid using AsyncTask altogether. AsyncTasks are prone to memory leaks and are poorly tied to the Activity lifecycle so you'll end up getting yourself into trouble.
Consider using RoboSpice as not only it will help you solve your question, but it'll avoid the problems with AsyncTasks and skip having to write stuff manually with HttpClient. I am not one of the devs for RoboSpice, but I've started using it recently and it's an excellent project.

Categories

Resources