簡體   English   中英

如何通過android中的意圖將字典從一個活動傳遞到另一個活動

[英]how to pass dictionary from one activity to another activity via intent in android

我有一個字典,我需要通過onclick方法通過Intent傳遞給另一個Activity.How如何將dictionray置於intent中以及如何從另一個activity中的intent獲取它。

您應該將字典實現為Parcelable接口。 它還具有比Serializable更高的性能。

實現Parcelable將幫助您通過意圖發送和接收自定義對象。

以下鏈接將幫助您實現Parcelable:

http://prasanta-paul.blogspot.in/2010/06/android-parcelable-example.html

http://xjaphx.wordpress.com/2011/06/24/pass-complex-object-structure-to-intent/

如果通過意圖發送數據涉及復雜性,對於自定義數據結構,請嘗試另一種更簡單的方法:

以下帶代碼的步驟將指導您如何工作。

第一: 創建一座橋梁

創建一個名為Bridge的類,如下所示:

class Bridge
{
    private Bridge{
    }

    static Bridge obj = null;
    public static Bridge instance()
    {
         if (obj == null) 
         obj = new Bridge();
         return obj;
    }

    public ArrayList<String> aList; // put your data structure here

 }

第二: 發送數據

在要從中發送數據的Activity.java文件中,輸入此代碼。 這是初始化Bridge類的數據結構的部分

ArrayList<String> sendList = new ArrayList<String>();
Bridge.instance().aList = sendList; // where sendList is the data structure that contains your data

第三: 接收數據

在Activity.java文件中接收這樣的數據

ArrayList<String> receiveList = new ArrayList<String>();
receiveList = Bridge.instance().alList;

字典需要是Serializable。

你可以像這樣傳遞它:

Intent intent = new Intent(context, activity.class);
Bundle extras = new Bundle();

extras.putSerializable(key, dictionary);
intent.putExtras(extras);

startActivity(intent);

我使用以下方法訪問活動和片段中的對象:

public class MySharedObject {

    // add shared data fields here

    private static MySharedObject instance;
    private Context context;

    // only add Context if you need it
    public static MySharedObject getInstance(Context context) {
        if(instance != null) {
            instance.context = context; // update to context from caller
            return instance;
        }

        return instance = new MySharedObject(context); 
    }

    private MySharedObject(Context context) { // private constructor
        this.context = context;

        // do any initial loading needed
        // this constructor will only be called at the first getInstance call

    }

    ...

}

現在在任何Activity或Fragment調用中:

// this = getActivity() if inside Fragment
MySharedObject myObject = MySharedObject.getInstance(this); 

獲取共享數據。

至於你的字典,你只需添加userListDictionary字段和getter方法。 該調用可能看起來像:

Dictionary<Object, ArrayList<Object>> userListDictionary = SharedDictionary.getInstance(this).getUserListDictionary();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM