tags:

views:

89

answers:

3

I am having SearchCritiera object and i make it singleton and declare this variable as static, now problem is if i left my application remain open for couple of hours that static object is removed by Android OS, how can i make sure static object should not be removed by the OS.

like i know there are few keywords like

Weekreference and softreference is there any strongreference keyword which can tell Android OS do not remove the reference ??

+1  A: 

Sadly, you can't force Android to keep your application in memory. If the OS feels it needs more memory for a foreground application or service it reserves the right to terminate one or all of your Activities.

I'm assuming what's happening is your static object is being lost and re-created when you call it, meaning that it has lost its state. That said, if you have a reference to the object in a foreground Activity I'm a little surprised that it's getting lost.

The best you can do work around this is hook into the lifecycle events and save the state of your singleton object and then restore it when appropriate.

Unfortunately, there are no Application wide lifecycle events in Androd. Have a look at this question for how to save transient application state.

Dave Webb
A: 

If i am not wrong when application remain open for long time data is released by the android OS, and while stopiong activity it will call "onSaveInstanceState" and when can i store searchritiera into this method and will it retrive back when "onRestoreInstanceState" is get called ?

private static SearchCriteria searchCriteria;


@Override 
    public void onSaveInstanceState(Bundle outState) 
    {
        outState.putSerializable(WLConstants.SEARCH_CRITERIA, searchCriteria);
        super.onSaveInstanceState(outState); 
    }
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        if(savedInstanceState != null){
            searchCriteria = (SearchCriteria)
            savedInstanceState.getSerializable(WLConstants.SEARCH_CRITERIA);
        }
        super.onRestoreInstanceState(savedInstanceState);
    }
Faisal khan
A: 

Don't use static references, even if your application remains in the foreground, these objects may be destroyed by the garbage collector (I've seen this happening a couple times now).

You can simply avoid this by storing them in your unique Application instance. That object is guaranteed to live as long as your app.

Matthias