Activity只有一個按鈕帶值“a”、“b”、“c”跳轉到ActivityB
ActivityB的代碼
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity_b);
recive();
setArray();
}
```//接收Bundle
private void recive() {
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
A = bundle.getString("a", "");
B = bundle.getString("b", "");
C = bundle.getString("c", "");
Set<String> set = bundle.keySet();
for (String value : set) {
mMap.put(value, bundle.getString(value, ""));
}
Log.e("Tag", "--->>>>" + A + "----->>" + B + "----->>>>" + C);
Log.e("TagMap", "--->>>>" + mMap.toString());
}
}
```class Util {
String a;
String b;
String c;
public Util(String a, String b, String c) {
this.a = a;
this.b = b;
this.c = c;
}
public Map<String, Object> getMap() {
Map<String, Object> map = new HashMap<>();
map.put("title", a);
map.put("value", b);
map.put("type", c);
return map;
}
}
class Util2 {
String a;
String b;
String c;
public Util2(String a, String b, String c) {
this.a = a;
this.b = b;
this.c = c;
}
public Map<String, Object> getMap2() {
Map<String, Object> map = new HashMap<>();
map.put("title", mMap.get(a));
map.put("value", mMap.get(b));
map.put("type", mMap.get(c));
return map;
}
}
public Util u[] = {
new Util(A, B, C),
new Util(A, B, C),
new Util(A, B, C),
new Util(A, B, C),
};
public Util2 u2[] = {
new Util2("a", "b", "c"),
new Util2("a", "b", "c"),
new Util2("a", "b", "c"),
new Util2("a", "b", "c"),
};
private void setArray() {
for (Util a : u) {
Log.e("tagUtil", "--->>>" + a.getMap().get("title") + "--->>>" + a.getMap().get("value") + "--->>>" + a.getMap().get("type"));
}
for (Util2 b : u2) {
Log.e("tagUtil2", "--->>>" + b.getMap2().get("title") + "--->>>" + b.getMap2().get("value") + "--->>>" + b.getMap2().get("type"));
}
}
打印的Log
04-05 10:50:23.413 14371-14371/com.project.xzj.testbundle E/Tag﹕ --->>>>a----->>b----->>>>c
04-05 10:50:23.413 14371-14371/com.project.xzj.testbundle E/TagMap﹕ --->>>>{b=b, c=c, a=a}
04-05 10:50:23.413 14371-14371/com.project.xzj.testbundle E/tagUtil﹕ --->>>--->>>null--->>>null
04-05 10:50:23.413 14371-14371/com.project.xzj.testbundle E/tagUtil﹕ --->>>--->>>null--->>>null
04-05 10:50:23.413 14371-14371/com.project.xzj.testbundle E/tagUtil﹕ --->>>--->>>null--->>>null
04-05 10:50:23.413 14371-14371/com.project.xzj.testbundle E/tagUtil﹕ --->>>--->>>null--->>>null
04-05 10:50:23.413 14371-14371/com.project.xzj.testbundle E/tagUtil2﹕ --->>>a--->>>b--->>>c
04-05 10:50:23.413 14371-14371/com.project.xzj.testbundle E/tagUtil2﹕ --->>>a--->>>b--->>>c
04-05 10:50:23.413 14371-14371/com.project.xzj.testbundle E/tagUtil2﹕ --->>>a--->>>b--->>>c
04-05 10:50:23.413 14371-14371/com.project.xzj.testbundle E/tagUtil2﹕ --->>>a--->>>b--->>>c
我想問題的是 為什util的值取成員變量A 、B、C的為空,而用map取值的Util2則有值?
之後我想了很久,後來突然知道了,我寫的數組也算成員變量,在運行接收數據的方法前他把數組初始化了,那時A、B、C的初始值是null,當我遍歷Util u[]數組的時候,他輸出的是null,所以把數組變成局部變量時候,獲取的值就是是我需要的值。