Android:在活动之间传递哈希映射 [英] Android:Passing a hash map between Activities

查看:148
本文介绍了Android:在活动之间传递哈希映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串和一个类对象之间的映射。我在Activity1中填写这个地图,我想把它传递给activity2。

  public class NEW extends Activity {

public class data {
String name;
浮点值;
.... etc}

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


解决方案

假设您拥有两个活动(称为A和B)。在这种情况下,将地图放在公共静态变量中,并通过A.data_map从B访问。



[update]



对于所有的下拉列表,请查看 Android应用程序框架常见问题部分如何在单个应用程序中的活动/服务之间传递数据?我推荐的解决方案与...完全相同。


公共静态字段/方法



可以通过活动/服务
访问数据
的另一种方式是使用公共静态字段和/或
方法。您可以从
应用程序中的任何其他类访问这些静态
字段。要共享一个对象,创建你的对象

活动设置一个静态字段来指向这个
对象,任何其他
想要使用此对象的活动只需访问
这个静态字段。


是的,这个解决方案有注意事项,但OP提供的信息有限,我们不能假设此方法将无法正常工作。


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.

这篇关于Android:在活动之间传递哈希映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆