Home > Software design >  How to pass data(value) from a fragment to an activity
How to pass data(value) from a fragment to an activity

Time:01-10

I want to pass a specific String from a fragment to an activity to use it there. When I am using Intent and Bundle, the value is null. I have tried several methods but can't seem to make it correctly. Can someone help, please?

In my Fragment :

Intent testintent = new Intent(getActivity(), MapActivity.class);         
Bundle bundle = new Bundle();         
bundle.putString("testing", "This is a test");         
testintent.putExtras(bundle);`

And in my Activity :

String message = getIntent().getStringExtra("testing");         
System.out.println("Value is : "   message);`

And this is what I am getting as a result in my console :

I/System.out: Value is : null

CodePudding user response:

In the Fragment :

    val intent = Intent(this, MapsActivity::class.java)
    intent.putExtra("testing", "This is a test")
    startActivity(intent)

In the receiving Activity :

    val extras = intent.extras
    if (extras != null) {
       val  receivingString = extras.getString("testing")
       System.out.println("Value is : "   receivingString)
    } else {
    
    }

CodePudding user response:

Using jave:

Intent intent = new Intent(getActivity(), MapActivity.class);
intent.putExtra("testing", "This is a test");
getActivity.startActivity(intent);
  • Related