Search code examples
androidnullpointerexceptiononresume

NullPointerException after resuming the application


Ok, this annoying problem is probably quite familiar, but I don't know what its being called and how to solve it. When I open my app and go to the menu and after a meanwhile, when resuming the app, I loose all my data. It seems that android likes to clean data in order to keep the OS as fast and stable as possible. Which method is recommended in saving data in the internal memory and retrieving it back when any kind of variable is cleaned/null before resuming the app? I tried setSharedPreferences to parse an ArrayList to an Object and parse the Object as a String to save the data and retrieve it, but I get cannot parse Object to String exception. There has to be a better alternative.

Any help will be appreciated.

Edit:

This is how I retrieve and store data:

JSONObject data = (JSONObject) new JSONTokener(result).nextValue();

Helper.RAW_PEOPLE_INFO = data.getJSONArray("people");
Helper.PEOPLE_CONTAINER = new ArrayList<PeopleInfoStorage>();
for( int i = 0; i < Helper.RAW_PEOPLE_INFO.length(); i++ ){
    Helper.PEOPLE_CONTAINER.add( new PeopleInfoStorage(Helper.RAW_PEOPLE_INFO.getJSONObject(i)) );
}

I use the PEOPLE_CONTAINER ArrayList to use it later for when I need it. The PEOPLE_CONTAINER ArrayList gets probably cleaned before I resume my application, so can someone help me giving an example on how to store this ArrayList in the internal memory so I can retrieve the data from the internal memory and put it back to the PEOPLE_CONTAINER ArrayList for when it's null again.

It needs to be something like this:

@Override
protected void onPause() {  
    if( Helper.PEOPLE_CONTAINER != null ){
        //save the Helper.PEOPLE_CONTAINER ArrayList to the internal memory
    }
    super.onPause();
}

@Override
protected void onResume() {
    if( Helper.PEOPLE_CONTAINER == null ){
        //retrieve the data and store it back to Helper.PEOPLE_CONTAINER ArrayList
    }
    super.onResume();
}

Solution

  • There are many methods to persist data in your application; I'm not going to go into great detail here, but you should check out these resources:

    http://developer.android.com/guide/topics/data/data-storage.html

    If you have an array list, it sounds like it might be worth SQLite.