简体   繁体   中英

Passing data between activities in Xamarin

I can't share the data I have in MainActivity to the Welcome activity, even though I followed the instructions of this page: https://developer.xamarin.com/recipes/android/fundamentals/activity/pass_data_between_activity/

MainActivity (Activity1)

Button button = FindViewById<Button>(Resource.Id.send);
EditText myName = FindViewById<EditText>(Resource.Id.name);
string name = myName.Text;

button.Click += delegate { 
    var welcome = new Intent(this, typeof(Welcome));
    welcome.PutExtra("name", name);
    StartActivity(welcome);
};

Welcome (Activity2)

string name = Intent.GetStringExtra("name") ?? "Data not available";

I get null, don't know why. Any suggestions or advise?

You have to fetch the text when the button is clicked otherwise it will have no value( because when the UI is created, EditText would be empty hence null value at that time ) so

string name = null;
button.Click += delegate { 
        name = myName.Text;
        var welcome = new Intent(this, typeof(Welcome));
        welcome.PutExtra("name", name);
        StartActivity(welcome);
    };

If you are going to a child view, use StartActivityForResult if you want to give back the result. You can get return objects in the ActivityResult:

protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)

So this is a good way for passing data and returning data between activities.

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