Missing check on the value returned by moveToFirst API
MediumYou 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.
Noncompliant example
public static String getDataFromURINonCompliant(Context context, Uri uri) {
String[] columns = { "name", "address" };
try (Cursor cursor = context.getContentResolver().query(uri, columns, null, null, null)) {
// Noncompliant: code does not check if the cursor is empty.
cursor.moveToFirst();
return cursor.getString(0);
}
}
Compliant example
public static String getDataFromURICompliant(Context context, Uri uri) {
String[] columns = { "name", "address" };
try (Cursor cursor = context.getContentResolver().query(uri, columns, null, null, null)) {
// Compliant: code handles the case when the cursor is empty.
if (!cursor.moveToFirst()) {
return null;
}
return cursor.getString(0);
}
}