简体   繁体   中英

Getting bundle on Main activity when passing bundles by intent in android

So the problem I am having is that my app keeps crashing on launch, I have two activities. Activity A and Activity B. My app launches on Activity A but I have created a bundle in Activity B and I am sending it to Activity A. So when it launches the bundle is empty or null so it crashes, how do i fix this? thanks.

This is in Activity A (Launching Activity) in on create

    Bundle extras = getIntent().getExtras();
    Title = extras.getString("Title");
    Description = extras.getString("Description");
    Price = extras.getString("Price");
    Availability = extras.getString("Availability");

Then we have me creating the bundle in Activity B

     Intent intent = new Intent(B.this, A.class);
                Bundle extras = new Bundle();
                extras.putString("Title", PostTitle);
                extras.putString("Description", PostDescription);
                extras.putString("Price", PostPrice);
                extras.putString("Availability", PostAvail);
                intent.putExtras(extras);
                startActivity(intent);

I would suggest the following:

A. Use Bundle from Intent:

Intent pIntent = new Intent(this, JustaClass.class);
Bundle extras = pIntent.getExtras();
extras.putString(key, value); 

B. Create a new Bundle:

Intent pIntent = new Intent(this, JustaClass.class);
Bundle pBundle = new Bundle();
pBundle.putString(key, value);
mIntent.putExtras(pBundle);

C. Use putExtra() method of the Intent:

Intent pIntent = new Intent(this, JustaClass.class);
pIntent.putExtra(key, value);

Finally in the launched Activity, you can read them hrough:

String value = getIntent().getExtras().getString(key)

I just used Strings as an example for passing, I refer to Bundle and Intent .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM