I have Activity A which loads fragments based on menu selects. If I make an intent from Activity B to Activity A, the default specified Activity A fragment will load. What I want to achieve is to load another fragment from Activity A instead of the default one. I hope this makes at least a bit of sense. What I tried to do is this -->
In Activity B I have -->
btnlinkToForum.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
ReaderActivity.class);
i.putExtra("fragmentNumber", 1);
startActivity(i);
}
});
And I try based on the putExtra data to load the specific fragment in Activity A like that --> I put this code into the onCreate method
if (getIntent().getIntExtra("fragmentNumber", 0) == 1) {
FragmentManager fm = ReaderActivity.this.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
FragmentForum fragment = new FragmentForum();
if (fragment != null) {
// Replace current fragment by this new one
ft.replace(R.id.activity_main_content_fragment, fragment);
ft.commit();
// Set title
tvTitle.setText("Forum");
}
}
This however loads the default fragment instead ... Any help will be highly appreciated
This works ;) My issue was that I mixed the button ids that initialized the intent so basically I though I was pressing the right button because the name of the button was correct but I was referencing the wrong button id so that is why I was always getting a null value! This being said below is the code that works for me! In activity B:
btnToForum.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(RssListActivity.this,
ReaderActivity.class);
//pass data to an intent to load a specific fragment of reader activity
String fragmnet = "forum";
i.putExtra("fragment", fragmnet);
startActivity(i);
}
});
In Activity A:
Intent i = getIntent();
String fragmentName = i.getStringExtra("fragment");
String forum = "forum";
Log.e("Test1", "Test1" + fragmentName);
if (fragmentName != null && fragmentName.equals(forum)) {
Do some magic here ;)
}
Can anyone give an example on how this can be done ... Whenever I try to get the value using for example getIntent().getStringExtra("whatever"); I get a null value ... –
Definitely you shall get values from one activity to another for example:
Activity_A.java
Intent i = new Intent(this, SignUpActivity.class);
i.putStringExtra("key", value);
startActivity(i);
Activity_B.java
onCreate()
{
Intent i = getIntent();
String var = i.getStringExtra("key");
..
}
P.S: If you would like to pass an object
i.putSerializable("object", object);
and
(Class) i.getSerializable("object");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With