code

번들의 Android HashMap?

codestyles 2020. 10. 7. 07:40
반응형

번들의 Android HashMap?


android.os.Message사용 Bundle그것의 sendMessage 첨부 메소드와 함께 보낼 수 있습니다. 따라서 HashMap내부에 Bundle?


다음과 같이 시도하십시오.

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

두 번째 활동에서

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

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

때문에 해시 맵 기본 구현으로 Serializable는 사용하여 전달할 수 있도록 putSerializable번들 및 사용하여 다른 활동에서 얻을getSerializable


에 따르면 문서 , Hashmap구현은 Serializable, 그래서 당신은 수있는 putSerializable것 같아요. 해봤 어?


참고 : AppCompatActivity를 사용하는 경우 protected void onSaveInstanceState(Bundle outState) {}( NOT public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {} ) 메서드 를 호출해야합니다 .

예제 코드 ...

지도 저장 :

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

그리고 onCreate에서 수신합니다.

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

중복 된 답변 인 경우 죄송합니다. 누군가 유용하다고 생각할 수 있습니다. :)


번들의 모든 키를 보내려면 시도 할 수 있습니다.

for(String key: map.keySet()){
    bundle.putStringExtra(key, map.get(key));
}

  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;
}

I am using my kotlin implementation of Parcelable to achieve that and so far it works for me. It is useful if you want to avoid the heavy serializable.

Also in order for it to work, I recommend using it with these

Declaration

class ParcelableMap<K,V>(val map: MutableMap<K,V>) : Parcelable {
    constructor(parcel: Parcel) : this(parcel.readMap(LinkedHashMap<K,V>()))

    override fun writeToParcel(parcel: Parcel, flags: Int) {
        parcel.writeMap(map)
    }

    override fun describeContents(): Int {
        return 0
    }

    companion object CREATOR : Parcelable.Creator<ParcelableMap<Any?,Any?>> {
        @JvmStatic
        override fun createFromParcel(parcel: Parcel): ParcelableMap<Any?,Any?> {
            return ParcelableMap(parcel)
        }
        @JvmStatic 
        override fun newArray(size: Int): Array<ParcelableMap<Any?,Any?>?> {
            return arrayOfNulls(size)
        }
    }

}

Use

write

val map = LinkedHashMap<Int, String>()
val wrap = ParcelableMap<Int,String>(map)
Bundle().putParcelable("your_key", wrap)

read

val bundle = fragment.arguments ?: Bundle()
val wrap = bundle.getParcelable<ParcelableMap<Int,String>>("your_key")
val map = wrap.map

Don't forget that if your map K,V are not parceled by default they must implement Parcelable


In Kotlin:

hashMap = savedInstanceState?.getSerializable(ARG_HASH_MAP) as? HashMap<Int, ValueClass>

putSerializable(ARG_HASH_MAP, hashMap)

참고URL : https://stackoverflow.com/questions/11452859/android-hashmap-in-bundle

반응형