安卓:传递活动之间的哈希映射

2023-09-12 00:32:21 作者:草莓味甜甜圈

我有字符串和类对象之间的映射。我填充这个地图活动1,我想将它传递给活性2。

 公共类新的延伸活动{

    公共类数据{
            字符串名称;
            浮动值;
                 ....   等等  }

 ......
    静态地图<字符串,数据和GT; data_map =新的HashMap<字符串,数据及GT;();
   .....}
 

解决方案

我假设你拥有这两项活动(称他们为A和B)。在这种情况下,只要把地图上的公共静态变量,并通过A.data_map选自B访问它。

[更新] 的

对于所有的downvotes的偷看在 Android应用程序框架常见问题解答部分我怎么在单个应用程序传递活动/服务之间的数据?。我推荐的解决方案是完全一样...

  

公共静态字段/方法

     

这是另一种方法,使数据   整个活动/服务访问   是使用公共静态字段和/或   的方法。您可以访问这些静态   从其他类领域的   应用。共享对象,该   活动创造你的对象   设置一个静态字段指向这个   对象和任何其他的活动,   要使用这个对象只是访问   该静态字段。

是的,有警告这一解决方案,但在有限的信息$ P $由OP psented我们不能假设这种方法是行不通的。

微传下载 安卓手机版apk 优亿市场

I have a map between string and a class object. I populate this map in Activity1 and i would like to pass it to activity2.

public class NEW extends Activity {

    public class data {
            String name;
            float value;
                 ....   etc  }

 ......   
    static Map<String, data> data_map = new HashMap<String, data>();
   .....  }

解决方案

I am assuming you own both Activities (call them A and B). In which case just put the map in a public static variable and access it from B via A.data_map.

[update]

For all of the downvotes take a peek at the Android Application Framework FAQ section "How do I pass data between Activities/Services within a single application?". The solution I recommend is exactly the same as...

A public static field/method

An alternate way to make data accessible across Activities/Services is to use public static fields and/or methods. You can access these static fields from any other class in your application. To share an object, the activity which creates your object sets a static field to point to this object and any other activity that wants to use this object just accesses this static field.

Yes, there are caveats to this solution but with the limited info presented by the OP we can not assume this method will not work.

相关推荐