简体   繁体   中英

Passing 3 elements (Intents)

I would like to pass the following three elements from one activity to another:

String a = "a";
String b = "b";
String c = "c";

I have tried the following with no success:

In the main activity (MainActivity):

Bundle extras = new Bundle();
extras.putString("a", a);
extras.putString("b", b);
extras.putString("c", c);
Intent intent = new Intent(MainActivity.this, SubActivity.class);
intent.putExtras(extras);
startActivity(intent);

In the sub activity (SubActivity):

Bundle extras = new Bundle();
String a = extras.getString("a");
String b = extras.getString("b");
String c = extras.getString("c");

In the SubActivity, you should get the Bundle by calling getIntent().getExtras(); , not by making a new Bundle.

public class SubActivity extends Activity {
    public void onCreate(Bundle saved) {
        super.onCreate(saved);
        setContentView(...);

        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            // call extras.getString() here
        }
    }
}
String array[] = {"a","b","c"};

Intent i = new Intent(A.this, B.class);
i.putExtra("array", array);
startActivity(i);

In the activity B :

Bundle extras = getIntent().getExtras();
String[] arrayB = extras.getStringArray("array");

In your SubActivity

Instead of

 Bundle extras = new Bundle();  

Use the below

 Bundle extras = getIntent().getExtras();
 if(extras!=null)
 {
       String a = extras.getString("a");
       String b = extras.getString("b");
       String c = extras.getString("c");
 } 

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