1

我有一本字典,我需要通过 onclick 方法通过 Intent 将其传递给另一个 Activity。如何将字典放入 Intent 以及如何从另一个 Activity 的 Intent 中获取它。

4

4 回答 4

3

您应该将字典实现为 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/

于 2013-10-24T13:09:57.247 回答
1

Provided the complexities involved in sending data via intents, for a custom data-structure, give a try to another, much easier approach:

The following steps with code will guide you how it works.

First : CREATE A BRIDGE

Create a class named Bridge as follows:

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

 }

Second : SEND DATA

In the Activity.java file from where you want to send data, put this code. This is the part where you initialize the data structure of Bridge class

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

Third : RECEIVE DATA

Receive the data like this in your Activity.java file

ArrayList<String> receiveList = new ArrayList<String>();
receiveList = Bridge.instance().alList;
于 2013-10-27T16:14:13.020 回答
0

我使用以下方法跨活动和片段访问对象:

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();
于 2013-10-24T14:08:49.913 回答
0

字典需要可序列化。

你可以像这样传递它:

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

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

startActivity(intent);
于 2013-10-24T12:46:41.357 回答