Search code examples
androidxamarinandroid-intentandroid-activityfragment

send data from a fragment to an activity xamarin android


I'm sorry I'm using google translate.

I am trying to send data from a Fragment to an Activity with no success, the purpose of this is to update a TextView. I can't validate that the Intent brings the data and if I eliminate the validation they have a null value, I detail my code.

Fragment

private void sendData()
 {
    Intent i = new Intent(Context,Activity.Class);
    //PACK DATA
    i.PutExtra("COUNT", "1");
    //START ACTIVITY
    Activity.StartActivity(i);
}

Invoked

void ButtonClicked2(object sender, EventArgs args)
    {
        sendData();
    }

Activity

protected override void OnResume()
    {
        base.OnResume();
        //Intent i = Intent;
        Bundle sender = Intent.Extras;

        ////IF ITS THE FRAGMENT THEN RECEIVE DATA
        if (sender != null)
        {
            receiveData();
            Android.Widget.Toast.MakeText(this, "Received", Android.Widget.ToastLength.Short).Show();

        }
       
    }
    private void receiveData()
    {
        //RECEIVE DATA VIA INTENT
        Intent i =  Intent;
       string count = i.GetStringExtra("COUNT");
       
        //SET DATA TO TEXTVIEWS
        Android.Widget.TextView CountView = FindViewById<Android.Widget.TextView>(Resource.Id.itemCount);
        CountView.SetText(count, Android.Widget.TextView.BufferType.Normal);
        Android.Widget.Toast.MakeText(this, count, Android.Widget.ToastLength.Short).Show();
    }

Solution

  • I was able to solve it on my own, although my solution does not completely convince me, I'll post it in case someone has the same problem as me.

    Fragment

    //add the activity reference to the fragment
    using static GumisaAPP.Activities.BaseActivity;
    
    
    //we create the procedure that will be in charge of modifying the activity's TextView
    private void sendData_CountItem()
     {
            string count;
            Variables.Contador_Items = Variables.Contador_Items + 1;
            count= Convert.ToString(Variables.Contador_Items);
    //we access the texview of the activity from the fragment
            TextView textCount = Activity.FindViewById<TextView>(Resource.Id.itemCount);
    // modify the text of the TextView
            textCount.SetText(count, TextView.BufferType.Normal);
     }
    
    // call the procedure
    private void EnviarDatos(){
    sendData_CountItem();
    }
    

    Thank you for taking the trouble to answer my question. Greetings