Reputation: 761
In order to maintain navigation information in my ActionBar I want to stock these info (String + Context) in HashMap using the Static class below :
public class NavigationBarContainer {
public static HashMap<String, Context> hashTest;
}
But when I add a value referring to this constant class through 3 activities I only get the last entry : on each activity my HashMap has the last entry value and the HasMap size is always equal to 1..
This is how I access to it into my first activity :
public class HomeActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
HashMap<String, Context> ctxHash = new HashMap<String, Context>();
NavigationBarContainer.hashTest = ctxHash;
ctxHash.put("key1", getApplicationContext());
NavigationBarContainer.hashTest = ctxHash;
}
}
How I'm adding a value in 2 others activity :
public class Myctivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_one);
HashMap<String, Context> ctxHash;
ctxHash = NavigationBarContainer.hashTest;
ctxHash.put("key2", getApplicationContext());
NavigationBarContainer.hashTest = ctxHash;
}
}
I tried some tricks to access data differently but I have always the same issue.. need help?
EDIT :
This is solved but actually, I'm doing some others harder tricks.. I make a Super Class Activity wich implements ActionTab listener and I map this listener via my static HashMap every time I go in other Activity but it doesn't work. I will make an other post if I don't solve it.
Thanks
Upvotes: 0
Views: 1201
Reputation: 4178
NavigationBarContainer.hashTest = ctxHash;
Re-assign's your static variable each time. Instead, use this:
HashMap<String, Context> ctxHash = NavigationBarContainer.hashTest;
ctxHash.put("key1", getApplicationContext());
Or just:
NavigationBarContainer.hashTest.put("key1", getApplicationContext());
And make sure in your static class you change it to instantiate a hash map before the variable is used:
public static HashMap<String, Context> hashTest = new HashMap<String, Context>();
Upvotes: 1
Reputation: 8928
You're adding elements with the same key all the time. Keys are compared and if equal key is found in map the elements you're adding will replace the existing one.
Also, you're recreating the map all the time :))
Upvotes: 0