Roy Henriquez
Roy Henriquez

Reputation: 81

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?

Upvotes: 3

Views: 2233

Answers (2)

Mark
Mark

Reputation: 419

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.

Upvotes: 0

Pavneet_Singh
Pavneet_Singh

Reputation: 37404

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);
    };

Upvotes: 6

Related Questions