作者:A_mnesia
來源:CSDN
原文:https://blog.csdn.net/m13984458297/article/details/78330419
開發(fā)中在頁(yè)面跳轉(zhuǎn)中經(jīng)常需要徐攜帶數(shù)據(jù)到另一個(gè)頁(yè)面,常用的是intent傳遞尊浪,然而在intent的Bundle等傳遞數(shù)據(jù)時(shí)有一個(gè)緩沖區(qū)做裙,而這個(gè)緩沖區(qū)最大只有1MB肴敛,當(dāng)數(shù)據(jù)大于這個(gè)值時(shí)就會(huì)出現(xiàn)android.os.TransactionTooLargeException問題,這時(shí)就不能用intent來傳遞數(shù)據(jù)了厌秒,可以使用WeakReference來暫時(shí)保存數(shù)據(jù),具體的解決方法為:
WeakDataHolder 類:
package cn.longmaster.hospital.doctor.ui.consult;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;
/**
- Created by W·H·K on 2017/10/24.
*/
public class WeakDataHolder {
private static WeakDataHolder instance;
public static WeakDataHolder getInstance(){
if(instance == null){
synchronized (WeakDataHolder.class) {
if (instance == null) {
instance = new WeakDataHolder();
}
}
}
return instance;
}
private Map<String, WeakReference<Object>> map = new HashMap<>();
/**
* 數(shù)據(jù)存儲(chǔ)
* @param id
* @param object
*/
public void saveData(String id, Object object) {
map.put(id, new WeakReference<>(object));
}
/**
* 獲取數(shù)據(jù)
* @param id
* @return
*/
public Object getData(String id) {
WeakReference<Object> weakReference = map.get(id);
return weakReference.get();
}
}
這個(gè)類中提供了兩個(gè)方法:
在需要攜帶數(shù)據(jù)的時(shí)候,調(diào)用WeakDataHolder.getInstance().saveData("", object);(兩個(gè)參數(shù)痢缎,第一個(gè)是map的key,
第二個(gè)是需要傳遞的數(shù)據(jù)世澜,支持所有的數(shù)據(jù)類型)独旷;
在第二個(gè)頁(yè)面需要獲取的時(shí)候調(diào)用:
WeakDataHolder.getInstance().getData("");得到數(shù)據(jù)并轉(zhuǎn)換為需要的類型即可。
如:int aa=(int)WeakDataHolder.getInstance().getData("")