static variable null when returning to the app

2019-01-03 03:06发布

In my app there's a static variable that's being set to null when I return to my app from the external browser. Seems like the app or some portion of it is killed if the external web page I'm launching is complex enough.

If the app were to be killed entirely and then relauched from the main activity that would be ok, but the relaunch is from the activity that started the browser - and it's not meant to set the app state so it's crashing when accessing the null static variable. This is a one-out-of-six device problem for me so I need some advice.

Is there a flag to set to prevent this behavior?

8条回答
来,给爷笑一个
2楼-- · 2019-01-03 03:26

You probably just want to follow the second link by kabuko. But if you want to keep your static variable (perhaps you have some great reason for this), you could do this:

private static MyObjType getVariable()
{
   if (myVar == null)
     myVar = new MyObjType();  // do whatever else you need to here

   return myVar;
}

That way you can replace your calls to myVar.test() with getVariable().test() and you know it will never cause a null pointer exception.

查看更多
你好瞎i
3楼-- · 2019-01-03 03:30

Whenever you left your app & switching browser your app got in background. So you need to follow these steps

  1. First initialize your static variable in Sharedpreferece or in savedInstanceState as follow

    sharedpreference.purString("your_static_variable_name","your_static_variable_value").
    

    or

    savedInstanceState.putString("your_static_variable_name","your_static_variable_value").
    

in the first execution of oncreate() method of activity or elsewhere

  1. Second, reinitialize your static variables in onResume() methods via sharedpreference or savedInstance whichever is used earlier.
查看更多
登录 后发表回答