-1

I need to make a Fragment (Dialog Box, whatever) with content that changes depending on what the user selects. This means that I need to transfer string data from my main activity to the activity responsible for the fragment. How do I do this?

Nathan Tuggy
  • 2,237
  • 27
  • 30
  • 38

1 Answers1

0

You can add extras to an Intent you use when starting an activity from inside of another.

So, for example, wherever you handle the users selection in the first Activity (Let's call it Activity A) you can send that string to Activity B like this:

Intent intent = new Intent(ActivityA.this, ActivityB.class);
intent.putExtra("stringKey", "stringValue");
startActivity(intent);

The first parameter is a key used to reference the extra that you need, and the value is whatever String you want passed to the next activity.

Then, somewhere in Activity B you can read the string like so:

if(getIntent().getExtras().containsKey("stringKey"){
   String passedStr = getIntent().getStringExtra("stringKey");
}

And the original "stringValue" will be assigned to 'passedStr'.

AdamMc331
  • 16,492
  • 10
  • 71
  • 133
  • Thanks for the response, but I seem to have run into another issue. When I paste the 'Activity B' code, it gives me a invalid method declaration; return type required. Any ideas? – Max Cukrowski Apr 23 '15 at 01:50
  • That must have to do with the broader code. Chances are you pasted the code into a method like `public myMethod()...` You need to have a return type like `public void myMethod()` or `public String myMethod()` – AdamMc331 Apr 23 '15 at 01:51