简体   繁体   中英

Passing Data Backwards and Forwards between two Activities

I've just started developing in Xamarin and have been having trouble passing an int[] both 'forward' and 'backwards' between two Activites. So when Activity 1 launches Activity 2, it should pass the int[] to Activity Two and when 'onBackPressed' is called on Activity 2, the int[] should be passed back to Activity 1.

I've got code in four places.

Activity One : Inside onCreate()

sharedIntent = new Intent(this,typeof(MyListViewActivity));
sharedIntent.PutExtra("SELECTED_LISTVIEW_ITEMS", selectedItems);
btnLaunchListViewActivity.Click += delegate { StartActivity(sharedIntent); };

Activity Two : Inside onCreate()

var previouslySelectedItems = Intent.GetIntArrayExtra("SELECTED_LISTVIEW_ITEMS");

if(previouslySelectedItems  != null) 
{
    foreach(int position in previouslySelectedItems )
    ListView.SetItemChecked(position, true);
}

Activity Two : Inside onBackPressed()

Intent.PutExtra("SELECTED_LISTVIEW_ITEMS", checkedItemPositions);

Activity One : Inside onRestart()

selectedItems = sharedIntent.GetIntArrayExtra("SELECTED_LISTVIEW_ITEMS");

Right now, it appears my int[] is going 'forward' into Activity Two but never 'back' into Activity One Any help would be greatly appreciated! Is Intent.GetIntArrayExtra in Activity Two calling the same intent as my sharedIntent in Activity One ?

You missed the startActivity() method in onBackPressed(). Or maybe you prefer to use in Activity1 the startActivityForResult() method and handle the result in onActivityResult().

I think the reason why that data is not received in the Activity One is because that Activity is not Subscribed to that Intent. When you start an Activity you have the option to pass an Intent with data. That is what you do with StartActivity(sharedIntent).

I am not sure but don't think onRestart() receives that Intent. Also, I doubt that onRestart() is actually triggered.

One thing you can do is to implement a Broadcast Reciever and filter by your Intent:

http://developer.android.com/reference/android/content/BroadcastReceiver.html

You can use startActivityForResult() instead of startActivity() to start the second Activity. This way, when the user press back to go to the first activity, the second activity will close. In the first Activity you will receive a call to onActivityResult() to handle the result of that second activity:

This is the header of that callback to handle the result:

protected void onActivityResult(int requestCode, int resultCode, Intent data);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM