Activity being destroyed when taking photo - java

When I do startActivityForResult to take a photo, the underlying Activity is destroyed. Even when I put
android:configChanges="orientation|keyboardHidden|screenSize"
in the manifest, any ideas would be extremely appreciated!

Probably your process is being terminated while your app is in the background. This is perfectly normal and will happen in many other cases, not just this one. You will need to adjust your application to deal with this situation (e.g., use the saved instance state Bundle).

Related

How to know when an app is killed after being in recents for a long time?

Which function is called when an app is killed by keeping it in recent apps list for a long time?
I am not asking about when an app is killed by swiping app from the recents list.
There is no such function in Android.
When user closes the app, the process is terminated with no notice. Even Activity's onDestroy method is not guaranteed to be called. Only when you explicitly call finish().
If you use ViewModel that is tied to the starting Activity's lifecycle, you can try to use onCleared() method, which is called always when ViewModel is no longer used and will be destroyed. See: https://developer.android.com/topic/libraries/architecture/viewmodel
There is no such function.
At the point when the system decides to kill your process, it will do so immediately without calling any more of your code beforehand.
Another answer suggests using ViewModel, but this won't work if you actually need a reliable signal. It is not guaranteed to trigger, and it may trigger in other circumstances (such as the user backing out of the activity, but the app process not being killed).

Click on item leads to IllegalStateException

How can this happen? I use a RecyclerView in an fragment and the fragment itself implements my click listener...
Sometimes, clicking an item in the list results in following error:
java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
How can this happen? Clicks should be forwarded to their handlers synchronous and this should not happen, should it?
Some code fragment would really help. But your error already states Can not perform this action after onSaveInstanceState
This means that after the function onSaveInstanceState() has been called, you try to do something. Put that code before onSaveInstanceState() and you might have a solution.
OnSaveInstance is called when the activity is about to be destroyed.
The android gives a last attempt to save all the data in a bundle that can be retrived back when the activity is recreated onRestoreInstance.
Mostly this case occurs when the android decide to garbage collect your activity due to lack of memory.
The error state that you are doing some work on UI -fragment after the onSaveInstance has been called.
Android does not allow any work on fragments after this has been called and soon onDestroy will be called.
So kindly revisit your logic or place a isFinishing() check before doing any work.
Actually it's because you're activity is getting destroyed due to lack of memory and before it gets destroyed it saves the fragment state also, and like you mentioned it happens sometine, during this you might have clicked your own which tried calling that previous state non click on the destroyed fragment.
How can you avoid it
Use volley and Picasso. And check which part of your application is using more memory using memory monitor given in android studio.
Also if you are not able to reduce memory usage consider adding.
large heap="true"
in your manifest

Android Studio: Out of Memory Error, Parse API [duplicate]

I spent 4 full days trying everything I can to figure out the memory leak in an app I'm developing, but things stopped making sense a long time ago.
The app I'm developing is of social nature, so think profile Activities (P) and list Activities with data - for example badges (B). You can hop from profile to a badge list to other profiles, to other lists, etc.
So imagine a flow like this P1 -> B1 -> P2 -> B2 -> P3 -> B3, etc. For consistency, I'm loading profiles and badges of the same user, so each P page is the same and so is each B page.
The general gist of the problem is: after navigating for a bit, depending on the size of each page, I get an out-of-memory exception in random places - Bitmaps, Strings, etc - it doesn't seem to be consistent.
After doing everything imaginable to figure out why I am running out of memory, I have come up with nothing. What I don't understand is why Android isn't killing P1, B1, etc if it runs out of memory upon loading and instead crashes. I would expect these earlier activities to die and be resurrected if I ever Back to them via onCreate() and onRestoreInstanceState().
Let alone this - even if I do P1 -> B1 -> Back -> B1 -> Back -> B1, I still get a crash. This indicates some sort of a memory leak, yet even after dumping hprof and using MAT and JProfiler, I can't pinpoint it.
I've disabled loading of images from the web (and increased the test data loaded to make up for it and make the test fair) and made sure the image cache uses SoftReferences. Android actually tries to free up the few SoftReferences it has, but right before it crashes out of memory.
Badge pages get data from the web, load it into an array of EntityData from a BaseAdapter and feed it to a ListView (I'm actually using CommonsWare's excellent MergeAdapter, but in this Badge activity, there is really only 1 adapter anyway, but I wanted to mention this fact either way).
I've gone through the code and was not able to find anything that would leak. I cleared and nulled everything I could find and even System.gc() left and right but still the app crashes.
I still don't understand why inactive activities that are on the stack don't get reaped, and I'd really love to figure that out.
At this point, I'm looking for any hints, advice, solutions... anything that could help.
Thank you.
I still don't understand why inactive activities that are on the stack
don't get reaped, and I'd really love to figure that out.
This is not how things work. The only memory management that impacts activity lifecycle is the global memory across all processes, as Android decides that it is running low on memory and so need to kill background processes to get some back.
If your application is sitting in the foreground starting more and more activities, it is never going into the background, so it will always hit its local process memory limit before the system ever comes close to killing its process. (And when it does kill its process, it will kill the process hosting all the activities, including whatever is currently in the foreground.)
So it sounds to me like your basic problem is: you are letting too many activities run at the same time, and/or each of those activities is holding on to too many resources.
You just need to redesign your navigation to not rely on stacking up an arbitrary number of potentially heavy-weight activities. Unless you do a serious amount of stuff in onStop() (such as calling setContentView() to clear out the activity's view hierarchy and clear variables of whatever else it may be holding on to), you are just going to run out of memory.
You may want to consider using the new Fragment APIs to replace this arbitrary stack of activities with a single activity that more tightly manages its memory. For example if you use the back stack facilities of fragments, when a fragment goes on the back stack and is no longer visible, its onDestroyView() method is called to completely remove its view hierarchy, greatly reducing its footprint.
Now, as far as you crashing in the flow where you press back, go to an activity, press back, go to another activity, etc and never have a deep stack, then yes you just have a leak. This blog post describes how to debug leaks: http://android-developers.blogspot.com/2011/03/memory-analysis-for-android.html
Some tips:
Make sure you are not leak activity context.
Make sure you are don't keep references on bitmaps. Clean all of your ImageView's in Activity#onStop, something like this:
Drawable d = imageView.getDrawable();
if (d != null) d.setCallback(null);
imageView.setImageDrawable(null);
imageView.setBackgroundDrawable(null);
Recycle bitmaps if you don't need them anymore.
If you use memory cache, like memory-lru, make sure it is not using to much memory.
Not only images take alot of memory, make sure you don't keep too much other data in memory. This easily can happens if you have infinite lists in your app. Try to cache data in DataBase.
On android 4.2, there is a bug(stackoverflow#13754876) with hardware acceleration, so if you use hardwareAccelerated=true in your manifest it will leak memory. GLES20DisplayList - keep holding references, even if you did step (2) and no one else is referencing to this bitmap. Here you need:
a) disable hardware acceleration for api 16/17;
or
b) detach view that holding bitmap
For Android 3+ you can try to use android:largeHeap="true" in your AndroidManifest. But it will not solve your memory problems, just postpone them.
If you need, like, infinite navigation, then Fragments - should be your choice. So you will have 1 activity, which will just switch between fragments. This way you will also solve some memory issues, like number 4.
Use Memory Analyzer to find out the cause of your memory leak.
Here is very good video from Google I/O 2011: Memory management for Android Apps
If you dealing with bitmaps this should be a must read: Displaying Bitmaps Efficiently
Bitmaps are often the culprit for memory errors on Android, so that would be a good area to double check.
Are you holding some references to each Activity? AFAIK this is a reason which keeps Android from deleting activities from the stack.
We're you able to reproduce this error on other devices as well? I've experienced some strange behaviour of some android devices depending on the ROM and/or hardware manufacturer.
I think the problem maybe a combination of many factors stated here in the answers are what is giving you problems. Like #Tim said, a (static) reference to an activity or an element in that activity can cause the GC to skip the Activity. Here is the article discussing this facet. I would think the likely issue comes from something keeping the Activity in an "Visible Process" state or higher, which will pretty much guaranty that the Activity and its associated resources never get reclaimed.
I went through the opposite problem a while back with a Service, so that's what got me going on this thought: there is something keeping your Activity high on the process priority list so that it won't be subject to the system GC, such as a reference (#Tim) or a loop (#Alvaro). The loop doesn't need to be an endless or long running item, just something that runs a lot like a recursive method or cascaded loop (or something along those lines).
EDIT: As I understand this, onPause and onStop are called as needed automatically by Android. The methods are there mainly for you to overide so that you can take care of what you need to before the hosting process is stopped (saving variables, manually saving state, etc.); but note that it is clearly stated that onStop (along with onDestroy) may not be called in every case. Additionally, if the hosting process is also hosting an Activity, Service, etc. that has a "Forground" or "Visible" status, the OS might not even look at stopping the process/thread. For example: an Activity and a Service are both luanched in the same process and the Service returns START_STICKY from onStartCommand() the process automatically takes at least a visible status. That might be the key here, try declaring a new proc for the Activity and see if that changes anything. Try adding this line to the declaration of your Activity in the Manifest as: android:process=":proc2" and then run the tests again if your Activity shares a process with anything else. The thought here is that if you've cleaned up your Activity and are pretty sure that the problem is not your Activity then something else is the problem and its time to hunter for that.
Also, I can't remember where I saw it (if I even saw it in the Android docs) but I remember something about a PendingIntentreferencing an Activity may cause an Activity to behave this way.
Here is a link for the onStartCommand() page with some insights on the process non-killing front.
One of the things that really helped the memory issue in my case ended up being setting inPurgeable to true for my Bitmaps. See Why would I ever NOT use BitmapFactory's inPurgeable option? and the answer's discussion for more info.
Dianne Hackborn's answer and our subsequent discussion (also thanks, CommonsWare) helped clarify certain things I was confused about, so thank you for that.
so the only thing i can really think of is if you have a static variable that references directly or indirectly to the context. Even something so much as a reference to part of the application. I'm sure you have already tried it but i will suggest it just in case, try just nulling out ALL of your static variables in the onDestroy() just to make sure the garbage collector gets it
The biggest source of memory leak I have found was caused by some global, high level or long-standing reference to the context. If you are keeping "context" stored in a variable anywhere, you may encounter unpredictable memory leaks.
Try passing getApplicationContext() to anything that needs a Context. You might have a global variable that is holding a reference to your Activities and preventing them from being garbage collected.
I encountered the same problem with you. I was working on a instant messaging app, for the same contact, it is possible to start a ProfileActivity in a ChatActivity, and vice versa.
I just add a string extra into the intent to start another activity, it takes the information of class type of starter activity, and the user id. For example, ProfileActivity starts a ChatActivity, then in ChatActivity.onCreate, I mark the invoker class type 'ProfileActivity' and user id, if it's going to start an Activity, I would check whether it is a 'ProfileActivity' for the user or not. If so, just call 'finish()' and go back to the former ProfileActivity instead of creating a new one.
Memory leak is another thing.

How can I do some cleanup right before an Android app is quitting?

Is there some sort of onTerminate() method where I can do some cleanup (I want to clear some SharedPreferences) when my Android app is terminating?
I have an Activity that is keeping a running average of a few numbers, that I'm storing in a SharedPreference. I want this average to last while the app is running (the user can move between different activities) so I can't clear it on onDestroy() for that particular activity. I need to be able to clear it once the app is about to quit.
How can I do this?
I've not tried this, but here's what I would do:
As Alex mentioned in the comment to original question, use a Service to share the app-wide state between Activities.
Whenever you move between Activities, bind to the service from the "new" activity, and unbind from the "old" one. Check this to understand how to coordinate activities.
If you follow this properly, you can ensure that at least one Activity is always bound to the Service as long as your app is running; and that all Activities are unbound when the app is no longer running - at which point your service's onDestroy() is called. This is where you perform your cleanup.
So android doesn't really have a concept of an app being "finished". Unfortunently there is nothing synonymous to "onTerminate()". Is there some criteria by which you can decide when to clear your running average?
Use SharedPreference.Editor to remove the preferences, and commit. Here's a link for you: http://developer.android.com/reference/android/content/SharedPreferences.Editor.html

android thread crashes when screen orientation changes

I am making an android app, which needs to download a text from a url and show it on a alertdialog.
I created a new thread. The thread reads a file on the web, a progressdialog appears before the thread starts, the thread packages the file content from the web on bundle , and passes it to a handler, the handler stops the progress, and shows the text from the bundle on a alertdialog. Well this works pretty good, but when the screen orientation changes when the progressdialog is shown and the thread is running, the app crashes. Any ideas on how to fix this thing?
Any help will be appreciated. :)
When the orientation changes, normally the OS will shut down your activity completely and restart it. That will mess up your download thread. One solution that might work is to save the Thread object as non-configuration data. You'll need to override onRetainNonConfigurationInstance() in your activity. However: do not do this if your Thread object has any references to any view- or activity-related object. That will cause a huge memory leak and will make your users very unhappy very quickly.
See the guide topic Handling Runtime Changes for details on using onRetainNonConfigurationInstance() and also an alternative approach. See the article Avoiding Memory Leaks on ... well, just that.
Add activity to menifest file as following -
<activity
android:name=".MyActivity" //Replace MyActivity with Your activity
android:configChanges="orientation|screenSize|screenLayout">
</activity>
This usually happens because your Activity actually gets destroyed and recreated on orientation changes.
Your options are:
Embrace the destruction, and use an AsyncTask instead of a Thread to fetch your data. You cancel() the task in your onDestroy() method.
Also use AsyncTask and cancel() it in your onDestroy() method. Additionally, handle configuration changes such as in the answers to this question.
KSubedi... Assumptions can be dangerous. Step by step testing to eliminate the exception may reveal that it is the running progress dialog that is causing the exception. The cure is:
protected void onPause() {
super.onPause();
//if (asynch != null) {asynch.cancel(true);}
if (progress != null){progress.cancel();}
}
JAL

Categories