1

While working in Android Dev Studio, I have been working on two classes, MainActivity and Main2Activity.

MainActivity

public class MainActivity extends AppCompatActivity {
public static final String EXTRA_MESSAGE = ".com.company.name.practiceapp.MESSAGE";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

public void sendMessage(View view) {
    Intent intent = new Intent(this, Main2Activity.class);
    EditText editText = (EditText) findViewById(R.id.editText);
    String message = editText.getText().toString();
    intent.putExtra(EXTRA_MESSAGE, message);
    startActivity(intent);

    }
}

How would I go about using the String message in Main2Activity?

note: I browsed through many other similar questions but none of the answers said how to use it. The class is public (as you can see), so I couldn't figure out why I couldn't use message.

Mairead
  • 275
  • 1
  • 2
  • 10

3 Answers3

0
Intent intent = getIntent();
String text = intent.getStringExtra(".com.company.name.practiceapp.MESSAGE");

Original answer: https://stackoverflow.com/a/4233898/7339411

Curio
  • 1,331
  • 2
  • 14
  • 34
0

In your second activity in onCreate you do the following:

 Intent intent = getIntent();
 Bundle bundle = intent.getExtras();
 String variable = bundle.getString(EXTRA_MESSAGE);

You can also specify a default value like:

 String variable = bundle.getString(EXTRA_MESSAGE, "");
luckyhandler
  • 10,651
  • 3
  • 47
  • 64
0

Since you sent over the message already through an intent extra, you can retrieve it by referencing the intent in Main2Activity:

Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
Kevin Lee
  • 38
  • 4