Android HashMap in Bundle?

后端 未结 7 2354
眼角桃花
眼角桃花 2020-12-02 11:57

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

相关标签:
7条回答
  • 2020-12-02 12:16

    If you want to send all the keys in the bundle, you can try

    for(String key: map.keySet()){
        bundle.putStringExtra(key, map.get(key));
    }
    
    0 讨论(0)
  • 2020-12-02 12:18

    In Kotlin:

    hashMap = savedInstanceState?.getSerializable(ARG_HASH_MAP) as? HashMap<Int, ValueClass>
    
    putSerializable(ARG_HASH_MAP, hashMap)
    
    0 讨论(0)
  • 2020-12-02 12:21

    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

    0 讨论(0)
  • 2020-12-02 12:25

    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. :)

    0 讨论(0)
  • 2020-12-02 12:29

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

    0 讨论(0)
  • 2020-12-02 12:29
      public static Bundle mapToBundle(Map<String, Object> data) throws Exception {
        Bundle bundle = new Bundle();
        for (Map.Entry<String, Object> entry : data.entrySet()) {
            if (entry.getValue() instanceof String)
                bundle.putString(entry.getKey(), (String) entry.getValue());
            else if (entry.getValue() instanceof Double) {
                bundle.putDouble(entry.getKey(), ((Double) entry.getValue()));
            } else if (entry.getValue() instanceof Integer) {
                bundle.putInt(entry.getKey(), (Integer) entry.getValue());
            } else if (entry.getValue() instanceof Float) {
                bundle.putFloat(entry.getKey(), ((Float) entry.getValue()));
            }
        }
        return bundle;
    }
    
    0 讨论(0)
提交回复
热议问题