Android五種數據傳遞方法彙總

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

1. 利用Intent對象攜帶簡單數據

利用Intent的Extra部分來存儲我們想要傳遞的數據,可以傳送int, long, char等一些基礎類型,對複雜的對象就無能爲力了。

1.1 設置參數

//傳遞些簡單的參數  
Intent intentSimple = new Intent();  
intentSimple.setClass(MainActivity.this,SimpleActivity.class);  

Bundle bundleSimple = new Bundle();  
bundleSimple.putString("usr", "xcl");  
bundleSimple.putString("pwd", "zj");  
intentSimple.putExtras(bundleSimple);  

startActivity(intentSimple);  

1.2 接收參數

//接收參數  
Bundle bunde = this.getIntent().getExtras();  
String eml = bunde.getString("usr");  
String pwd = bunde.getString("pwd");   

2. 利用Intent對象攜帶如ArrayList之類複雜些的數據

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

2.1 設置參數

//傳遞複雜些的參數  
Map<String, Object> map1 = new HashMap<String, Object>();  
map1.put("key1", "value1");  
map1.put("key2", "value2");  
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();  
list.add(map1);  

Intent intent = new Intent();  
intent.setClass(MainActivity.this,ComplexActivity.class);  
Bundle bundle = new Bundle();  
//須定義一個list用於在budnle中傳遞需要傳遞的ArrayList<Object>,這個是必須要的  
ArrayList bundlelist = new ArrayList();   
bundlelist.add(list);   
bundle.putParcelableArrayList("list",bundlelist);  
intent.putExtras(bundle);                
startActivity(intent); 

2.1 接收參數

        //接收參數  
         Bundle bundle = getIntent().getExtras();   
         ArrayList list = bundle.getParcelableArrayList("list");  
        //從List中將參數轉回 List<Map<String, Object>>  
         List<Map<String, Object>> lists= (List<Map<String, Object>>)list.get(0);  

         String sResult = "";  
         for (Map<String, Object> m : lists)    
         {    
             for (String k : m.keySet())    
             {    
                  sResult += "\r\n"+k + " : " + m.get(k);    
             }            
         } 

3. 通過實現Serializable接口

3.1 設置參數

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

//通過Serializable接口傳參數的例子  
HashMap<String,String> map2 = new HashMap<String,String>();  
map2.put("key1", "value1");  
map2.put("key2", "value2");  

Bundle bundleSerializable = new Bundle();  
bundleSerializable.putSerializable("serializable", map2);  
Intent intentSerializable = new Intent();     
intentSerializable.putExtras(bundleSerializable);  
intentSerializable.setClass(MainActivity.this,   
                            SerializableActivity.class);                      
startActivity(intentSerializable); 

3.2 接收參數

  //接收參數  
   Bundle bundle = this.getIntent().getExtras();      
   //如果傳 LinkedHashMap,則bundle.getSerializable轉換時會報ClassCastException,不知道什麼原因  
   //傳HashMap倒沒有問題。        
   HashMap<String,String> map =  (HashMap<String,String>)bundle.getSerializable("serializable");  

String sResult = "map.size() ="+map.size();  

Iterator iter = map.entrySet().iterator();  
while(iter.hasNext())  
{  
    Map.Entry entry = (Map.Entry)iter.next();  
    Object key = entry.getKey();  
    Object value = entry.getValue();  
    sResult +="\r\n key----> "+(String)key;  
    sResult +="\r\n value----> "+(String)value;            
}  

4. 通過實現Parcelable接口

這個是通過實現Parcelable接口,把要傳的數據打包在裏面,然後在接收端自己分解出來。這個是Android獨有的,在其本身的源碼中也用得很多,
效率要比Serializable相對要好。

4.1 首先要定義一個類,用於 實現Parcelable接口

因爲其本質也是序列化數據,所以這裏要注意定義順序要與解析順序要一致噢。

public class XclParcelable implements Parcelable {  

    //定義要被傳輸的數據  
    public int mInt;  
    public String mStr;  
    public HashMap<String,String> mMap = new HashMap<String,String>();  

    //Describe the kinds of special objects contained in this Parcelable's marshalled representation.  
    public int describeContents() {  
        return 0;  
    }  

    //Flatten this object in to a Parcel.  
    public void writeToParcel(Parcel out, int flags) {  
        //等於將數據映射到Parcel中去  
        out.writeInt(mInt);          
        out.writeString(mStr);  
        out.writeMap(mMap);  
    }  

    //Interface that must be implemented and provided as a public CREATOR field   
    //that generates instances of your Parcelable class from a Parcel.   
    public static final Parcelable.Creator<XclParcelable> CREATOR  
            = new Parcelable.Creator<XclParcelable>() {  
        public XclParcelable createFromParcel(Parcel in) {  
            return new XclParcelable(in);  
        }  

        public XclParcelable[] newArray(int size) {  
            return new XclParcelable[size];  
        }  
    };  

    private XclParcelable(Parcel in) {  
        //將映射在Parcel對象中的數據還原回來  
        //警告,這裏順序一定要和writeToParcel中定義的順序一致才行!!!  
        mInt = in.readInt();          
        mStr  = in.readString();  
        mMap  = in.readHashMap(HashMap.class.getClassLoader());  
    }  

    public XclParcelable() {  
        // TODO Auto-generated constructor stub  
    }  
}  

4.2 設置參數

//通過實現Parcelable接口傳參的例子  
                    Intent intentParcelable = new Intent();                   
                    XclParcelable xp = new XclParcelable();               
                    xp.mInt = 1;  
                    xp.mStr = "字符串";  
                    xp.mMap = new HashMap<String,String>();  
                    xp.mMap.put("key", "value");                      
                    intentParcelable.putExtra("Parcelable", xp);                      
                    intentParcelable.setClass(MainActivity.this,   
                                              ParcelableActivity.class);     
                    startActivity(intentParcelable); 

4.3 接收參數

        //接收參數  
     Intent i = getIntent();     
     XclParcelable xp = i.getParcelableExtra("Parcelable");     

     TextView  tv = (TextView)findViewById(R.id.tv);  
     tv.setText(" mInt ="+xp.mInt   
                    +"\r\n mStr"+xp.mStr  
                    +"\r\n size()="+xp.mMap.size());

5. 通過單例模式實現參數傳遞

單例模式的特點就是可以保證系統中一個類有且只有一個實例。這樣很容易就能實現,在A中設置參數,在B中直接訪問了。這是幾種方法中效率最高的。

5.1 定義一個單實例的類

//單例模式  
public class XclSingleton  
{  
    //單例模式實例  
    private static XclSingleton instance = null;  

    //synchronized 用於線程安全,防止多線程同時創建實例  
    public synchronized static XclSingleton getInstance(){  
        if(instance == null){  
            instance = new XclSingleton();  
        }     
        return instance;  
    }     

    final HashMap<String, Object> mMap;  
    public XclSingleton()  
    {  
        mMap = new HashMap<String,Object>();  
    }  

    public void put(String key,Object value){  
        mMap.put(key,value);  
    }  

    public Object get(String key)  
    {  
        return mMap.get(key);  
    }  

}  

5.2 設置參數

    //通過單例模式傳參數的例子  
    XclSingleton.getInstance().put("key1", "value1");  
    XclSingleton.getInstance().put("key2", "value2");  

    Intent intentSingleton = new Intent();                
    intentSingleton.setClass(MainActivity.this,   
                        SingletonActivity.class);                     
    startActivity(intentSingleton);   

5.3 接收參數

        //接收參數  
        HashMap<String,Object> map = XclSingleton.getInstance().mMap;                           
        String sResult = "map.size() ="+map.size();       

        //遍歷參數  
        Iterator iter = map.entrySet().iterator();  
        while(iter.hasNext())  
        {  
            Map.Entry entry = (Map.Entry)iter.next();  
            Object key = entry.getKey();  
            Object value = entry.getValue();  
            sResult +="\r\n key----> "+(String)key;  
            sResult +="\r\n value----> "+(String)value;                
        }  

轉載自:

http://www.2cto.com/kf/201311/256174.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章