Check if cursor is closed for staleDataException

Test: atest DocumentsUIGoogleTests
Bug: 162292209

Change-Id: Ia4df46e4a1938bc421754763fa9d8ca12fde6280
Merged-In: Ia4df46e4a1938bc421754763fa9d8ca12fde6280
(cherry picked from commit 56e7a5f9a8dcea2c8d61725907ce306f469d67cd)
diff --git a/src/com/android/documentsui/DirectoryLoader.java b/src/com/android/documentsui/DirectoryLoader.java
index 458f861..3196396 100644
--- a/src/com/android/documentsui/DirectoryLoader.java
+++ b/src/com/android/documentsui/DirectoryLoader.java
@@ -281,10 +281,11 @@
 
     @Override
     protected void onStartLoading() {
-        if (mResult != null) {
+        boolean isCursorStale = checkIfCursorStale(mResult);
+        if (mResult != null && !isCursorStale) {
             deliverResult(mResult);
         }
-        if (takeContentChanged() || mResult == null) {
+        if (takeContentChanged() || mResult == null || isCursorStale) {
             forceLoad();
         }
     }
@@ -313,4 +314,22 @@
         FileUtils.closeQuietly(mResult);
         mResult = null;
     }
+
+    private boolean checkIfCursorStale(DirectoryResult result) {
+        if (result == null || result.cursor == null || result.cursor.isClosed()) {
+            return true;
+        }
+        Cursor cursor = result.cursor;
+        try {
+            cursor.moveToPosition(-1);
+            for (int pos = 0; pos < cursor.getCount(); ++pos) {
+                if (!cursor.moveToNext()) {
+                    return true;
+                }
+            }
+        } catch (Exception e) {
+            return true;
+        }
+        return false;
+    }
 }
diff --git a/src/com/android/documentsui/MultiRootDocumentsLoader.java b/src/com/android/documentsui/MultiRootDocumentsLoader.java
index 643f122..e7d09bf 100644
--- a/src/com/android/documentsui/MultiRootDocumentsLoader.java
+++ b/src/com/android/documentsui/MultiRootDocumentsLoader.java
@@ -303,10 +303,11 @@
 
     @Override
     protected void onStartLoading() {
-        if (mResult != null) {
+        boolean isCursorStale = checkIfCursorStale(mResult);
+        if (mResult != null && !isCursorStale) {
             deliverResult(mResult);
         }
-        if (takeContentChanged() || mResult == null) {
+        if (takeContentChanged() || mResult == null || isCursorStale) {
             forceLoad();
         }
     }
@@ -456,4 +457,22 @@
             mIsClosed = true;
         }
     }
+
+    private boolean checkIfCursorStale(DirectoryResult result) {
+        if (result == null || result.cursor == null || result.cursor.isClosed()) {
+            return true;
+        }
+        Cursor cursor = result.cursor;
+        try {
+            cursor.moveToPosition(-1);
+            for (int pos = 0; pos < cursor.getCount(); ++pos) {
+                if (!cursor.moveToNext()) {
+                    return true;
+                }
+            }
+        } catch (Exception e) {
+            return true;
+        }
+        return false;
+    }
 }