1

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);
}
A. Rodas
  • 20,171
  • 8
  • 62
  • 72
user2413632
  • 31
  • 1
  • 1
  • 3

3 Answers3

5

Simply: you can make a third class and create a static string variable. Then you can access that variable within any class in the same project by using the following.

ClassC.java

public static String sharedValue = null;

You can access within any other class (with in the same package) as follows.

ClassC.sharedValue = "Some Text";   //set value

String s = ClassC.sharedValue;   //get value
Mogsdad
  • 44,709
  • 21
  • 151
  • 275
enadun
  • 3,107
  • 3
  • 31
  • 34
2

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
}
Raghunandan
  • 132,755
  • 26
  • 225
  • 256
0

In your first activity:

inside onclick(), do this

startActivity(new Intent(FirstActivity.this, SecondActivity.class).putExtra("key", "value to pass"));

And then in your second activity:

inside OnCreate(), do this:

Intent intent = getIntent();
String value = intent.getStringExtra("key");
Chintan Soni
  • 24,761
  • 25
  • 106
  • 174