Prevent activity from loading until task has completed - android

I have 3 activities:
MainActivity
Activity A
Activity B
The user can start a process in Activity B. I show a notification helper % completed, and I go back to MainActivity.
But I don't want to user to be able to do anything with the app until the process had completed, so basically - there is a button on MainActivity that I want to be disabled until the process has completed.
Anyway to check if the notificationbar is still there when they click a button, or anyway to check if the async task is still running?
Thanks

private class DownloadStuff extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... params) {
// DO STUFF in Background
return null;
}
protected Void onPostExecute() {
// Disable Button
}
}
More info: http://developer.android.com/reference/android/os/AsyncTask.html

ok use this in asynctask
on preExecute()
button1.setEnabled(false);
on postExecute()
button1.setEnabled(true);

By Use of Async Task u can solve that

Think to use something like :
MainActivity.java
MainActivity implements LoadingTaskFinishedListener
#Override
public void onTaskFinished() {
myButton.setEnabled(true);
}
..
public class Task extends AsyncTask<String, Integer, Integer> {
Actualite[] pages;
int i=0;
public interface LoadingTaskFinishedListener {
void onTaskFinished();
}

Related

asyncTask from one activity running in another activity android

Im just wondering what would be the best and possibly easiest way to do this. I have two activites LoginAcitivty and Main Activity.
Ive coded an AsyncTask in my MainActivity as an inner class which sends updates to a web service. When i click the logout button of the MainActivity this returns the app to the Login Activity. Is it possible to still run the ASyncTask even though there is a different activity running or is there another way to do something like this?
Any suggestions would be greatly appreciated
Thanks
The Asynctask is tied to the "Entity" that created it, in your case it would be the MainActivity, so it will not survive the destroy of your activity (I trust you call the finis() method of the main activity once the user logs out)
What you can do is use a service that runs in background and use the async task to poll your server:
The service shall look like this:
public class PollService extends Service {
#Override
public void onCreate() {
super.onCreate();
}
public void onStart(Intent intent, int startId) {
(new PollAsyncTask(this)).execute();
}
//callback used to retrieve the result from the asynctask
void callBack(String result) {
//here is your logic, taking the result back from the async task
//eventually re-run the asynctask
(new PollAsyncTask(this)).execute();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
The AsyncTask shall look like this:
private class PollAsyncTask extends AsyncTask<String, Void, String> {
private PollService caller;
PollAsyncTask(PollService caller) {
this.caller = caller;
}
#Override
protected String doInBackground(String... params) {
//do your polling here and return something meaningful to the service,
return SOMETHING_REFERRING_TO_THE_1_OF_3;
}
#Override
protected void onPostExecute(String result) {
//Give the result back to the caller:
this.caller.callBack(result);
}
#Override
protected void onPreExecute() {//nothing special here}
#Override
protected void onProgressUpdate(Void... values) {//nothing special here}
}
That way your async task will poll your server whatever activity is currently in foreground.
The service shall be started by your first activity when it is run the first time (i.e. in the onCreate method):
#Override
public void onCreate(Bundle savedInstanceState) {
if (savedInstanceState==null) {//only the first time
Intent serviceIntent = new Intent();
serviceIntent.setAction("com.yourcompany....PollService");
startService(serviceIntent);
}
}
Hope this helps.
For what I understand, you have an inner Class in your MainActivity.
So just make your AsyncTask in a separate Class and you can call it from both Activites.
Like: new YourAsyncTask().execute();
Greetings.

How run two AsyncTasks in one Activity?

I have two Activitys (mainActivity & downloadActivity) and I have 2 AsyncTasks in downloadActivity
In downloadActivity first it execute getFileAsyncTask for reading a JSON file for adding some images and create a ListView from images, if user clicks on an image, the downloadAsyncTask was called and it starts to download something from the internet.
My problem is here: when the second AsyncTask is running I go back to mainActivity and comeback again to downloadActivity the first AsyncTask wasn't called until the downloadAsyncTask completed.
public class downloadActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
...
new getFileAsyncTask().execute();
...
}
private class getFileAsyncTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
//fetch a json file from internet and add images in ListView
return null;
}
}
//there is a Base Adapter class
//if user clicks on an image it calls this downloadAsyncTask.execute()
private class downloadAsyncTask extends AsyncTask<Void, Integer, Void> {
#Override
protected void onPreExecute() {
//download the file
}
}
#Override
protected Void doInBackground(Void... unused) {
//download the file
}
}
note: I want to write something like shopping apps. For example, user can download file and surf into shop to see products .
If you want to run multiple AsyncTasks in parallel, you can call executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR) instead of execute() on your task. By default, AsyncTasks run in serial, first come first serve.
Be careful that the two threads do not interact on the same data, this can cause some strange and hard to trace errors.
you can make it in one asynk class that have two methodes first fetch json file wait response in doInBackground ... if it is ok call download file methode. Those methodes will return an httpResponse object
You can override onBackPressed function in activity and finish the current activity before go to previous activity. When again you come to downloadActivity it call it's oncreate method and call first AsynctTask.
Make one class task like:
Declare progress bar globally in main thread.
Now what you have to do is start one async task in main thread like:
public class myactivity extends Activity {
private ProgressDialog _dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.base_screen);
new abc().execute();
}
class abc extends AsyncTask(String,String,String) {
#Override
protected void onPreExecute() {
_dialog = new ProgressDialog(_ctx);
_dialog.setCancelable(false);
_dialog.setMessage("Loading");
_dialog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
#Override
protected void onPostExecute(String result) {
// in post execute of this class you can run a new thread of your downaloder thread. and in post execute of last thread you have to dismiss the progess bar.
new download activity.execute();
}
}
}
}
}

How to code more than 2 ...extends AsyncTask .doInBackground() onPostExecute() within an Activity

By the time android apps onStart(),it would execute HttpRequestTask. I have done this part and it works fine.
After the apps open and display data,needs to click on a submit button to POST some data to spring rest web service.In my mind,I think I might need to write another extends AsyncTask ,doInBackground and onPostExecute
What should I code so that system could differentiate extends AsyncTask ,doInBackground and onPostExecute within same Activity?
protected void onStart(){
super.onStart();
new HttpRequestTask().execute();
}
private class HttpRequestTask extends AsyncTask<Void, Void, ArrayList<Item>> {
#Override
protected ArrayList<Item> doInBackground(Void... params) {
//....some code
}
#Override
protected void onPostExecute(ArrayList<PickerItemDetail> pickerList) {
//.....come code and logic
}
}

How to check if an activity is continuing

In my app, I am trying to run multiple photos through a photo editor (one at a time). I have it set up in a for-loop at the moment, but I feel like it is overloading the photo editor and not actually waiting until the current edit session is over, so I wanted to put a control statement in my for-loop to check if the session was still active.
Is this possible?
Easier to tell when the current is over than polling to see if it is still active. If you start it with startActivityForResult, your calling activity will be notified when the invoked activity ends.
Have a look at Starting Activities and Getting Results in the Activity docs for an example.
You might also want to consider running this in an async task. This will pull your heavy processing away from the UI thread. Async task let's you do progress updates as well.
http://developer.android.com/reference/android/os/AsyncTask.html
public class MainActivity extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.logo_page);
// Call async task.
my_async as = new my_async(this);
as.execute();
}
--
my_async:
public class my_async extends AsyncTask<Object, Integer, String> {
private parentClass activity;
public my_async (parentClass activity) {
this.activity = activity;
}
#Override
protected String doInBackground(Object... arg0) {
// Do stuff
return "MyString";
}
protected void onPostExecute(String contents) {
activity.contents = contents;
}

Is it possible to access an object of an activity fom other place?

This maybe a stupid idea, but does anyone know is it possible to access one activity's object form other places?
To be specific, lets say if you have an activity A (with a textView t) and you create a normal java class B.
At onCreate, you start to run B for some calculation like below,
public class MyActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
t = (TextView)findViewById(R.id.outputtext);
Somejava B = new Somejava();
B.run();
}
}
Is there a way for B to update the textView?
I know the simple way (maybe the correct way) is to return the result from B class and use t.setText(result) in MyActivity, but I'm just want to know is it possible to update the textview in B?
Use Intent or public static variables
can simply pass activity refernce to b in constructor and create the method in your acitivty to update textview. if you using another thread not forgot to use handler or other ways to update UI thread.
Yes, it is possible if the Activity's field is public and post the UI changes in a public Handler created on the first Activity but in facts, it's really ugly to do that...
You can use startActivityForResult(...) to notify an other activity how the process has passed with some serialiezable data in the Bundle extras of the Intent and catch the result in the overrided method onActivityResult(...)...
For a "normal java class" B I would work with interfaces
public interface SomejavaListener{
void onSomejavaFinish(Object result);
}
public class MyActivity implements SomejaveFinish extends Activity {
TextView t;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
t = (TextView)findViewById(R.id.outputtext);
Somejava B = new Somejava();
B.run(MyActivity.this); //notice the extra argument!
}
public void onSomejavaFinish(Object result){
t.setText("updated! ^,^");
}
}
public class Somejava {
//...
public void run(SomejavaListener callback){
//working working
callback.onSomejavaFinish( new Object() );
}
}
However in respect to the android environment the question is sitting in I got the feeling maybe an AsyncTask would be the right thing for you. It has an doInBackground method to do work and not spoiling your UI Thread (resulting in ANR Errors.)
Another advantage is the onPreExecute and onPostExecute methods are running in the UI Thread itself again, so it just takes a blink to update your TextView
public class MyActivity extends Activity {
TextView t;
private class MyAsyncTask extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... void) {
//do your stuff
return null
}
protected void onPostExecute(Void void) {
MyActivity.this.t.setText("updated ^^v");
}
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
t = (TextView) findViewById(R.id.outputtext);
MyAsyncTask myAsyncTask = new MyAsyncTask();
myAsyncTask.execute();
}
}

Categories

Resources