Issue
I have two activities, MainActivity(With three Buttons) & SecondActivity(with a TextView). When one of the Buttons is clicked, it should open the SecondActivity with a specific extra data related to the clicked button sent to be viewed on the TextView. I'm using the same onClick method for all the three Buttons and identifying the clicked button based on the id of the clicked View... In the SecondActivity I try to get the Intent but don't know on which key should I call it? In other words, how to get the clicked button's related text in SecondActivity? Here's the code:
public class MainActivity extends AppCompatActivity {
public static final String B1 = "com.example.android.B1";
public static final String B2 = "com.example.android.B2";
public static final String B3 = "com.example.android.B3";
private Button mButton1;
private Button mButton2;
private Button mButton3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton1 = findViewById(R.id.button_1);
mButton2 = findViewById(R.id.button_2);
mButton3 = findViewById(R.id.button_3);
}
// XML's openSecondActivity on all the buttons.
public void openSecondActivity(View view) {
Intent intent = new Intent(this, SecondActivity.class);
if (view.getId() == mButton1.getId()) {
intent.putExtra(B1, R.string.text_1);
} else if (view.getId() == mButton2.getId()) {
intent.putExtra(B2, R.string.text_2);
} else {
intent.putExtra(B3, R.string.text_3);
}
startActivity(intent);
}
} // End MainActivity
public class SecondActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
TextView scrollableText = findViewById(R.id.scrollable_text);
// The source of problem!
scrollableText.setText(getIntent().getStringExtra(MainActivity.???)); // which Button?!
}
}
Solution
You will need to pass the values using the same key. So instead of the above try:
public static final String EXTRA_FROM_BUTTON = "com.example.android.B1";
if (view.getId() == mButton1.getId()) {
intent.putExtra(EXTRA_FROM_BUTTON, R.string.text_1);
} else if (view.getId() == mButton2.getId()) {
intent.putExtra(EXTRA_FROM_BUTTON, R.string.text_2);
} else {
intent.putExtra(EXTRA_FROM_BUTTON, R.string.text_3);
}
Then in your SecondActivity you can do:
scrollableText.setText(getIntent().getStringExtra(MainActivity.EXTRA_FROM_BUTTON));
Answered By - RestingRobot
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.