Karthik Karthik - 2 months ago 20
Java Question

How to access hashmap values from another class?

I would like to access hashmap set of values created in main class from other class.I have followed the steps for it but I am only getting null value at the sub-class.Here is the code

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);
}
}


//Sub Class

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
}
}


Have I missed anything?

Answer

make the HashMap static

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

In this way we can change values in any activity at will, regardless of the exact flow of control between the various activities.

Note that this trick can only be used if you don't care about the instantiation of more than one copy of the same activity (class) in the application, this is the easiest to implement

Step 2 : Android; Implementing global state; share data between Activities and across your application