From 2f04cea8d22944e5c3fc8ed085237e01f7f90fd8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ra=C3=BAl=20D=C3=ADaz?= Date: Thu, 2 Mar 2017 21:29:32 +0100 Subject: [PATCH] Simplified and intuitive data check for Cursor. Rather than moving to the first element and checking if that was successful to set a flag and return if it failed, it's easier and more intuitive to ask if the cursor is null or empty, and finally, in case it contains information point the cursor to it. PS: As doing the `moveToFirst` is mandatory, I think it's not a bad idea to isolate the call so people know straight away that is not a simple check. --- .../example/android/sunshine/DetailActivity.java | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/S09.05-Solution-MoreDetails/app/src/main/java/com/example/android/sunshine/DetailActivity.java b/S09.05-Solution-MoreDetails/app/src/main/java/com/example/android/sunshine/DetailActivity.java index 413c556bc7..d26185801b 100755 --- a/S09.05-Solution-MoreDetails/app/src/main/java/com/example/android/sunshine/DetailActivity.java +++ b/S09.05-Solution-MoreDetails/app/src/main/java/com/example/android/sunshine/DetailActivity.java @@ -242,23 +242,17 @@ public void onLoadFinished(Loader loader, Cursor data) { /* * Before we bind the data to the UI that will display that data, we need to check the * cursor to make sure we have the results that we are expecting. In order to do that, we - * check to make sure the cursor is not null and then we call moveToFirst on the cursor. - * Although it may not seem obvious at first, moveToFirst will return true if it contains - * a valid first row of data. + * check to make sure the cursor is not null and is not empty. * * If we have valid data, we want to continue on to bind that data to the UI. If we don't * have any data to bind, we just return from this method. */ - boolean cursorHasValidData = false; - if (data != null && data.moveToFirst()) { - /* We have valid data, continue on to bind the data to the UI */ - cursorHasValidData = true; - } - - if (!cursorHasValidData) { + if (data == null || data.getCount() == 0) { /* No data to display, simply return and do nothing */ return; } + /* We have valid data, point the cursor to the first row and continue on to bind the data to the UI */ + data.moveToFirst(); // COMPLETED (26) Display a readable data string /**************** @@ -381,4 +375,4 @@ public void onLoadFinished(Loader loader, Cursor data) { @Override public void onLoaderReset(Loader loader) { } -} \ No newline at end of file +}