Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resume old activity by passing new data in bundle

I have couple of activities say A , B, C. Activity A starts B , B starts C and so on. In my app I have put a navigation drawer which allows users to go back to activity A. When user goes back to activity A I have passed some flags which don't actually restart the activity but just resumes it.

intent = new Intent(activity, A.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
        | Intent.FLAG_ACTIVITY_SINGLE_TOP);

Now I m trying to pass some data using bundles.

    bundle.putInt("selectedTab", FEATURED_COUPONS);
    intent.putExtras(bundle);

But in my activity A the bundle is always null.

if(bundle != null)
{
    if(bundle.containsKey("selectedTab"))
    {
        int tab = bundle.getInt("selectedTab");
    }
}
like image 517
Vihaan Verma Avatar asked Jun 23 '14 07:06

Vihaan Verma


People also ask

How do you refresh an activity on a resume?

I can use this intent to refresh the activity currently: Intent refresh = new Intent(this, Favorites. class); startActivity(refresh); this. finish();

How do you pass data between activities?

This example demonstrates how do I pass data between activities in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.

How pass data from second activity to first activity when pressed back Android?

Intent i = new Intent(this, SecondActivity. class); startActivityForResult(i, 1); In your SecondActivity set the data which you want to return back to FirstActivity. If you don't want to return back, don't set any.


2 Answers

You're going about things in the wrong way.

If all you want to do is put an Integer extra into the Intent extras then don't do this...

bundle.putInt("selectedTab", FEATURED_COUPONS);
intent.putExtras(bundle);

From the docs for putExtras(Bundle extras)...

Add a set of extended data to the intent. The keys must include a package prefix, for example the app com.android.contacts would use names like "com.android.contacts.ShowAll".

Instead just use...

intent.putExtra("selectedTab", FEATURED_COUPONS);

This isn't the real cause of your problem however. As Sumit Uppal mentions, you should implement onNewIntent(Intent intent) in Activity A. You can then use that to set the 'current' Intent to be the new Intent...

@Override
protected void onNewIntent(Intent intent) {
    if (intent != null)
        setIntent(intent);
}

Then in onResume() you can use...

Intent intent = getIntent();

...and then get the Bundle from that Intent.

like image 121
Squonk Avatar answered Oct 18 '22 22:10

Squonk


I think you should do " if(bundle != null)" task in onNewIntent(Intent) method

like image 2
Sumit Uppal Avatar answered Oct 18 '22 23:10

Sumit Uppal