Why does the Intent that starts my activity not co

2019-04-28 20:19发布

问题:

I explained this badly originally. This is my question: The Intent I send to the startActivity() method, contains a private field, mMap, which is a Map containing the strings I sent to putExtra(). When the target activity starts, a call to getIntent() returns an Intent that does not contain those values. The mMap field is null. Obviously, something in the bowels of the View hierarchy or the part of the OS that started the new activity created a new Intent to pass to it, since the object IDs are different.

But why? And why are the putData() values not carried fowrard to the new Intent?

The activity that starts the new activity extends Activity. Here's the startup code:

public boolean onOptionsItemSelected(final MenuItem item) {
    switch (item.getItemId()) {
    case 4:
        i = new Intent(this, StatList.class);
        i.putExtra("Name1", "Test1");
        i.putExtra("Name3", "Test2");
        startActivity(i);
     }   
 }

I've tried the key values with and without the (recommended) complete package name prefix.

In the Eclipse debugger, I have verified the values for the player names are being inserted into i.mExtras.mMap properly.

Here's the code from the startee:

public class StatList extends ListActivity {
private final StatsListAdapter statsAdapter;

public StatList() {
    statsAdapter = StatsListAdapter.getInstance(this);
} // default ctor

@Override
public void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    final Intent i = getIntent();
    final Bundle extras = i.getExtras();
          < more code here >
} 

When execution gets to this method, mIntent.mExtras.mMap is null, and mIntent.mExtras.mParcelledData now contains some values that don't look sensible (it was null when startActivity() was called). getIntent() returns mIntent.

I've also tried startActivityForResult(), with the same result.

From the docs and the samples I've seen online & in the sample apps, this should be easy. I've found another way to meet my immediate need, but I'd like to know if anyone can help me understand why something this simple doesn't work.

回答1:

In your main Activity:

i = new Intent(this, StatList.class);
i.putExtra("Name1", "Test1");
i.putExtra("Name3", "Test2");
startActivity(i);

Then in StatList.class

Bundle extras = getIntent().getExtras();
String name1 = extras.getString("Name1");
String name3 = extras.getString("Name3");
Log.i("StatList", "Name1 = " + name1 + " && Name3 = " + name3)


回答2:

Update the following two line

final Intent i = getIntent(); final Bundle extras = i.getExtras();

Replace it with

Bundle extras = getIntent().getExtras();
if(extras!= null){
String var1= extras.getString("Name1");
String var2= extras.getString("Name2");
}