You must check if the cursor pointing to the result of a database operation is empty. If a check on the value returned by moveToFirst is missing, subsequent database read operations can cause your application to crash.
1public static String getDataFromURINonCompliant(Context context, Uri uri) {
2 String[] columns = { "name", "address" };
3 try (Cursor cursor = context.getContentResolver().query(uri, columns, null, null, null)) {
4 // Noncompliant: code does not check if the cursor is empty.
5 cursor.moveToFirst();
6 return cursor.getString(0);
7 }
8}
1public static String getDataFromURICompliant(Context context, Uri uri) {
2 String[] columns = { "name", "address" };
3 try (Cursor cursor = context.getContentResolver().query(uri, columns, null, null, null)) {
4 // Compliant: code handles the case when the cursor is empty.
5 if (!cursor.moveToFirst()) {
6 return null;
7 }
8 return cursor.getString(0);
9 }
10}