CursorWindowAllocationException thrown in SyncAdapter - android

I occasionally get the following exception thrown in my SyncAdapter class. I think that I am closing all cursors correctly. Can there be any other explanation for why this exception is being thrown? Or am I definitely missing a cursor.close() somewhere?
Fatal Exception: android.database.CursorWindowAllocationException: Cursor window could not be created from binder.
at android.database.CursorWindow.<init>(CursorWindow.java:150)
at android.database.CursorWindow.<init>(CursorWindow.java:42)
at android.database.CursorWindow$1.createFromParcel(CursorWindow.java:698)
at android.database.CursorWindow$1.createFromParcel(CursorWindow.java:696)
at android.database.BulkCursorDescriptor.readFromParcel(BulkCursorDescriptor.java:75)
at android.database.BulkCursorDescriptor$1.createFromParcel(BulkCursorDescriptor.java:34)
at android.database.BulkCursorDescriptor$1.createFromParcel(BulkCursorDescriptor.java:30)
at android.content.ContentProviderProxy.query(ContentProviderNative.java:424)
at android.content.ContentProviderClient.query(ContentProviderClient.java:161)
at android.content.ContentProviderClient.query(ContentProviderClient.java:123)
at com.forever.forever.Utils.sync.SyncAdapter.getNextItemInUploadQueue(SyncAdapter.java:799)
at com.forever.forever.Utils.sync.SyncAdapter.proccessUploads(SyncAdapter.java:697)
at com.forever.forever.Utils.sync.SyncAdapter.onPerformSync(SyncAdapter.java:199)
at android.content.AbstractThreadedSyncAdapter$SyncThread.run(AbstractThreadedSyncAdapter.java:272)

I was able to find an additional closable leaks by adding the following snippet to my application onCreate():
if(BuildConfig.DEBUG){
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.detectLeakedClosableObjects()
.penaltyLog()
.build());
}
It logged a couple leaks that I was able to fix. This is an EXTREMELY helpful development tool.

Related

When start strict mode and set `android:persistent` to `true` will has error. How can I fix this error?

When start strict mode and set android:persistent to true will has error. How can I fix this error? Thanks.
Application
override fun onCreate() {
if (BuildConfig.DEBUG) {
setStrictMode()
}
super.onCreate()
}
private fun setStrictMode() {
StrictMode.setThreadPolicy(StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork() // or .detectAll() for all detectable problems
.penaltyLog()
.build())
StrictMode.setVmPolicy(StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.detectLeakedClosableObjects()
.penaltyLog()
.penaltyDeath()
.build())
}
preference_example.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<SwitchPreference
android:key="switch_preference_night_mode"
android:persistent="true"
android:title="#string/theme_settings_night_mode" />
</PreferenceScreen>
PreferenceFragment:
public class ThemeSettingsFragment extends PreferenceFragmentCompat {
#Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.preference_example, rootKey);
}
}
Error log:
StrictMode: StrictMode policy violation; ~duration=30 ms: android.os.strictmode.DiskReadViolation
at android.os.StrictMode$AndroidBlockGuardPolicy.onReadFromDisk(StrictMode.java:1500)
at java.io.UnixFileSystem.checkAccess(UnixFileSystem.java:251)
at java.io.File.exists(File.java:815)
at android.app.ContextImpl.getDataDir(ContextImpl.java:2237)
at android.app.ContextImpl.getPreferencesDir(ContextImpl.java:550)
at android.app.ContextImpl.getSharedPreferencesPath(ContextImpl.java:747)
at android.app.ContextImpl.getSharedPreferences(ContextImpl.java:400)
at android.content.ContextWrapper.getSharedPreferences(ContextWrapper.java:174)
at android.content.ContextWrapper.getSharedPreferences(ContextWrapper.java:174)
at android.support.v7.preference.PreferenceManager.getSharedPreferences(PreferenceManager.java:330)
SharedPreferences are read from the disk the first time they are accessed and then cached in memory, hence your DiskReadViolation in strict mode.
While running all I/O as non-blocking off the main thread is ideal, even if you enable strict mode on Google Apps you will see red flashes at app start-up so you may not easily be able to get around your strict-mode violation.
The main thing for you to be concerned about is long-running HTTP requests or long-running database operations running on the main thread - these are to be avoided and the solutions involve using something like AsyncTask, RxJava or Kotlin coroutines.
For now, the SharedPreference and the associated setPreferenceFromResource have a modes of operation that you do not control and so you are unlikely to make things better by adding asynchronous code around these.

ModernAsyncTask IllegalStateException

We are using AsyncTaskLoaders in our app, to load the content. We are getting this crash
java.lang.IllegalStateException: Cannot execute task: the task is already running.
at android.support.v4.content.ModernAsyncTask.doInBackground(ModernAsyncTask.java:414)
at android.support.v4.content.AsyncTaskLoader.executePendingTask(AsyncTaskLoader.java:219)
at android.support.v4.content.AsyncTaskLoader.dispatchOnCancelled(AsyncTaskLoader.java:232)
at android.support.v4.content.AsyncTaskLoader$LoadTask.onCancelled(AsyncTaskLoader.java:88)
at android.support.v4.content.ModernAsyncTask.finish(ModernAsyncTask.java:464)
at android.support.v4.content.ModernAsyncTask.access$400(ModernAsyncTask.java:48)
at android.support.v4.content.ModernAsyncTask$InternalHandler.handleMessage(ModernAsyncTask.java:483)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:211)
at android.app.ActivityThread.main(ActivityThread.java:5335)
at java.lang.reflect.Method.invoke(Method.java)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1016)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:811)
We have tried to reproduce this, but haven't been successful!
Is there a way to find out which Loader that is causing this?
We are using
com.android.support:support-v4:23.0.1
We are looking into the possibility that this might have a link to Activity Leaks, other than that, this is all the info we are getting.
Any ideas?
I'm still hunting this error as I can't reproduce it myself, but I believe I found the cause (at least for my case, but I have to release and see if it helps).
Turns out that when creating the observer on my loader I passed the handler as null, expecting similar beheavior as I would get if I use the default constructor for Handler (for it to run on the main thread, the thread I was creating it from).
However what happens is that it calls onChange inmediately, from whatever thread.. onChange at least in my case calls the loader's onContentChanged, that is documented to need to be called from the main thread... as that's not the case, the task and cancellationTask get screwed up (for lack of a better technical term) which causes the cancellation to be triggered in an unexpected state of the task, hence the error message.
This also manifested in my case as the loader not correctly updating entries, the cancellationTask was already loaded with a value, so the loader discarded new tasks, so the new load was skipped (takeContentChanged was false).
So make sure you are initializing your observer using new Handler() from the main thread (onStartLoading should be a fine place to do it).
Propably you have in your activity, or wrapper class reference to async task. If you have execution of this task in onClick. You can tap two times on View and you get this error.
Update
If you want to check if activity has leaked , you can use Leak Canary. This is very useful tool.
Leak canary
You can use StrictMode for finding information about leaks.
public void onCreate() {
if (DEVELOPER_MODE) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork() // or .detectAll() for all detectable problems
.penaltyLog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.detectLeakedClosableObjects()
.penaltyLog()
.penaltyDeath()
.build());
}
super.onCreate();
}

Android StrictMode doesn't kill the app and report errors in eclipse

I am trying to use strict mode in android so I want the app to be turned off in case I do time consuming things on the main thread. This does not seem to happen I don't get any errors or warnings in the logcat in eclipse.
What do I need to change so StrictMode will kill the app and give me feedback in the logcat of where this violation occured? What would I need to do if I had a lot of fragments and activities in my project in order to make it work for a bigger project?
I have written the following code in my mainActivity:
public void onCreate(Bundle savedInstanceState) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork()
.penaltyLog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.detectLeakedClosableObjects()
.penaltyLog()
.penaltyDeath()
.build());
super.onCreate(savedInstanceState);
int disturb=0;
while(disturb<10000){
disturb += 2;
SystemClock.sleep(300);
}
}
Just use penaltyDeath() instead of penaltyLog() in first builder initialization.

Finding what violated StrictMode policy

I've enabled StrictMode in my app and it's causing a few crashes as expected.
How can I find out where in my code I'm violating these policies?
This is the stack trace:
E/AndroidRuntime(19523): FATAL EXCEPTION: main
E/AndroidRuntime(19523): android.os.StrictMode$StrictModeViolation: policy=95 violation=2
E/AndroidRuntime(19523): at android.os.StrictMode.executeDeathPenalty(StrictMode.java:1326)
E/AndroidRuntime(19523): at android.os.StrictMode.access$1300(StrictMode.java:111)
E/AndroidRuntime(19523): at android.os.StrictMode$AndroidBlockGuardPolicy.handleViolation(StrictMode.java:1319)
E/AndroidRuntime(19523): at android.os.StrictMode$AndroidBlockGuardPolicy$1.run(StrictMode.java:1206)
E/AndroidRuntime(19523): at android.os.Handler.handleCallback(Handler.java:605)
E/AndroidRuntime(19523): at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime(19523): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(19523): at android.app.ActivityThread.main(ActivityThread.java:4424)
E/AndroidRuntime(19523): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(19523): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(19523): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:787)
E/AndroidRuntime(19523): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:554)
E/AndroidRuntime(19523): at dalvik.system.NativeStart.main(Native Method)
but as you can see ... it's not very useful ... I know who killed my app, I need to know why!
Thanks.
You need to call penaltyLog() on your StrictMode.ThreadPolicy.Builder, so that it will show you the underlying reason as well as stopping your app.
Here's what you probably have currently:
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork()
.penaltyDeath()
.build());
If you call the network on the main thread, you'll get this exception which is hard to understand:
E/AndroidRuntime(8752): android.os.StrictMode$StrictModeViolation: policy=71 violation=4
E/AndroidRuntime(8752): at android.os.StrictMode.executeDeathPenalty(StrictMode.java:1311)
If you then add penaltyLog() to your policy...
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork()
.penaltyLog()
.penaltyDeath()
.build());
then you will see a much more helpful message like the one below. This will be in the LogCat output.
D/StrictMode(8810): StrictMode policy violation; ~duration=2956 ms: android.os.StrictMode$StrictModeNetworkViolation: policy=87 violation=4
D/StrictMode(8810): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1090)
If you look closely, you'll see that this stack trace will lead you to the code which is causing the StrictMode violation.
StrictMode (android.os.StrictMode) class can be used to enable and enforce various policies that can be checked for and reported upon.
This can be a StrictMode violation in executing a disk write violation that occurs when you are performing disk writes on the main UI thread. To solve it, you need to move the disk writes off the main thread.
If you can't move the code at this point, you could disable the check for a part of the code.
Explicitly add code to stop checking for a particular rule violation just before the offending code is executed and then re-enable detection for that rule after the offending code has completed.
StrictMode.ThreadPolicy old = StrictMode.getThreadPolicy();
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder(old)
.permitDiskWrites()
.build());
doCorrectStuffThatWritesToDisk();
StrictMode.setThreadPolicy(old);
Source code taken from here.
Whenever I see stack traces like this I always look into my Activity lifecycle events. Checkout what's going on in your onCreate, onResume, onPause methods (there are more lifecycle events but these are the common ones). Put break points in those methods and see which one terminates with this fatal message. Then take it from there.
Try catching this error using
protected void onResume() {
super.onResume();
try {
codeThatCrashesBecauseOfStrictMode();
} catch(Throwable tr) { Log.e(tr); }
}
This should be a pretty good starting point for debugging this problem.
even though this does nothing to understand root cause, would it help you to simply add "strict=False" to your Library definition? (note that my context is Robot Framework *** Settings *** where I include "Browser" library): eg:
Library Browser strict=False

Android StrictMode InstanceCountViolation

I am running my app with StrictMode activated in development as documented here StrictMode for lower platform versions
and noticed an error message that I do not know what to think about nor can I find any reference.
I get a android.os.StrictMode$InstanceCountViolation with values for instances and limit e.g.
instances=3; limit=2
Now I am wondering:
A) how is the limit calculated
B) how can such a violation actually happen and then I would look into evasive actions.
Any ideas?
It's all in the code
The key is StrictMode.sExpectedActivityInstanceCount and incrementExpectedActivityCount and decrementExpectedActivityCount:
Increment is called in ActivityThread.performLaunchActivity
just after creating the Activity instance.
Decrement is called in ActivityThread.performDestroyActivity
after the activity has been removed from the application.
So the limit is less each time an activity is destroyed, however if an instance is leaked the real instance count will be bigger than the limit, to detect if it's leaked they do some GC magic (in decrementExpectedActivityCount):
System.gc();
System.runFinalization(); // added in https://github.com/android/platform_frameworks_base/commit/6f3a38f3afd79ed6dddcef5c83cb442d6749e2ff
System.gc();
if after this the GC didn't remove the activity from the app's memory it is considered a leak.
Conclusion
Based on the above the only way to prevent is to make sure there are no references to the offending activity after onDestroy. The problem is that some there may be some WeakReferences which are still accessible through some native objects, which seem to have a different lifecycle. Here's how I came to this conclusion:
after backing out from MyActivity and seeing the log message
make a heap dump (.hprof)
open it in Eclipse Memory Analyzer
run OQL: select * from instanceof full.package.name.of.MyActivity
select all with Ctrl+Click or Shift+Click
right click and Merge Shortest Path to GC Roots > with all references
Workaround
If we increase the count initially we'll have more legroom before it reports the leak for specific classes:
// Application.onCreate or nearby where you set up StrictMode detectActivityLeaks
Method incrementExpectedActivityCount = StrictMode.class.getMethod("incrementExpectedActivityCount", Class.class)
incrementExpectedActivityCount.invoke(null, MyActivity.class);
incrementExpectedActivityCount.invoke(null, MyActivity2.class);
Further reading
WeakReferences
Eclipse Memory Analyzer (MAT)
History of StrictMode
It seems there might be a bug in the StrictMode checking on some devices.
If an Activity is started, and exited and restarted very quickly, you can get a StrictMode.InstanceCountViolation.
However this is simply because the garbage collector has not yet finalized the first instance of the Activity, meaning there are temporarily 2 (or more) instances in memory.
Calling System.gc() before startActivity() or startActivityForResult() will stop the StrictMode.InstanceCountViolation.
This seems to indicate a bug (or perhaps a feature?) in the StrictMode checking.
Here is a discussion on google groups about handling the StrictMode InstanceCountViolation. It looks like every different Android version has a different policy so they seem to just disable it. Also the Android docs say about Strict Mode
But don't feel compelled to fix everything that StrictMode finds. In particular, many cases of disk access are often necessary during the normal activity lifecycle. Use StrictMode to find things you did by accident. Network requests on the UI thread are almost always a problem, though.
I think that is what #sri is trying to show with his code.
public class MyApplication extends Application {
#Override
public void onCreate (){
super.onCreate();
// when you create a new application you can set the Thread and VM Policy
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectCustomSlowCalls() // API level 11, to use with StrictMode.noteSlowCode
.detectDiskReads()
.detectDiskWrites()
.detectNetwork()
.penaltyLog()
.penaltyFlashScreen() // API level 11
.build());
//If you use StrictMode you might as well define a VM policy too
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.detectLeakedClosableObjects() // API level 11
.setClassInstanceLimit(Class.forName(“com.apress.proandroid.SomeClass”), 100)
.penaltyLog()
.build());
}
}
My understanding is that this violation is used to detect memory leaks. So at that point you should only have 2 instances of the class loaded, but the VM found 3.
I have seen this violation in my code also, but my extra instances were all referenced by weak pointers. So I choose to disable this rule.
see the below example it varies based on android version
public class MyApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectCustomSlowCalls() // API level 11, to use with StrictMode.noteSlowCode
.detectDiskReads()
.detectDiskWrites()
.detectNetwork()
.penaltyLog()
.penaltyFlashScreen() // API level 11
.build());
// not really performance-related, but if you use StrictMode you might as well define a VM policy too
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.detectLeakedClosableObjects() // API level 11
.setClassInstanceLimit(Class.forName(“com.apress.proandroid.SomeClass”), 100) // API level 11
.penaltyLog()
.build());
}
}
Remove the line below from on create.
//StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll().penaltyLog().penaltyDeath().detectLeakedSqlLiteObjects().build());

Categories

Resources