How do I pass a string from one class to another class

advertisements

This question already has an answer here:

  • How to pass an object from one activity to another on Android 31 answers

How can I pass a string from a public class to TextView of other class in Java (android)?

ClassA.java:

hereButton updateButton = (Button)findViewById(R.id.updateButton);
updateButton.setOnClickListener(new OnClickListener(){
    @Override
    public void onClick(View v) {
        String text = inputText.getText().toString();
        outputText.setText(text);
    }
});

ClassB.java:

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


Pass values using intents.

In your first Activity:

Intent i= new Intent("com.example.secondActivity");
// Package name and activity
// Intent i= new Intent(MainActivity.this,SecondActivity.Class);
// Explicit intents
i.putExtra("key",mystring);
// Parameter 1 is the key
// Parameter 2 is your value
 startActiivty(i);

In your second Activity retrieve it:

Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("key");
//get the value based on the key
}