Publish progress from an external class during Async Task? - android

I have an async task with a doInBackground() method like this:
protected String doInBackground(String... params) {
MyClass session = new MyClass("email", "password");
return session.isAuthorized();
}
While MyClass, which is in a completly different package, is something like this:
private class MyClass {
// fields, constructors, etc
public Boolean isAuthorized() {
// some stuff
log("Action 1...");
// some stuff
log("Action 2...");
// some other stuff
return result;
}
public static void log(String str) {
// HERE I would like to publish progress in the Async Task
// but, until now, it's kinda like:
System.out.println(str);
}
}
The question is: how can I pass log descriptions hold in the log() method, external even to the main Activity "container", to publishProgress() method? I already read this thread: Difficulty in changing the message of progress dialog in async task - but it wasn't a valid source of help, since my method isn't contained in the main class public class MainActivity extends Activity {}.
EDIT #1 -
After some work, I realized that the only way is passing to the external class a referece to the "main" thread, and then implement there a specific method to publish progress. In such a way:
public void log(String str) {
if (mThreadReference==null) {
System.out.println(str);
} else {
mThreadReference.doProgress();
}
}
While mThreadReference points to this AsyncTask:
private class MyClassTask extends AsyncTask<String,String,String> {
#Override
protected String doInBackground(String... params) {
// constructs MyClass instance with a reference and run main method
(new MyClass("email", "password", this)).isAuthorized();
}
public void doProgress(String str) {
publishProgress(str);
}
#Override
protected void onProgressUpdate(String... values) {
// some stuff
}
#Override
protected void onPostExecute(String result) {
}
}
But, obviously, Eclipse is warning me: The method publishProgress() is undefined for the type Activity. How can I write a general and absolute method, in the external class, which I can use in more than one specific AsyncThread?
--> LOGs IN THE LOGIN THREAD 1
/
EXTERNAL CLASS ---> LOGs IN THE LOGIN THREAD 2
\
--> LOGs IN THE LOGIN THREAD 3

I figured out that the only way is importing the istance of the AsyncTask, which has to be public (not the default option!), in the main activity. With this trick, I can invoke the publishProgress method even if it's protected.
// MyClass, in a different package
import MainActivity.MyClassTask mThreadReference = null;
// some stuff...
public void log(String str) {
if (mThreadReference==null) {
System.out.println(str);
} else {
mThreadReference.doProgress("");
}
}
While this is the activity:
public class LoginLanding extends Activity {
// stuff...
public class MyClassTask extends AsyncTask<String,String,String> {
// bla bla bla, some stuff...
public void doProgress(String str) {
// do something
}
}
}

Today I faced similar problem. Previous answer helped be solve problem 50%. It was null pointer exception as mThreadReference is null.
Now you need an instance of the enclosing class in order to instantiate the inner class which is AsyncTask class. Since I had such class defined inside my fragment, what I did was below:
MyFragment fm = new MyFragment();
MyFragment.AsyncTaskClassName aTCN = fm.new AsyncTaskClassName();
After that you can call doProgress method the way Gianlunca has suggested.
My 2 cents !!

Related

android asynctask sending callbacks to ui [duplicate]

This question already has answers here:
How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?
(17 answers)
Closed 6 years ago.
I have the following asynctask class which is not inside the activity. In the activity I'm initializing the asynctask, and I want the asynctask to report callbacks back to my activity.
Is it possible? Or does the asynctask must be in the same class file as the activity?
protected void onProgressUpdate(Integer... values)
{
super.onProgressUpdate(values);
caller.sometextfield.setText("bla");
}
Something like this?
You can create an interface, pass it to AsyncTask (in constructor), and then call method in onPostExecute()
For example:
Your interface:
public interface OnTaskCompleted{
void onTaskCompleted();
}
Your Activity:
public class YourActivity implements OnTaskCompleted{
// your Activity
}
And your AsyncTask:
public class YourTask extends AsyncTask<Object,Object,Object>{ //change Object to required type
private OnTaskCompleted listener;
public YourTask(OnTaskCompleted listener){
this.listener=listener;
}
// required methods
protected void onPostExecute(Object o){
// your stuff
listener.onTaskCompleted();
}
}
EDIT
Since this answer got quite popular, I want to add some things.
If you're a new to Android development, AsyncTask is a fast way to make things work without blocking UI thread. It does solves some problems indeed, there is nothing wrong with how the class works itself. However, it brings some implications, such as:
Possibility of memory leaks. If you keep reference to your Activity, it will stay in memory even after user left the screen (or rotated the device).
AsyncTask is not delivering result to Activity if Activity was already destroyed. You have to add extra code to manage all this stuff or do you operations twice.
Convoluted code which does everything in Activity
When you feel that you matured enough to move on with Android, take a look at this article which, I think, is a better way to go for developing your Android apps with asynchronous operations.
I felt the below approach is very easy.
I have declared an interface for callback
public interface AsyncResponse {
void processFinish(Object output);
}
Then created asynchronous Task for responding all type of parallel requests
public class MyAsyncTask extends AsyncTask<Object, Object, Object> {
public AsyncResponse delegate = null;//Call back interface
public MyAsyncTask(AsyncResponse asyncResponse) {
delegate = asyncResponse;//Assigning call back interfacethrough constructor
}
#Override
protected Object doInBackground(Object... params) {
//My Background tasks are written here
return {resutl Object}
}
#Override
protected void onPostExecute(Object result) {
delegate.processFinish(result);
}
}
Then Called the asynchronous task when clicking a button in activity Class.
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
Button mbtnPress = (Button) findViewById(R.id.btnPress);
mbtnPress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MyAsyncTask asyncTask =new MyAsyncTask(new AsyncResponse() {
#Override
public void processFinish(Object output) {
Log.d("Response From Asynchronous task:", (String) output);
mbtnPress.setText((String) output);
}
});
asyncTask.execute(new Object[] { "Youe request to aynchronous task class is giving here.." });
}
});
}
}
Thanks
IN completion to above answers, you can also customize your fallbacks for each async call you do, so that each call to the generic ASYNC method will populate different data, depending on the onTaskDone stuff you put there.
Main.FragmentCallback FC= new Main.FragmentCallback(){
#Override
public void onTaskDone(String results) {
localText.setText(results); //example TextView
}
};
new API_CALL(this.getApplicationContext(), "GET",FC).execute("&Books=" + Main.Books + "&args=" + profile_id);
Remind: I used interface on the main activity thats where "Main" comes, like this:
public interface FragmentCallback {
public void onTaskDone(String results);
}
My API post execute looks like this:
#Override
protected void onPostExecute(String results) {
Log.i("TASK Result", results);
mFragmentCallback.onTaskDone(results);
}
The API constructor looks like this:
class API_CALL extends AsyncTask<String,Void,String> {
private Main.FragmentCallback mFragmentCallback;
private Context act;
private String method;
public API_CALL(Context ctx, String api_method,Main.FragmentCallback fragmentCallback) {
act=ctx;
method=api_method;
mFragmentCallback = fragmentCallback;
}
I will repeat what the others said, but will just try to make it simpler...
First, just create the Interface class
public interface PostTaskListener<K> {
// K is the type of the result object of the async task
void onPostTask(K result);
}
Second, create the AsyncTask (which can be an inner static class of your activity or fragment) that uses the Interface, by including a concrete class. In the example, the PostTaskListener is parameterized with String, which means it expects a String class as a result of the async task.
public static class LoadData extends AsyncTask<Void, Void, String> {
private PostTaskListener<String> postTaskListener;
protected LoadData(PostTaskListener<String> postTaskListener){
this.postTaskListener = postTaskListener;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result != null && postTaskListener != null)
postTaskListener.onPostTask(result);
}
}
Finally, the part where your combine your logic. In your activity / fragment, create the PostTaskListener and pass it to the async task. Here is an example:
...
PostTaskListener<String> postTaskListener = new PostTaskListener<String>() {
#Override
public void onPostTask(String result) {
//Your post execution task code
}
}
// Create the async task and pass it the post task listener.
new LoadData(postTaskListener);
Done!

how to pass the result of asynctask onpostexecute method into the parent activity android

I am developing an application in which i need to send the value of the asynctask's onPostExecute method's result in to the previous activity , ie the activity in which the aync task is being called.pls put some codes. Anyhelp is appreciated
Two ways:
Declare class extending AsyncTask as private class in parent Activity
Pass Handler or Activity itself as param of class extending AsyncTask
If I were you, I'd follow the first option.
Look at DOCS:
class MyActivitySubclass extends Activity {
function runOnPostExecute(){
// whatever
}
private class MyTask extends AsyncTask<Void, Void, Void> {
void doInBackground(Void... params){
// do your background stuff
}
void onPostExecute(Void... result){
runOnPostExecute();
}
}
}
Note 1
Code placed in body of function onPostExecute is already run on Activity thread, you should just mention that this keywords leads to MyTask.this and not MyActivitySubclass.this
Well if your AsyncTask is an inner class, you could simply call a method in your activity from onPostExecute():
public class MyActivity extends Activity {
public void someMethod(String someParam) {
// do something with string here
}
public class InnerTask extends AsyncTask<...> {
protected void onPostExecute(result) {
someMethod(Send parameters);
}
}
}
The onPostExecute method is fired on the main UI thread, so anything done there is already on the AsyncTasks caller.
http://developer.android.com/reference/android/os/AsyncTask.html
Fire an event in the OnPostExecute.
Its an add on to the answer by Marek Sebera, he pointed to use a handler. To keep the code simple and intuitive use an interface. This isn't alien concept, we use it all the time for callback functions (eg: OnClickListner etc..). The code would look some thing like this.
public class InnerTask extends AsyncTask<...>
{
interface ResultHandler
{
void gotResult(<> result);
}
private ResultHandler myResult;
//constructor
public InnerTask(....params...,ResultHandler callback)
{
...
this.myResult = callback;
}
protected void onPostExecute(<>result)
{
...
myResult.gotResult(result);
}
}
public class MyActivity extends Activity implements InnerTask.ResultHandler
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
//do something
//if you want the InnerTask to execute here
InnerTask i = new InnerTask(....params...,this); //send 'this' as parameter
i.execute();
}
#Override
public void gotResult(<> result)
{
//from onPostExecute
}
}
If we want to use the same AsynTask class at multiple sites we can use this type of implementation instead of using nested classes implementation.

Is passing interface to AsyncTask a good practice

I have an interface class
public interface AsyncTaskExecuteCommand {
public Object executeCommand(String jsonLocation) throws IOException,JSONException;
}
And I have a HashMap which store instances of this interface
public static HashMap<String,AsyncTaskExecuteCommand> executeCommandHashMap
executeCommandHashMap.put(COMMAND_CORE_FIELD_FETCH, new AsyncTaskExecuteCommand() {
#Override
public Object executeCommand(String jsonLocation) throws IOException, JSONException{
//return some thing
}
});
executeCommandHashMap.put(COMMAND_REGISTER_FIELD_FETCH, new AsyncTaskExecuteCommand() {
#Override
public Object executeCommand(String jsonLocation) throws IOException,
JSONException {
//return some thing
}
});
And my AsyncTask named GeneralAsyncTask includes
doInBackground(){
AsyncTaskExecuteCommand asyncTaskExecuteCommand = executeCommandHashMap.get(params[0]);
return asyncTaskExecuteCommand.executeCommand(params[1]);
}
And this AsyncTask is called
new GeneralAsyncTask().execute(COMMAND_REGISTER_FIELD_FETCH,"http://something");
I have done this because the general structure of my AsyncTask remains the same i.e.,it does some method execution and return some value.Only method execution type and return value will be different.If I won't implement passing interface to async task,I end up creating lots of AsyncTask classes.
So,is this method a good to way to tackle my scenario?
Seems like a lot of complexity. Is there a reason you just don't use an anonymous class:
new AsyncTask<String, Void, Object>() {
#Override
protected Object doInBackground(String... url) {
//return some thing
}
protected void onPostExecute(Object result) {
// do something with result
}
}.execute("http://something");
The interface makes sense if you are going to code the implementations and have them as separate classes in some package. This improves readability. If the purpose is not writing the AsynkTask each time, because it has some common parts but only the doInBackground changes, then I'd extend the AsyncTask to a concrete generic class accepting a GENERIC interface like this one:
public interface MyTask<T,R> {
R doInBackground(T... param);
}
The class would be something like this (not tested):
public class MyAsyncTask<T, P, R> extends AsyncTask<T, P, R> {
private MyTask<T,R> task;
public MyAsyncTask(MyTask<T,R> todo){
task = todo;
}
protected R doInBackground(T... params) {
if(task != null){
return task.doInBackground(params);
} else {
return null;
}
}
//Other AsyncTask mandatory methods implemented here.
}
Or if you are fine without generics, then do the interface and the AsyncTask subclass non generic. Either way, I'd code the task(s) class(es) and command implementations, put them on a package, make them singletons (or have public references in some main class) and get rid of the map.

How to refresh asyncTask from another acctivity?

I am launching a activity, and once a user is logged in, i want to refresh the main activity. To load the data from the logged in user.
Such as the image and name. I have all of this set up already.
I just need to know is it possible to launch another activity and run its async task again.From an launching an intent from inside another activity?
It's not clear what exactly your design is, but if you need to use the same AsyncTask from two different activities, it should be a separate class, not tied to a particular activity. You can have the two activities implement a common interface, so that the AsyncTask doesn't need to know which activity it is updating. Then instantiate the task by passing a reference to the enclosing activity, and start it as needed. There is no need for one activity to start the other.
Something like:
public interface UserActivity {
void updateUserData(UserData userData);
}
public class Activity1 implements UserActivity {
public void onStart() {
UpdateUserDataTask task = new UpdateUserDataTask(this);
task.execute();
}
public void updateUserData(UserData userData) {
// update
}
}
public class UpdateUserDataTask extends AsyncTask<Void, Void, UserData> {
UserActivity userActivity;
public UpdateUserDataTask(UserActivitiy userActivity) {
this.userActivity = userActivity;
}
// doInBackground, etc implementation.
protected void onPostExecute(UserData userData) {
userActivity.updateUserData(userData);
}
}
As far as I'm aware, AsyncTasks aren't supposed to be reused. They're supposed to be run once and then you can create a new one if you need it.
Once an AsyncTask is executed once, you cannot execute it again. What you can do, though, is control it's "refresh" using onProgressUpdate() and publishProgress() as follows. Note that this will only work for a one-time refresh. If you wanted to be more semantically correct, you might do the "normal" operation in onProgressUpdate() and use onPostExecute() for your resfresh.
public class MyAsyncTask extends AsyncTask<Void, String, Void> {
private boolean isRefresh = false;
#Override
protected Void doInBackground(Void... arg0) {
while (!isRefresh){
//Perform your normal operation
}
//When isRefresh is true, you want to refresh.
this.publishProgress(values);
return null;
}
#Override
protected void onProgressUpdate(String... values) {
// Refresh code here
super.onProgressUpdate(values);
}
public void refreshTask(){
this.isRefresh = true;
}
}
You could then maintain a reference to the object of MyAsyncTask and invoke refreshTask() on it whenever you want to refresh it.

Android async task - which activity evoked it?

I am facing problem of having one async task, but I need it use twice, because each time I change different part of GUI (updating progress bar).
Is there any way how to determine in if - else clause, which activity does it call and then make appropriate function for each of both of them?
Edit: huh, answer was here and now there isn't...
Thanks
You can hold a member variable which contains the activity/context it is started from.
//pseudocode
AsyncTask task = new AsyncTask();
task.mActivity = this;
task.execute();
Inside doInBackground just check the activity:
//pseudocode
if (mActivity instanceof MyActivity) {
// ....
} else {
// ....
}
Extract the code from the AsyncTask implementation and delegate that to the Activity. Example:
public interface MyDelegate {
public void updateProgress(....)
}
Your AsyncTask takes a delegate and calls it when appropiate:
public class MyAsyncTask .... {
public MyAsyncTask(MyDelegate myDelegate) { ... }
// somewhere in your code (probably onProgressUpdate)
myDelegate.updateProgress(...)
}
Your Activity/ies implement/s the delegate:
public class MyActivity extends Activity implements MyDelegate {
public void updateProgress(...) {
// update ui
}
// somewhere in your code:
new MyAsyncTask(this).execute(...);
}

Categories

Resources