1. 程式人生 > >(轉)Android五種資料傳遞方法彙總

(轉)Android五種資料傳遞方法彙總

Android開發中,在不同模組(如Activity)間經常會有各種各樣的資料需要相互傳遞,我把常用的幾種
方法都收集到了一起。它們各有利弊,有各自的應用場景。
我現在把它們集中到一個例子中展示,在例子中每一個按紐代表了一種實現方法。

1. 利用Intent物件攜帶簡單資料

利用Intent的Extra部分來儲存我們想要傳遞的資料,可以傳送int, long, char等些基礎型別,對複雜的物件就無能為力了。

1.1 設定引數

  1. //傳遞些簡單的引數
  2. Intent intentSimple = new Intent();  
  3. intentSimple.setClass(MainActivity.this,SimpleActivity.
    class);  
  4. Bundle bundleSimple = new Bundle();  
  5. bundleSimple.putString("usr""xcl");  
  6. bundleSimple.putString("pwd""zj");  
  7. intentSimple.putExtras(bundleSimple);  
  8. startActivity(intentSimple);  
1.2接收引數
  1. this.setTitle("簡單的引數傳遞例子");  
  2. //接收引數
  3. Bundle bunde = this.getIntent().getExtras();  
  4. String eml = bunde.getString("usr"
    );  
  5. String pwd = bunde.getString("pwd");   

2. 利用Intent物件攜帶如ArrayList之類複雜些的資料

這種原理是和上面一種是一樣的,只是要注意下。 在傳引數前,要用新增加一個List將物件包起來。

2.1 設定引數

  1. //傳遞複雜些的引數
  2. Map<String, Object> map1 = new HashMap<String, Object>();  
  3. map1.put("key1""value1");  
  4. map1.put("key2""value2");  
  5. List<Map<String, Object>> list = new
     ArrayList<Map<String, Object>>();  
  6. list.add(map1);  
  7. Intent intent = new Intent();  
  8. intent.setClass(MainActivity.this,ComplexActivity.class);  
  9. Bundle bundle = new Bundle();  
  10. //須定義一個list用於在budnle中傳遞需要傳遞的ArrayList<Object>,這個是必須要的
  11. ArrayList bundlelist = new ArrayList();   
  12. bundlelist.add(list);   
  13. bundle.putParcelableArrayList("list",bundlelist);  
  14. intent.putExtras(bundle);                
  15. startActivity(intent);  
2.1 接收引數
  1. <span style="white-space:pre;"> </span>   this.setTitle("複雜引數傳遞例子");  
  2.         //接收引數
  3.          Bundle bundle = getIntent().getExtras();   
  4.          ArrayList list = bundle.getParcelableArrayList("list");  
  5.         //從List中將引數轉回 List<Map<String, Object>>
  6.          List<Map<String, Object>> lists= (List<Map<String, Object>>)list.get(0);  
  7.          String sResult = "";  
  8.          for (Map<String, Object> m : lists)    
  9.          {    
  10.              for (String k : m.keySet())    
  11.              {    
  12.                   sResult += "\r\n"+k + " : " + m.get(k);    
  13.              }            
  14.          }    

3. 通過實現Serializable介面

3.1 設定引數

利用Java語言本身的特性,通過將資料序列化後,再將其傳遞出去。

  1. //通過Serializable介面傳引數的例子
  2. HashMap<String,String> map2 = new HashMap<String,String>();  
  3. map2.put("key1""value1");  
  4. map2.put("key2""value2");  
  5. Bundle bundleSerializable = new Bundle();  
  6. bundleSerializable.putSerializable("serializable", map2);  
  7. Intent intentSerializable = new Intent();     
  8. intentSerializable.putExtras(bundleSerializable);  
  9. intentSerializable.setClass(MainActivity.this,   
  10.                             SerializableActivity.class);                      
  11. startActivity(intentSerializable);    

3.2 接收引數

  1. this.setTitle("Serializable例子");  
  2.   //接收引數
  3.    Bundle bundle = this.getIntent().getExtras();      
  4.    //如果傳 LinkedHashMap,則bundle.getSerializable轉換時會報ClassCastException,不知道什麼原因
  5.    //傳HashMap倒沒有問題。      
  6.    HashMap<String,String> map =  (HashMap<String,String>)bundle.getSerializable("serializable");  
  7. String sResult = "map.size() ="+map.size();  
  8. Iterator iter = map.entrySet().iterator();  
  9. while(iter.hasNext())  
  10. {  
  11.     Map.Entry entry = (Map.Entry)iter.next();  
  12.     Object key = entry.getKey();  
  13.     Object value = entry.getValue();  
  14.     sResult +="\r\n key----> "+(String)key;  
  15.     sResult +="\r\n value----> "+(String)value;            
  16. }  

4. 通過實現Parcelable介面

這個是通過實現Parcelable介面,把要傳的資料打包在裡面,然後在接收端自己分解出來。這個是Android獨有的,在其本身的原始碼中也用得很多,

效率要比Serializable相對要好。

4.1 首先要定義一個類,用於 實現Parcelable介面

因為其本質也是序列化資料,所以這裡要注意定義順序要與解析順序要一致噢。

  1. publicclass XclParcelable implements Parcelable {  
  2.     //定義要被傳輸的資料
  3.     publicint mInt;  
  4.     public String mStr;  
  5.     public HashMap<String,String> mMap = new HashMap<String,String>();  
  6.     //Describe the kinds of special objects contained in this Parcelable's marshalled representation.
  7.     publicint describeContents() {  
  8.         return0;  
  9.     }  
  10.     //Flatten this object in to a Parcel.
  11.     publicvoid writeToParcel(Parcel out, int flags) {  
  12.         //等於將資料對映到Parcel中去
  13.         out.writeInt(mInt);          
  14.         out.writeString(mStr);  
  15.         out.writeMap(mMap);  
  16.     }  
  17.     //Interface that must be implemented and provided as a public CREATOR field 
  18.     //that generates instances of your Parcelable class from a Parcel. 
  19.     publicstaticfinal Parcelable.Creator<XclParcelable> CREATOR  
  20.             = new Parcelable.Creator<XclParcelable>() {  
  21.         public XclParcelable createFromParcel(Parcel in) {  
  22.             returnnew XclParcelable(in);  
  23.         }  
  24.         public XclParcelable[] newArray(int size) {  
  25.             returnnew XclParcelable[size];  
  26.         }  
  27.     };  
  28.     private XclParcelable(Parcel in) {  
  29.         //將對映在Parcel物件中的資料還原回來
  30.         //警告,這裡順序一定要和writeToParcel中定義的順序一致才行!!!
  31.         mInt = in.readInt();          
  32.         mStr  = in.readString();  
  33. 相關推薦

    Android資料傳遞方法彙總

    Android開發中,在不同模組(如Activity)間經常會有各種各樣的資料需要相互傳遞,我把常用的幾種方法都收集到了一起。它們各有利弊,有各自的應用場景。我現在把它們集中到一個例子中展示,在例子中每一個按紐代表了一種實現方法。1. 利用Intent物件攜帶簡單資料利用In

    Android資料傳遞方法彙總

           Android開發中,在不同模組(如Activity)間經常會有各種各樣的資料需要相互傳遞,我把常用的幾種 方法都收集到了一起。它們各有利弊,有各自的應用場景。我現在把它們集中到一個例子

    Django 前後臺的資料傳遞

    Django 從後臺往前臺傳遞資料時有多種方法可以實現。 最簡單的後臺是這樣的: from django.shortcuts import render def main_page(request): return render(request, 'index.html') 這個就是返回index

    Android開發書籍推薦:從入門到精通系列學習路線書籍介紹

    成長 程序員 理論 targe base 官方 app als 自己的 Android開發書籍推薦:從入門到精通系列學習路線書籍介紹 轉自:http://blog.csdn.net/findsafety/article/details/52317506 很多時候我們都會

    android:inputType參數類型說明

    網頁 char xtu cnblogs div 日期 mes signed rac android:inputType參數類型說明 android:inputType="none"--輸入普通字符 android:inputType="text"--輸入普通字符 a

    Android中Parcelable接口用法

    string date 場景 應用 用法 反序列化 數組 auth 序列化對象 1. Parcelable接口 Interface for classes whose instances can be written to and restored from a Parce

    二十三設計模式及其python實現

    本文原始碼寄方於github:https://github.com/w392807287/Design_pattern_of_python 參考文獻: 《大話設計模式》——吳強 《Python設計模式》——pythontip.com 《23種設計模式》——http://www.cnblogs.com/

    與其他系統介面對接java,json格式資料傳遞···OkHttpClient方式

    上一種方式HttpURLConnection方式出現了點問題,就是在idea中啟動服務一切正常。當時用tomcat部署專案時候,對方介面接收引數出現中文亂碼問題。用了很多方式都沒有解決,不知有沒有大佬可以解決 引入依賴 <dependency>

    與其他系統介面對接java,json格式資料傳遞···HttpURLConnection方式

    這個操作是與****系統進行資料介面的對接,本系統向****系統傳遞幾個引數,****系統接收並返回值。 目錄 post請求方式 @Service層 工具類ResultUtil pom需要新增的依賴 get請求方式 另一種 OkHttpClient 方式 post

    Android資料儲存方式之SQLite資料庫儲存 載入SD卡資料庫 sql操作 事務 防止SQL注入

    資料庫 前言 資料庫儲存 資料庫建立 內建儲存資料庫 外接儲存資料庫 編寫DAO 插入操作 更新操作 刪除操作 查詢操作

    Android資料儲存方式之檔案儲存 內部儲存 外部儲存 檔案讀取儲存操作封裝

    檔案儲存 前言 檔案儲存 記憶體 內部儲存 外部儲存 內部儲存操作 API 讀寫操作 外部儲存操作 公共目錄 私有目錄

    十道海量資料處理面試題與十個方法大總結

          首先是這一天,並且是訪問百度的日誌中的IP取出來,逐個寫入到一個大檔案中。注意到IP是32位的,最多有個232個IP。同樣可以採用對映的方法,比如模1000,把整個大檔案對映為1000個小檔案,再找出每個小文中出現頻率最大的IP(可以採用hash_m

    Android NDK編譯Openssl-1.1.0f靜態庫

    https://blog.csdn.net/ljttianqin/article/details/72991869 0 前言 按照原始碼C:\openssl-1.1.0f下的INSTALL檔案中的編譯指導,在Windows中用Cygwin模擬Linux環境順利編譯出libcrypt.a和libs

    android Apk打包過程概述_android是如何打包apk的

    最近看了老羅分析android資源管理和apk打包流程的部落格,參考其他一些資料,做了一下整理,脫離繁瑣的打包細節和資料結構,從整體上概述了apk打包的整個流程。 流程概述: 1、打包資原始檔,生成R.java檔案 2、處理aidl檔案,生成相應java

    Vue 爬坑之路—— 元件之間的資料傳遞

    Vue 的元件作用域都是孤立的,不允許在子元件的模板內直接引用父元件的資料。必須使用特定的方法才能實現元件之間的資料傳遞。 首先用 vue-cli 建立一個專案,其中 App.vue 是父元件,components 資料夾下都是子元件。 一、父元件向子元件傳遞資料

    Android資料儲存方式

    1、分類 資料儲存在開發中是使用最頻繁的,Android平臺中實現資料儲存主要有5種方式,分別是: SQLite: SQLite是一個輕量級嵌入式資料庫,支援基本SQL語法,是常被採用的一種資料儲存方式。Android為此資料庫提供了一個名為SQLiteDatabase的類,

    設計模式2——單例模式singleton構建方法最喜歡列舉和內部類方式

    單例模式,在配置檔案的時候用的比較多,各處的配置都保持統一性。 一、什麼是單例模式? layout title folder permalink categories tags

    mybatis常用jdbcType資料型別

    Mybatis中javaType和jdbcType對應和CRUD例子 <resultMap type="java.util.Map" id="resultjcm"> <result property="FLD_NUMBER" column="FLD

    Android 軟鍵盤監聽回車不起作用

    1. imeOptions <EditText android:imeOptions="actionSend"/> 或 mEditText.setImeOptions(EditorInfo.IME_ACTION_SEND);

    Native和html5的互動Android native傳資料給js

    js裡面 某函式用來接收android傳過來的資料 function onDeviceScanResult(data) { alert("Device Scan Result:" + data); } Android裡面把資料拼接成字串發給js ta); }W