Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force main Acivity to wait for subactivity in Android?

I am calling a subactivity from main activity. This subactivity should take few numbers from user (i'm using Edit text control to achieve this), save them to static variable in another class and terminate. I want main activity to wait for subactivity but both are just running simultaneously. Even doing sth like that doesn't help:

     Thread t = new Thread(new Runnable(){
     public void run(){
     Log.v("==================", "run "+new Date());
     startActivityForResult(new Intent(ctx,myCustomSubactivity.class),1);  
     } });
     Log.v("==================", "calling run "+new Date());
     t.start();      
     try {
        t.join();
    } catch (InterruptedException e) {Log.v("==================", "can't join");}
    Log.v("==================", "back from activity "+new Date());

do you know how to force main activity to wait? Thread.wait() method is not supported in Android(program throws error).

like image 428
questioner Avatar asked May 21 '10 06:05

questioner


3 Answers

May be I'm missing something but why don't just use startActivityForResult and onActivityResult mechanism? You could get result from you subactivity from intent it was resulted with.
Edit: BTW as far as I understand, if you will run Object.wait() from Activity code if will hold UI tread whitch can result in Application not responding error.

like image 134
Nikolay Ivanov Avatar answered Nov 09 '22 11:11

Nikolay Ivanov


I agree with Nikolay this is definitely the android way to do this.

Start the subactivity with startActivityForResult in the sub activity use setResult to add an result code and an intent with all the numbers you need in the data bundle.

In your first activity overwrite onActivityResult and retrieve the numbers from the Intent.

If you use the static variable this seems easier in the first moment but it is very insecure and there are some cases this may not work. If your program is send to the background your activities will be saved but if the phone runs low on memory the system will close your program and after the user resumes it everything looks like the moment the user left it but the static variables will be recreated to their initialization value.

Try to get used to the way the android activity lifecycle works. Using this approach will result in fewer used memory and a much better user experience.

like image 37
Janusz Avatar answered Nov 09 '22 09:11

Janusz


Check out the Notepad example, it covers exactly this situation. And as others have said, the Android way is to have your first activity start up your second activity (not sub-activity!) and asynchronously listen for a response (not pause or wait, no need for joining, etc.).

like image 3
Josh Avatar answered Nov 09 '22 11:11

Josh