Entrail
Entrail

Reputation: 1

Android - Open Activity and wait for Result before continue in calling class

I am quite new to Android and facing a problem.

I have a class A from where i would like to call another activity. I have found some post saying that there is no way to pause the calling Activity and wait for the result.

    public class A extends AppCompatActivity {
    [...]
    private List<String> list = new ArrayList<String>();

    private void doSomething() {
        list.add("a");
        list.add("b");
        for(String tmp:list) {
            Intent intent = new Intent(this, OtherActivity.class);
            intent.putStringExtra("TAG", tmp);
            startActivityForResult(intent, 1);
        }
    }

This is not a complete example but basically the problem I am facing.

I have a loop and try to open another activity. The loop does not stop when i start the "OtherActivity". The first thing i see is the OtherActivity for the last element of the list (here String "b"). When i finish this Activity i see the OtherActivity with String "a" in wrong order.

I considered a callback for this, but i am not sure how to implement it because the callback handler wouldn't be within the loop.

Again I am not sure if a callback would be a good idea because many people say i should not Pause the "calling" activity for the sub activity.

Upvotes: 0

Views: 506

Answers (2)

Denny
Denny

Reputation: 1783

If you want to pass the whole list of string to the other activity I suggest you do this

You can pass an ArrayList the same way, if the E type is Serializable.

You would call the putExtra (String name, Serializable value) of Intent to store, and getSerializableExtra (String name) for retrieval.

Example:

ArrayList<String> myList = new ArrayList<String>();
intent.putExtra("mylist", myList); 

In the other Activity:

ArrayList<String> myList = (ArrayList<String>) getIntent().getSerializableExtra("mylist");

Please note that serialization can cause performance issues: it takes time, and a lot of objects will be allocated (and thus, have to be garbage collected)

Source: Passing a List from one Activity to another

Or as Abdul suggested, save the data to a database and retrieve it from there in the other activity

Upvotes: 0

Abdul Kawee
Abdul Kawee

Reputation: 2727

You are doing it totally wrong, if you want to send data to other activity and do some work then get the result , i would prefer that send the whole data as a list , do the work and then get the data from that activity , you shouldn't be doing it in a loop. Either pass it is as intent or save it in database then retrieve from database.

Upvotes: 1

Related Questions