Android Transmission de données différentes via une intention dans l'activité


Exemple

1. Passer des données entières:

SenderActivity

Intent myIntent = new Intent(SenderActivity.this, ReceiverActivity.class);
myIntent.putExtra("intVariableName", intValue);
startActivity(myIntent);

ReceiverActivity

Intent mIntent = getIntent();
int intValue = mIntent.getIntExtra("intVariableName", 0); // set 0 as the default value if no value for intVariableName found

2. Passer des données doubles:

SenderActivity

Intent myIntent = new Intent(SenderActivity.this, ReceiverActivity.class);
myIntent.putExtra("doubleVariableName", doubleValue);
startActivity(myIntent);

ReceiverActivity

Intent mIntent = getIntent();
double doubleValue = mIntent.getDoubleExtra("doubleVariableName", 0.00); // set 0.00 as the default value if no value for doubleVariableName found

3. Données de chaîne de transmission:

SenderActivity

Intent myIntent = new Intent(SenderActivity.this, ReceiverActivity.class);
myIntent.putExtra("stringVariableName", stringValue);
startActivity(myIntent);

ReceiverActivity

Intent mIntent = getIntent();
String stringValue = mIntent.getExtras().getString("stringVariableName");

ou

Intent mIntent = getIntent();
String stringValue = mIntent.getStringExtra("stringVariableName");

4. Transmission des données ArrayList:

SenderActivity

Intent myIntent = new Intent(SenderActivity.this, ReceiverActivity.class);
myIntent.putStringArrayListExtra("arrayListVariableName", arrayList);
startActivity(myIntent);

ReceiverActivity

Intent mIntent = getIntent();
arrayList = mIntent.getStringArrayListExtra("arrayListVariableName");

5. Passer des données d'objet:

SenderActivity

Intent myIntent = new Intent(SenderActivity.this, ReceiverActivity.class);
myIntent.putExtra("ObjectVariableName", yourObject);
startActivity(myIntent);

ReceiverActivity

Intent mIntent = getIntent();
yourObj = mIntent.getSerializableExtra("ObjectVariableName");

Remarque: gardez à l'esprit que votre classe personnalisée doit implémenter l'interface Serializable .

6. Transmission des données HashMap <String, String>:

SenderActivity

HashMap <String, String> hashMap;

Intent mIntent = new Intent(SenderActivity.this, ReceiverActivity.class);
mIntent.putExtra("hashMap", hashMap);
startActivity(mIntent);

ReceiverActivity

Intent mIntent = getIntent();    
HashMap<String, String> hashMap = (HashMap<String, String>)
mIntent.getSerializableExtra("hashMap");

7. Transmission de données Bitmap:

SenderActivity

Intent myIntent = new Intent(SenderActivity.this, ReceiverActivity.class);
myIntent.putExtra("image",bitmap);
startActivity(mIntent);

ReceiverActivity

Intent mIntent = getIntent();
Bitmap bitmap = mIntent.getParcelableExtra("image");