Android - do something in MainActivity after AsyncTask is done - android

I've got an AsyncTask class that will do a HttpGet-request. I want to do something after this AsyncTask is done, but from within my MainActivity.
Here is my TaskGetAPI class:
public class TaskGetAPI extends AsyncTask<String, Void, String>
{
private TextView output;
private Controller controller;
public TaskGetAPI(TextView output){
this.output = output;
}
#Override
protected String doInBackground(String... urls){
String response = "";
for(String url : urls){
HttpGet get = new HttpGet(url);
try{
// Send the GET-request
HttpResponse execute = MainActivity.HttpClient.execute(get);
// Get the response of the GET-request
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while((s = buffer.readLine()) != null)
response += s;
content.close();
buffer.close();
}
catch(Exception ex){
ex.printStackTrace();
}
}
return response;
}
#Override
protected void onPostExecute(String result){
if(!Config.LOCALHOST)
output.setText(result);
else
controller = Controller.fromJson(result);
}
public Controller getController(){
return controller;
}
And here is the method from my MainActivity where I use this class:
private void sendGetRequest(){
...
// Web API GET-request
if(!get_url.equals("") && get_url != null){
TaskGetAPI task = new TaskGetAPI(output);
task.execute(new String[] { get_url });
// TODO: When AsyncTask is done, do:
controller = task.getController();
Log.i("CONTROLLER", controller.toString());
}
}
As you can see I set the Controller that I use later on in the onPostExecute-method of the AsyncTask.
Since this counters the entire purpose of Async tasks I first thought of removing the extends AsyncTask and just make a regular class & method of my HttpGet, but then I get a android.os.NetworkOnMainThreadException, meaning I need to use an AsyncTask (or something similar) to use HttpGet from within a different thread than my MainThread.
So, does anyone know what I should put at the // TODO?
I did try adding a boolean field (isDone) to the TaskGetAPI class with a getter and then use:
while(true){
if(task.isDone()){
Controller controller = task.getController();
Log.i("CONTROLLER", controller.toString());
}
}
But then the following steps occur:
doInBackground of the TaskGetAPI class is completely done.
Now we are stuck in this while(true)-loop..
and onPostExecute which sets the isDone to true is never called.

When the task will get finish then it will call onPostExecute, So you can use LocalBroadcast to send the broadcast message to main activity. You can use sendBroadcast which uses asynchronous manner i.e. send broadcast to all listener at a time rather than sendOrderedBroadcast.

Assuming that you only use TaskGetAPI inside your Activity, you can just define TaskGetAPI as an inner class, like the example in https://developer.android.com/guide/components/processes-and-threads.html#AsyncTask
public class MainActivity extends Activity {
public class TaskGetAPI extends AsyncTask<String, Void, String> {
/*
* This object is instanced inside the MainActivity instance,
* so it has access to MainActivity methods and members
* (including private ones).
* Remember to only access to UI elements like views from the main thread,
* that is, only from onPreExecute, onProgress or onPostExecute
* In this class "this" makes reference to the TaskGetAPI instance,
* if you need a refeence to the MainActivity instance, use MainActivity.this
*
*/
protected String doInBackground(String... urls){ ... }
protected void onPostExecute(String result){
mMyTextView.setText(result);
}
}
private TextView mMyTextView;
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.main);
mMyTextView = (TextView) findViewById(R.id.view);
new TaskGetAPI().exec();
}
}
If you need to use TaskGetAPI you can define it outside MainActivity and define a subclass as inner class of MainActivity.
There are other options, though, like defining listeners (like the onClickListeners) and call them in onPostExecute, but that is unnecesarily complex.

You can send a broadcast with your result from onPostExecute with the response. The activity will listen to it and execute the code you want.
while(true) is never a good idea, especially on mobiles where battery life is important.

Related

Handling data passed to a result argument of AsyncTask.onPostExecute()

I have this private class that is within my main activity, and I am using it pull a JSon object off of my server into my app. The code below works fine and will display the JSon object as a string.
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
return httpBuild(urls[0]);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Received!", Toast.LENGTH_LONG).show();
etResponse.setText(result);
}
}
what I am trying to do is place change the onPostExecute() method so it acts like webResult = result where webResult is an instance variable of the class mainActivity The problem is once I do this when I try to put the below code into the onCreate() method after HTTpAsyncTask has been called the app fails to display the object and crashes.
public class MainActivity extends Activity {
private static final String mainSite = "http://mysitehere";
private String webResult;
// private JSONArray floorsInBuilding, roomsInGender;
// private JSONObject room;
// private JSONArray arrayOfFloors;
// private JSONObject room, arrayOfRooms;
EditText etResponse;
TextView tvIsConnected;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get reference to the views
etResponse = (EditText) findViewById(R.id.etResponse);
tvIsConnected = (TextView) findViewById(R.id.tvIsConnected);
// check if you are connected or not
if(isConnected()){
tvIsConnected.setBackgroundColor(0xFF00CC00);
tvIsConnected.setText("You are conncted");
}
else{
tvIsConnected.setText("You are NOT conncted");
}
// call AsynTask to perform network operation on separate thread
new HttpAsyncTask().execute(this.buildBuildingAddress(8));
Toast.makeText(getBaseContext(), "Received!", Toast.LENGTH_LONG).show();
etResponse.setText(WebResult);
}
I'm wondering what makes the part of the code that displays the result dependent on the HttpAsyncTask. I'm also wondering how I can get the result of the HttpAsyncTask and store it as a string in the main class.
A good chunk of my code is based of of this example.
http://hmkcode.com/android-parsing-json-data/
I'm sorry If my knowledge of android isn't so great but my experience lies in more in java.
If you want to wait till the task is over so that you can override the result with webResult then you may use the asyncTask method onProgressUpdate which runs on UI thread. You may refer android developer site to know how to use that method.
The answer to this is that the asynchronous task runs alongside onCreate(). So you have to create some piece of code that waits for the task to complete or you have to manipulate the result of the async task in the onPostExecute() method

Activity -> AsyncTask -> BroadcastReceiver -> Update UI

I am starting an AsyncTask from an Activity. When, the AsyncTask completes its execution I need to send a broadcast which needs to call Activity method to update the UI.
Any good approach to achieve this.
Yes.
If the AsyncTask is an inner class of your Activity then it has access to any member variables and your Activity methods. If it isn't then you can simply pass variables to its constructor or even a reference to the Activity to call Activity methods from onPostExecute(). Without any code its hard to say much else.
To pass an instance of your Activity and use its methods if its a separate class then you can create a constructor and do something like
public class MyTask extends AsyncTask<...> // add your params
{
private MyActivity activty;
public MyTask (MyActivity act)
{
this.activty = activty;
}
// ...
}
and in onPostExecute() add something like
activity.myMethod();
and call the task like
MyTask task = new MyTask(this); // pass a reference of the activity
task.execute(); // add params if needed
If the AsyncTask is a separate file from the Activity then you can see this answer on how to use an interface for a callback
Please use Interface.
interface INotifyChange {
void notifyChange(); // You can use params to transfer data :D
}
In Activity you should implements this interface.
YourActivity extends Activity implements INotifyChange {
#Override
public void notifyChange() {
// Right here, you can Update UI.
}
}
When you create new instance of AsyncTask
Example:
YourAsyncTask mTask = new YourAsyncTask(this); // You put INotifyChange
In YourAsyncTask
private INotifyChange iNotifyChange;
public YourAsyncTask(INotifyChange iNotifyChange) {
this.iNotifyChange = iNotifyChange;
}
// When you complete doInBackground or anywhere you want to Update UI please use iNotifyChange.notifyChange()
Example:
#Override
public void onPostExecute(ResultType mResult) {
iNotifyChange.notifyChange();
}
By this way I often use to update progress bar. In this case, I use parameter in my method:
Example:
iNotifyChange.notify(progress);
Have you considered overwriting the onPostExecute() method of the AsyncTask to update the UI? Try something like this:
AsyncTask<String, Void, Bitmap> task = new AsyncTask<String, Void, Bitmap>(imageView)
{
private ImageView imageView;
public AsyncTask(ImageView imageView)
{
this.imageView = imageView;
}
#Override
protected Bitmap doInBackground (String... params)
{
if(params.length > 0)
{
String filePath = params[0];
// Load Bitmap from file
return bitmap;
}
}
#Override
protected void onPostExecute(Bitmap result)
{
imageView.setImageBitmap(result);
}
}
task.execute(filePath);

How to pass variables in and out of AsyncTasks?

I haven't spent much time working with AsyncTasks in Android. I'm trying to understand how to pass variables to and from the class. The syntax:
class MyTask extends AsyncTask<String, Void, Bitmap>{
// Your Async code will be here
}
it's a little bit confusing with the < > syntax on the end of the class definition. Never seen that type of syntax before. It seems like I'm limited to only passing one value into the AsyncTask. Am I incorrect in assuming this? If I have more to pass, how do I do that?
Also, how do I return values from the AsyncTask?
It's a class and when you want to use it you call new MyTask().execute() but the actual method you use in the class is doInBackground(). So where do you actually return something?
Note: all of the information below is available on the Android Developers AsyncTask reference page. The Usage header has an example. Also take a look at the Painless Threading Android Developers Blog Entry.
Take a look at the source code for AsynTask.
The funny < > notation lets you customize your Async task. The brackets are used to help implement generics in Java.
There are 3 important parts of a task you can customize:
The type of the parameters passed in - any number you want
The type for what you use to update the progress bar / indicator
The type for what you return once done with the background task
And remember, that any of the above may be interfaces. This is how you can pass in multiple types on the same call!
You place the types of these 3 things in the angle brackets:
<Params, Progress, Result>
So if you are going to pass in URLs and use Integers to update progress and return a Boolean indicating success you would write:
public MyClass extends AsyncTask<URL, Integer, Boolean> {
In this case, if you are downloading Bitmaps for example, you would be handling what you do with the Bitmaps in the background. You could also just return a HashMap of Bitmaps if you wanted. Also remember the member variables you use are not restricted, so don't feel too tied down by params, progress, and result.
To launch an AsyncTask instantiate it, and then execute it either sequentially or in parallel. In the execution is where you pass in your variables. You can pass in more than one.
Note that you do not call doInBackground() directly. This is because doing so would break the magic of the AsyncTask, which is that doInBackground() is done in a background thread. Calling it directly as is, would make it run in the UI thread. So, instead you should use a form of execute(). The job of execute() is to kick off the doInBackground() in a background thread and not the UI thread.
Working with our example from above.
...
myBgTask = new MyClass();
myBgTask.execute(url1, url2, url3, url4);
...
onPostExecute will fire when all the tasks from execute are done.
myBgTask1 = new MyClass().execute(url1, url2);
myBgTask2 = new MyClass().execute(urlThis, urlThat);
Notice how you can pass multiple parameters to execute() which passes the multiple parameter on to doInBackground(). This is through the use of varargs (you know like String.format(...). Many examples only show the extraction of the first params by using params[0], but you should make sure you get all the params. If you are passing in URLs this would be (taken from the AsynTask example, there are multiple ways to do this):
// This method is not called directly.
// It is fired through the use of execute()
// It returns the third type in the brackets <...>
// and it is passed the first type in the brackets <...>
// and it can use the second type in the brackets <...> to track progress
protected Long doInBackground(URL... urls)
{
int count = urls.length;
long totalSize = 0;
// This will download stuff from each URL passed in
for (int i = 0; i < count; i++)
{
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
}
// This will return once when all the URLs for this AsyncTask instance
// have been downloaded
return totalSize;
}
If you are going to be doing multiple bg tasks, then you want to consider that the above myBgTask1 and myBgTask2 calls will be made in sequence. This is great if one call depends on the other, but if the calls are independent - for example you are downloading multiple images, and you don't care which ones arrive first - then you can make the myBgTask1 and myBgTask2 calls in parallel with the THREAD_POOL_EXECUTOR:
myBgTask1 = new MyClass().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, url1, url2);
myBgTask2 = new MyClass().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, urlThis, urlThat);
Note:
Example
Here is an example AsyncTask that can take as many types as you want on the same execute() command. The restriction is that each type must implement the same interface:
public class BackgroundTask extends AsyncTask<BackgroundTodo, Void, Void>
{
public static interface BackgroundTodo
{
public void run();
}
#Override
protected Void doInBackground(BackgroundTodo... todos)
{
for (BackgroundTodo backgroundTodo : todos)
{
backgroundTodo.run();
// This logging is just for fun, to see that they really are different types
Log.d("BG_TASKS", "Bg task done on type: " + backgroundTodo.getClass().toString());
}
return null;
}
}
Now you can do:
new BackgroundTask().execute(this1, that1, other1);
Where each of those objects is a different type! (which implements the same interface)
I recognize that this is a late answer, but here's what I've been doing for the last while.
When I'm needing to pass in a bunch of data to an AsyncTask, I can either create my own class, pass that in and then access it's properties, like this:
public class MyAsyncTask extends AsyncTask<MyClass, Void, Boolean> {
#Override
protected Boolean doInBackground(MyClass... params) {
// Do blah blah with param1 and param2
MyClass myClass = params[0];
String param1 = myClass.getParam1();
String param2 = myClass.getParam2();
return null;
}
}
and then access it like this:
AsyncTask asyncTask = new MyAsyncTask().execute(new MyClass());
or I can add a constructor to my AsyncTask class, like this:
public class MyAsyncTask extends AsyncTask<Void, Void, Boolean> {
private String param1;
private String param2;
public MyAsyncTask(String param1, String param2) {
this.param1 = param1;
this.param2 = param2;
}
#Override
protected Boolean doInBackground(Void... params) {
// Do blah blah with param1 and param2
return null;
}
}
and then access it like this:
AsyncTask asyncTask = new MyAsyncTask("String1", "String2").execute();
Hope this helps!
Since you can pass array of objects in the square bracket, that is the best way to pass data based on which you want to do processing in the background.
You could pass the reference of your activity or the view in the Constructor and use that to pass data back into your activity
class DownloadFilesTask extends AsyncTask<URL, Integer, List> {
private static final String TAG = null;
private MainActivity mActivity;
public DownloadFilesTask(MainActivity activity) {
mActivity = activity;
mActivity.setProgressBarIndeterminateVisibility(true);
}
protected List doInBackground(URL... url) {
List output = Downloader.downloadFile(url[0]);
return output;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
private void setProgressPercent(final Integer integer) {
mActivity.setProgress(100*integer);
}
protected void onPostExecute(List output) {
mActivity.mDetailsFragment.setDataList((ArrayList<Item>) output);
//you could do other processing here
}
}
Alternatively, you could just use a regular thread and usea handler to send data back to the ui thread by overriding the handlemessage function.
Passing a simple String:
public static void someMethod{
String [] variableString= {"hello"};
new MyTask().execute(variableString);
}
static class MyTask extends AsyncTask<String, Integer, String> {
// This is run in a background thread
#Override
protected String doInBackground(String... params) {
// get the string from params, which is an array
final String variableString = params[0];
Log.e("BACKGROUND", "authtoken: " + variableString);
return null;
}
}

Android - Call method from an Activity from a Thread

I have the following snippet:
public class SocketActivity extends Activity {
.
.
.
EditText textView;
Socket socket = new Socket(name,ip);
out = new PrintWriter(socket.getOutputStream());
out.flush();
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
.
.
.
}
Now, I have other lines to allow this activity to converse with a java server. But what I would like to do, is create a thread that constantly listens for a message from the server. Currently, it only listens for a response after I send a message. How would I set the textView from the thread? Is this the best way to do this? If not, where else should I do this?
======================
So, here is a more complete description of what I want to do, the textView is too primitive for what I want. So I have a MainActivity that creates a superclassed SurfaceView which has a superclassed Renderer that contains a Cube object with buffers, so it can be drawn. I also have a SocketActivity to connect to a server
What I want to do is wait for the server to send a packet of points to the client. Then, as each point is received it is put into the buffer. Then, once it completes, it waits again for the next packet. How should I use Asynctask be used to put a point to a buffer everytime I receive one. So to get a map of what's going on:
public class MainActivity extends Activity {
OpenGLSurfaceView view;
.
.
.
}
public class OpenGLSurfaceView extends SurfaceView {
OpenGLRenderer renderer;
.
.
.
}
public class OpenGLRenderer extends Renderer {
Cube cube;
.
.
.
}
public class Cube{
private FloatBuffer vertexBuffer;
.
.
.
}
public class SocketActivity extends Activity {
Socket socket;
BufferedReader in;
PrintWriter out;
.
.
.
}
Now where should the Asynctask be instantiated? Should I structure my program this way, or is there a better way? (For those that do not know, to put a primitive into a buffer you use buffer.put(/*primitive*/), but this is trivial.)
You cannot modify UI (in this case TextView) from non-UI thread. Try using AsyncTask. The UI can be modified ONLY in onPreExecute() and onPostExecute() methods. If you need example of how to use AsyncTask, please ask for.
There is another way to use Runnable with the method runOnUiThread() but, I recommend AsyncTask.
Example:
private class Surgery extends AsyncTask<String, Void, String> {
private String dataSurgery=null;
private File fileSurgery=null;
public Surgery (String data1, File data) //constructor
{
this.dataSurgery = data1; //this is just example here you can put anything you want
this.fileSurgery = data;
}
#Override
protected String doInBackground(String... params) {
//OPERATION WHICH IS UI-INDEPENDENT LET'S SAY SOMETHING LIKE THIS:
Socket socket = new Socket(name,ip);
out = new PrintWriter(socket.getOutputStream());
out.flush();
in = new BufferedReader(new InputStreamReader(socket.getInputStream())); return "here you return data for the textview or anything you need";
}
#Override
protected void onPostExecute(String result) {
// HERE YOU UPDATE YOUR TEXTVIEW i.e HERE YOU UPDATE ANYTHING WHICH IS ON THE UI
}
#Override
protected void onPreExecute() {
// This is OPTIONAL, you might find you dont need to use it.
}
}
}

Android: How can I pass parameters to AsyncTask's onPreExecute()?

I use an AsyncTask for loading operations that I implemented as an inner class.
In onPreExecute() I show a loading dialog which I then hide again in onPostExecute(). But for some of the loading operations I know in advance that they will finish very quickly so I don't want to display the loading dialog.
I wanted to indicate this by a boolean parameter that I could pass to onPreExecute() but apparently for some reason onPreExecute() doesn't take any parameters.
The obvious workaround would probably be to create a member field in my AsyncTask or in the outer class which I would have to set before every loading operation but that does not seem very elegant. Is there a better way to do this?
You can override the constructor. Something like:
private class MyAsyncTask extends AsyncTask<Void, Void, Void> {
public MyAsyncTask(boolean showLoading) {
super();
// do stuff
}
// doInBackground() et al.
}
Then, when calling the task, do something like:
new MyAsyncTask(true).execute(maybe_other_params);
Edit: this is more useful than creating member variables because it simplifies the task invocation. Compare the code above with:
MyAsyncTask task = new MyAsyncTask();
task.showLoading = false;
task.execute();
1) For me that's the most simple way passing parameters to async task
is like this
// To call the async task do it like this
Boolean[] myTaskParams = { true, true, true };
myAsyncTask = new myAsyncTask ().execute(myTaskParams);
Declare and use the async task like here
private class myAsyncTask extends AsyncTask<Boolean, Void, Void> {
#Override
protected Void doInBackground(Boolean...pParams)
{
Boolean param1, param2, param3;
//
param1=pParams[0];
param2=pParams[1];
param3=pParams[2];
....
}
2) Passing methods to async-task
In order to avoid coding the async-Task infrastructure (thread, messagenhandler, ...) multiple times you might consider to pass the methods which should be executed in your async-task as a parameter. Following example outlines this approach.
In addition you might have the need to subclass the async-task to pass initialization parameters in the constructor.
/* Generic Async Task */
interface MyGenericMethod {
int execute(String param);
}
protected class testtask extends AsyncTask<MyGenericMethod, Void, Void>
{
public String mParam; // member variable to parameterize the function
#Override
protected Void doInBackground(MyGenericMethod... params) {
// do something here
params[0].execute("Myparameter");
return null;
}
}
// to start the asynctask do something like that
public void startAsyncTask()
{
//
AsyncTask<MyGenericMethod, Void, Void> mytest = new testtask().execute(new MyGenericMethod() {
public int execute(String param) {
//body
return 1;
}
});
}
why, how and which parameters are passed to Asynctask<>, see detail here. I think it is the best explanation.
Google's Android Documentation Says that :
An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.
AsyncTask's generic types :
The three types used by an asynchronous task are the following:
Params, the type of the parameters sent to the task upon execution.
Progress, the type of the progress units published during the background computation.
Result, the type of the result of the background computation.
Not all types are always used by an asynchronous task. To mark a type as unused, simply use the type Void:
private class MyTask extends AsyncTask<Void, Void, Void> { ... }
You Can further refer : http://developer.android.com/reference/android/os/AsyncTask.html
Or You Can clear whats the role of AsyncTask by refering Sankar-Ganesh's Blog
Well The structure of a typical AsyncTask class goes like :
private class MyTask extends AsyncTask<X, Y, Z>
protected void onPreExecute(){
}
This method is executed before starting the new Thread. There is no input/output values, so just initialize variables or whatever you think you need to do.
protected Z doInBackground(X...x){
}
The most important method in the AsyncTask class. You have to place here all the stuff you want to do in the background, in a different thread from the main one. Here we have as an input value an array of objects from the type “X” (Do you see in the header? We have “...extends AsyncTask” These are the TYPES of the input parameters) and returns an object from the type “Z”.
protected void onProgressUpdate(Y y){
}
This method is called using the method publishProgress(y) and it is usually used when you want to show any progress or information in the main screen, like a progress bar showing the progress of the operation you are doing in the background.
protected void onPostExecute(Z z){
}
This method is called after the operation in the background is done. As an input parameter you will receive the output parameter of the doInBackground method.
What about the X, Y and Z types?
As you can deduce from the above structure:
X – The type of the input variables value you want to set to the background process. This can be an array of objects.
Y – The type of the objects you are going to enter in the onProgressUpdate method.
Z – The type of the result from the operations you have done in the background process.
How do we call this task from an outside class? Just with the following two lines:
MyTask myTask = new MyTask();
myTask.execute(x);
Where x is the input parameter of the type X.
Once we have our task running, we can find out its status from “outside”. Using the “getStatus()” method.
myTask.getStatus();
and we can receive the following status:
RUNNING - Indicates that the task is running.
PENDING - Indicates that the task has not been executed yet.
FINISHED - Indicates that onPostExecute(Z) has finished.
Hints about using AsyncTask
Do not call the methods onPreExecute, doInBackground and onPostExecute manually. This is automatically done by the system.
You cannot call an AsyncTask inside another AsyncTask or Thread. The call of the method execute must be done in the UI Thread.
The method onPostExecute is executed in the UI Thread (here you can call another AsyncTask!).
The input parameters of the task can be an Object array, this way you can put whatever objects and types you want.
You can either pass the parameter in the task constructor or when you call execute:
AsyncTask<Object, Void, MyTaskResult>
The first parameter (Object) is passed in doInBackground.
The third parameter (MyTaskResult) is returned by doInBackground. You can change them to the types you want. The three dots mean that zero or more objects (or an array of them) may be passed as the argument(s).
public class MyActivity extends AppCompatActivity {
TextView textView1;
TextView textView2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
textView1 = (TextView) findViewById(R.id.textView1);
textView2 = (TextView) findViewById(R.id.textView2);
String input1 = "test";
boolean input2 = true;
int input3 = 100;
long input4 = 100000000;
new MyTask(input3, input4).execute(input1, input2);
}
private class MyTaskResult {
String text1;
String text2;
}
private class MyTask extends AsyncTask<Object, Void, MyTaskResult> {
private String val1;
private boolean val2;
private int val3;
private long val4;
public MyTask(int in3, long in4) {
this.val3 = in3;
this.val4 = in4;
// Do something ...
}
protected void onPreExecute() {
// Do something ...
}
#Override
protected MyTaskResult doInBackground(Object... params) {
MyTaskResult res = new MyTaskResult();
val1 = (String) params[0];
val2 = (boolean) params[1];
//Do some lengthy operation
res.text1 = RunProc1(val1);
res.text2 = RunProc2(val2);
return res;
}
#Override
protected void onPostExecute(MyTaskResult res) {
textView1.setText(res.text1);
textView2.setText(res.text2);
}
}
}

Categories

Resources