我想从其他类访问在主类中创建的值的hashmap集。我已经执行了相应的步骤,但在子类中只得到空值。下面是代码

public class SoapTester extends Activity {
private static final String TAG = "Test";
public HashMap<String, String> map = new HashMap<String, String>();

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    map.put("year", "Apple");
    map.put("make", "Mango");
    map.put("model", "Grape");
    map.put("style", "Orange");
    map.put("series", "Peach");
}

public HashMap<String, String> getHashmap() {
    Log.v(TAG, "map2: E" + map);
    return map;
}

public void setHashmap(HashMap<String, String> map) {
    this.map = map;
    getHashmap();
    Log.v(TAG, "map1: E" + map);
}
}

/ /子类
public class Tradein extends Activity {
private static final String TAG = "Test";

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.tradein);
    SoapTester ex = new SoapTester();
    HashMap<String, String> hm = ex.getHashmap();
    Log.v(TAG, "hm: " + hm);//Getting Null Value here
}
}

我错过什么了吗?

最佳答案

使hashmap成为静态的

public static HashMap<String, String> map = new HashMap<String, String>();

通过这种方式,我们可以随意更改任何活动中的值,而不必考虑各个活动之间的确切控制流。
注意,只有当您不关心应用程序中同一个活动(类)的多个副本的实例化时,才可以使用此技巧,这是最容易实现的
第二步:Android; Implementing global state; share data between Activities and across your application

08-07 00:55