Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android HashMap in Bundle?

The android.os.Message uses a Bundle to send with it's sendMessage-method. Therefore, is it possible to put a HashMap inside a Bundle?

like image 277
Marcus Toepper Avatar asked Jul 12 '12 13:07

Marcus Toepper


3 Answers

try as:

Bundle extras = new Bundle();
extras.putSerializable("HashMap",hashMap);
intent.putExtras(extras);

and in second Activity

Bundle bundle = this.getIntent().getExtras();

if(bundle != null) {
   hashMap = bundle.getSerializable("HashMap");
}

because Hashmap by default implements Serializable so you can pass it using putSerializable in Bundle and get in other activity using getSerializable

like image 179
ρяσѕρєя K Avatar answered Nov 15 '22 18:11

ρяσѕρєя K


According to the doc, Hashmap implements Serializable, so you can putSerializable I guess. Did you try it ?

like image 24
AMerle Avatar answered Nov 15 '22 16:11

AMerle


Please note: If you are using a AppCompatActivity, you will have to call the protected void onSaveInstanceState(Bundle outState) {} (NOT public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {}) method.

Example code...

Store the map:

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putSerializable("leftMaxima", leftMaxima);
    outState.putSerializable("rightMaxima", rightMaxima);
}

And receive it in onCreate:

if (savedInstanceState != null) {
    leftMaxima = (HashMap<Long, Float>) savedInstanceState.getSerializable("leftMaxima");
    rightMaxima = (HashMap<Long, Float>) savedInstanceState.getSerializable("rightMaxima");
}

Sorry if it's some kind of a duplicate answer - maybe someone will find it useful. :)

like image 6
Martin Pfeffer Avatar answered Nov 15 '22 16:11

Martin Pfeffer