Chad
Chad

Reputation: 50

Android simple Hashmap not maintaining values?

I've recently tried to simplify some data structures by posting them into a simple key, value map. I push a log to verify the value has been associated to the key during the .put method.

When I later call a .get, the value is no longer available. Important code snippets:

MainActivity.class

public final HashMap<String, Integer> resumeMap = new HashMap<String, Integer>();

        if (resumeMap.containsKey(url)) {
                Log.i("Value is there!", url);
                resumeTime = resumeMap.get(url);
                Log.i("Value set to:", "" + resumeTime);
            } else {
                resumeTime = 0;
                Log.i("Value is not found!", "" + url);
            }

public void setHashmap(String url, Integer time) {
    resumeMap.put(url, time);
    int newTime = resumeMap.get(url);
    Log.i("Setting:", "URL: " + url);
    Log.i("Setting:", "TIME:" + newTime);
}

VideoPlayer.class

MainActivity setter = new MainActivity();
setter.setHashmap(urlString, player.getCurrentPosition());

In the setHashmap method, the log is correctly outputting both url and time as expected. However resumeMap.containsKey(url) is remaining false, even while the debugger is confirming an expected matching key via "Value is not found!" output.

To make clear, during first pass in MainActivity, I expect a not found result, the VideoPlayer class is then called with the resumeTime of 0 with proper results. I verify the setting of the key and value, and when I open the same link I am still receiving a 0.

I originally built the Hashmap in it's own class, with the same results. I moved the map to the MainActivity just to debug. Thank you for any assistance you may be able to provide.

Upvotes: 0

Views: 120

Answers (1)

Jason LeBrun
Jason LeBrun

Reputation: 13293

Activity instances are quickly destroyed and re-created all the time, for example, when you rotate the screen (but for other reasons as well). It often appears that the Activity is "still there", but the actual underlying object instance has been destroyed and recreated.

A quick way to verify that that is really the problem before going down the instance state bundle path is to make the HashMap static to prevent instance destruction from destroying it.

Sometimes, static maps like this are OK, but proceed with caution, as structures like this open up avenues for leaking memory all over the place. A better approach is to use some sort of persistence, or if you only need the information while the Activity is being used, pass the information around using onSaveInstanceState and onRestoreInstanceState (see http://developer.android.com/training/basics/activity-lifecycle/recreating.html)

Upvotes: 2

Related Questions