Focus handling null pointer exception during monkey tests.

- Also fix a bug where the focus is not navigating to the next page when there
isn't an icon within +45 and -45 range of the origin.

b/20294717

Change-Id: I16dac5c6a0463fbc9f56a447abedad18abadde98
diff --git a/src/com/android/launcher3/FocusHelper.java b/src/com/android/launcher3/FocusHelper.java
index 8791c89..32ed98c 100644
--- a/src/com/android/launcher3/FocusHelper.java
+++ b/src/com/android/launcher3/FocusHelper.java
@@ -222,7 +222,7 @@
         Hotseat hotseat = (Hotseat) hotseatLayout.getParent();
 
         Workspace workspace = (Workspace) v.getRootView().findViewById(R.id.workspace);
-        int pageIndex = workspace.getCurrentPage();
+        int pageIndex = workspace.getNextPage();
         int pageCount = workspace.getChildCount();
         int countX = -1;
         int countY = -1;
@@ -231,6 +231,12 @@
                 .getChildAt(iconIndex).getLayoutParams()).cellX;
 
         final CellLayout iconLayout = (CellLayout) workspace.getChildAt(pageIndex);
+        if (iconLayout == null) {
+            // This check is to guard against cases where key strokes rushes in when workspace
+            // child creation/deletion is still in flux. (e.g., during drop or fling
+            // animation.)
+            return consume;
+        }
         final ViewGroup iconParent = iconLayout.getShortcutsAndWidgets();
 
         ViewGroup parent = null;
@@ -364,6 +370,7 @@
                 }
                 int row = FocusLogic.findRow(matrix, iconIndex);
                 parent = getCellLayoutChildrenForIndex(workspace, newPageIndex);
+                workspace.snapToPage(newPageIndex);
                 if (parent != null) {
                     iconLayout = (CellLayout) parent.getParent();
                     matrix = FocusLogic.createSparseMatrix(iconLayout,
@@ -394,6 +401,7 @@
                 if (newIconIndex == FocusLogic.PREVIOUS_PAGE_LEFT_COLUMN) {
                     newPageIndex = pageIndex - 1;
                 }
+                workspace.snapToPage(newPageIndex);
                 row = FocusLogic.findRow(matrix, iconIndex);
                 parent = getCellLayoutChildrenForIndex(workspace, newPageIndex);
                 if (parent != null) {
diff --git a/src/com/android/launcher3/PagedView.java b/src/com/android/launcher3/PagedView.java
index 158a30c..5dc3930 100644
--- a/src/com/android/launcher3/PagedView.java
+++ b/src/com/android/launcher3/PagedView.java
@@ -475,13 +475,14 @@
 
     /**
      * Returns the index of the currently displayed page.
-     *
-     * @return The index of the currently displayed page.
      */
     int getCurrentPage() {
         return mCurrentPage;
     }
 
+    /**
+     * Returns the index of page to be shown immediately afterwards.
+     */
     int getNextPage() {
         return (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
     }