Android基礎 -- Activity之間傳遞資料(bitmap和map物件)
這邊文章很古老了,看到還有朋友回覆,這裡更新幾點,避免誤導大家。
第一,傳遞HashMap物件
HashMap本身已經實現了Cloneable, Serializable,Intent傳遞時,直接強轉就可以了。(感謝@qcks指正)
Map<String, String> params = new HashMap<>(); params.put("key", "value"); Intent intent = new Intent(app, Activity.class); intent.putExtra("parmas",(Serializable)params);
2. 傳遞Bitmap
強調一遍一定不要通過Intent傳
2.1 本地資源只傳遞R.id,然後通過resource去解析出來;
2.2 如果是SDCard中的檔案,只傳遞Uri;
2.3 如果是網路流,先本地儲存圖片,然後再傳遞路徑Uri。
當時的寫法水平很low,只是為了完成專案,弄了一個能用的方案,回頭再來看是在是水的一比。
不用再往下看了,以前的古老方案實在是不堪入目~~~
--------------------------------------------------我是分割線 2018.8.20,----------------------------------------------
做專案的時候需要用到在2個activity之間傳遞一些資料,之前做的都是些字串之類的東東,結果這次卡了好久,折騰了一個下午。
第一個:傳遞bitmap
這個問題非常奇葩(可能我android水平還不夠),居然不會報錯,我是直接用bundle或Intent的extral域直接存放bitmap,結果執行時各種宕機,各種介面亂竄(我非常的納悶)。。。搜尋之後看大家都說不能直接傳遞大於40k的圖片,然後在德問論壇上找到了解法。就是把bitmap儲存為byte陣列,然後再通過Intent傳遞。
的
程式碼如下所示:
Bitmap bmp=((BitmapDrawable)order_con_pic.getDrawable()).getBitmap(); Intent intent=new Intent(OrderConfirm.this,ShowWebImageActivity.class); ByteArrayOutputStream baos=new ByteArrayOutputStream(); bmp.compress(Bitmap.CompressFormat.PNG, 100, baos); byte [] bitmapByte =baos.toByteArray(); intent.putExtra("bitmap", bitmapByte); startActivity(intent);
其中 第一行程式碼就是如何從一個imageview中獲得其圖片,這個問題也倒騰了下,貌似用setDrawingCacheEnabled也行,因為開始用的這個方法,但是直接在activity之間傳遞bitmap,所以導致執行時錯誤,後來改正之後沒有再嘗試。
先new一個ByteArrayOutputStream流,然後使用Bitmap中的compress方法,把資料壓縮到一個byte中,傳輸就可以了。
在另一個activity中取出來的方法是:
imageView = (ZoomableImageView) findViewById(R.id.show_webimage_imageview);
Intent intent=getIntent();
if(intent !=null)
{
byte [] bis=intent.getByteArrayExtra("bitmap");
Bitmap bitmap=BitmapFactory.decodeByteArray(bis, 0, bis.length);
imageView.setImageBitmap(bitmap);
}
取出來位元組陣列之後,用BitmapFactory中的decodeByteArray方法組合成一個bitmap就可以了。
再加上一個儲存的程式碼:
public void saveMyBitmap(String bitName,Bitmap mBitmap) throws IOException {
File f = new File("/sdcard/Note/" + bitName);
if(!f.exists())
f.mkdirs();//如果沒有這個資料夾的話,會報file not found錯誤
f=new File("/sdcard/Note/"+bitName+".png");
f.createNewFile();
try {
FileOutputStream out = new FileOutputStream(f);
mBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
Log.i(TAG,e.toString());
}
}
2.傳遞map物件:
封裝到bundle中:
Map<String,Object> data=orderlist.get(arg2-1);
SerializableMap tmpmap=new SerializableMap();
tmpmap.setMap(data);
bundle.putSerializable("orderinfo", tmpmap);
intent.putExtras(bundle);
這個SeralizableMap是自己封裝的一個實現了Serializable介面的類:
public class SerializableMap implements Serializable {
private Map<String,Object> map;
public Map<String,Object> getMap()
{
return map;
}
public void setMap(Map<String,Object> map)
{
this.map=map;
}
}
這樣才能把map物件扔到bundle中去,
取出來的方法是:
Bundle bundle = getIntent().getExtras();
SerializableMap serializableMap = (SerializableMap) bundle
.get("orderinfo");