Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
214 views
in Technique[技术] by (71.8m points)

android - App crashes when restoring from background after a long time

My application crashes after idling for a long time in the background. I debugged and found the reason that it is crashing is due to a NullPointerException. Exception was due to the fact that the data in the application singleton class is destroyed by the garbage collector when application is in background. I am using static data in each activity throughout my application.

My question is: is there any way to make the data of application class persistent when in background? Or is there any other solution?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For more accurate answer you put your code here. On, Android memory is limited so VM can remove any piece of code it think un-necessary.

Look into Activity life-cycle method, specially into onResume and make sure that you understand that perfectly. So many time application crashes just for not using Activity life-cycle method properly.

Another important design consideration for Activity is, no matter what happened with persistence data you Activity should display its UI with some default value. So assumption is like this, if i have data i will display if i don't, i really do not care. Your UI should never ever crash with or without data. You can use String.xml for storing some default value or even in layouts.

if you still want go with singleton class, which is perfectly fine but make sure you do the following checking every time you try to access your singleton.

if (instance==null)
    instance=Singleton.getInstance()

your getInstance() method not only return you current instance it will also make sure that

  • it initializes all object and variable
  • other singleton methods as instance method

Do not statically access data from one Activity to another. It is not good for android specially for the type problem you are facing now and also it is not very good OOP programming practice.

SharedPreference is good way to persist data, if that meet your requirement go for it.

if you want to pass data from different Android component like Activity, Service or BroadcastReciever you can put it inside a bundle and and send as intent. And, as always their are SQLLite data storage, file IO etc etc.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...