diff --git a/src/android/support/v7/mms/DefaultApnSettingsLoader.java b/src/android/support/v7/mms/DefaultApnSettingsLoader.java index 0a91e85..d55f5fe 100644 --- a/src/android/support/v7/mms/DefaultApnSettingsLoader.java +++ b/src/android/support/v7/mms/DefaultApnSettingsLoader.java @@ -399,9 +399,7 @@ class DefaultApnSettingsLoader implements ApnSettingsLoader { return; } // MCC/MNC is good, loading/querying APNs from XML - XmlResourceParser xml = null; - try { - xml = mContext.getResources().getXml(R.xml.apns); + try (XmlResourceParser xml = mContext.getResources().getXml(R.xml.apns)) { new ApnsXmlParser(xml, apnValues -> { final String mcc = trimWithNullCheck(apnValues.getAsString(APN_MCC)); final String mnc = trimWithNullCheck(apnValues.getAsString(APN_MNC)); @@ -425,10 +423,6 @@ class DefaultApnSettingsLoader implements ApnSettingsLoader { }).parse(); } catch (final Resources.NotFoundException e) { Log.w(MmsService.TAG, "Can not get apns.xml " + e); - } finally { - if (xml != null) { - xml.close(); - } } } diff --git a/src/android/support/v7/mms/DefaultCarrierConfigValuesLoader.java b/src/android/support/v7/mms/DefaultCarrierConfigValuesLoader.java index f3f263b..b7da089 100644 --- a/src/android/support/v7/mms/DefaultCarrierConfigValuesLoader.java +++ b/src/android/support/v7/mms/DefaultCarrierConfigValuesLoader.java @@ -92,9 +92,7 @@ class DefaultCarrierConfigValuesLoader implements CarrierConfigValuesLoader { private void loadFromResources(final int subId, final Bundle values) { // Get a subscription-dependent context for loading the mms_config.xml final Context subContext = Utils.getSubDepContext(mContext, subId); - XmlResourceParser xml = null; - try { - xml = subContext.getResources().getXml(R.xml.mms_config); + try (XmlResourceParser xml = subContext.getResources().getXml(R.xml.mms_config)) { new CarrierConfigXmlParser(xml, (type, key, value) -> { try { if (KEY_TYPE_INT.equals(type)) { @@ -111,10 +109,6 @@ class DefaultCarrierConfigValuesLoader implements CarrierConfigValuesLoader { }).parse(); } catch (final Resources.NotFoundException e) { Log.w(MmsService.TAG, "Can not get mms_config.xml"); - } finally { - if (xml != null) { - xml.close(); - } } } } diff --git a/src/com/android/messaging/datamodel/BugleDatabaseOperations.java b/src/com/android/messaging/datamodel/BugleDatabaseOperations.java index 2474bb1..9364f0c 100644 --- a/src/com/android/messaging/datamodel/BugleDatabaseOperations.java +++ b/src/com/android/messaging/datamodel/BugleDatabaseOperations.java @@ -251,22 +251,16 @@ public class BugleDatabaseOperations { Assert.isNotMainThread(); String conversationId = null; - Cursor cursor = null; - try { + try (Cursor cursor = dbWrapper.rawQuery("SELECT " + ConversationColumns._ID + + " FROM " + DatabaseHelper.CONVERSATIONS_TABLE + + " WHERE " + ConversationColumns.SMS_THREAD_ID + "=" + threadId, + null)) { // Look for an existing conversation in the db with this thread id - cursor = dbWrapper.rawQuery("SELECT " + ConversationColumns._ID - + " FROM " + DatabaseHelper.CONVERSATIONS_TABLE - + " WHERE " + ConversationColumns.SMS_THREAD_ID + "=" + threadId, - null); if (cursor.moveToFirst()) { Assert.isTrue(cursor.getCount() == 1); conversationId = cursor.getString(0); } - } finally { - if (cursor != null) { - cursor.close(); - } } return conversationId; @@ -285,13 +279,11 @@ public class BugleDatabaseOperations { Assert.isNotMainThread(); long threadId = -1; - Cursor cursor = null; - try { - cursor = dbWrapper.query(DatabaseHelper.CONVERSATIONS_TABLE, - new String[] { ConversationColumns.SMS_THREAD_ID }, - ConversationColumns._ID + " =?", - new String[] { conversationId }, - null, null, null); + try (Cursor cursor = dbWrapper.query(DatabaseHelper.CONVERSATIONS_TABLE, + new String[]{ConversationColumns.SMS_THREAD_ID}, + ConversationColumns._ID + " =?", + new String[]{conversationId}, + null, null, null)) { if (cursor.moveToFirst()) { Assert.isTrue(cursor.getCount() == 1); @@ -299,10 +291,6 @@ public class BugleDatabaseOperations { threadId = cursor.getLong(0); } } - } finally { - if (cursor != null) { - cursor.close(); - } } return threadId; @@ -320,23 +308,17 @@ public class BugleDatabaseOperations { static boolean isBlockedParticipant(final DatabaseWrapper db, final String value, final String column) { - Cursor cursor = null; - try { - cursor = db.query(DatabaseHelper.PARTICIPANTS_TABLE, - new String[] { ParticipantColumns.BLOCKED }, - column + "=? AND " + ParticipantColumns.SUB_ID + "=?", - new String[] { value, - Integer.toString(ParticipantData.OTHER_THAN_SELF_SUB_ID) }, - null, null, null); + try (Cursor cursor = db.query(DatabaseHelper.PARTICIPANTS_TABLE, + new String[]{ParticipantColumns.BLOCKED}, + column + "=? AND " + ParticipantColumns.SUB_ID + "=?", + new String[]{value, + Integer.toString(ParticipantData.OTHER_THAN_SELF_SUB_ID)}, + null, null, null)) { Assert.inRange(cursor.getCount(), 0, 1); if (cursor.moveToFirst()) { return cursor.getInt(0) == 1; } - } finally { - if (cursor != null) { - cursor.close(); - } } return false; // if there's no row, it's not blocked :-) } @@ -524,12 +506,10 @@ public class BugleDatabaseOperations { new String[]{ conversationId }, null, null, null); if (cursor != null) { - try { + try (cursor) { if (cursor.moveToFirst()) { return cursor.getLong(0); } - } finally { - cursor.close(); } } return 0; @@ -675,21 +655,15 @@ public class BugleDatabaseOperations { // Make sure the selfId passed in is valid and active. final String selection = ParticipantColumns._ID + "=? AND " + ParticipantColumns.SIM_SLOT_ID + "<>?"; - Cursor cursor = null; - try { - cursor = dbWrapper.query(DatabaseHelper.PARTICIPANTS_TABLE, - new String[] { ParticipantColumns._ID }, selection, - new String[] { selfId, String.valueOf(ParticipantData.INVALID_SLOT_ID) }, - null, null, null); + try (Cursor cursor = dbWrapper.query(DatabaseHelper.PARTICIPANTS_TABLE, + new String[]{ParticipantColumns._ID}, selection, + new String[]{selfId, String.valueOf(ParticipantData.INVALID_SLOT_ID)}, + null, null, null)) { if (cursor != null && cursor.getCount() > 0) { values.put(ConversationColumns.CURRENT_SELF_ID, selfId); return true; } - } finally { - if (cursor != null) { - cursor.close(); - } } return false; } @@ -700,22 +674,17 @@ public class BugleDatabaseOperations { Assert.isTrue(dbWrapper.getDatabase().inTransaction()); long sortTimestamp = 0L; - Cursor cursor = null; - try { + try (Cursor cursor = dbWrapper.query(DatabaseHelper.MESSAGES_TABLE, + REFRESH_CONVERSATION_MESSAGE_PROJECTION, + MessageColumns.CONVERSATION_ID + "=?", + new String[]{conversationId}, null, null, + MessageColumns.RECEIVED_TIMESTAMP + " DESC", "1" /* limit */)) { // Check to find the latest message in the conversation - cursor = dbWrapper.query(DatabaseHelper.MESSAGES_TABLE, - REFRESH_CONVERSATION_MESSAGE_PROJECTION, - MessageColumns.CONVERSATION_ID + "=?", - new String[]{conversationId}, null, null, - MessageColumns.RECEIVED_TIMESTAMP + " DESC", "1" /* limit */); + /* limit */ if (cursor.moveToFirst()) { sortTimestamp = cursor.getLong(1); } - } finally { - if (cursor != null) { - cursor.close(); - } } @@ -854,21 +823,15 @@ public class BugleDatabaseOperations { public static String getConversationSelfId(final DatabaseWrapper dbWrapper, final String conversationId) { Assert.isNotMainThread(); - Cursor cursor = null; - try { - cursor = dbWrapper.query(DatabaseHelper.CONVERSATIONS_TABLE, - new String[] { ConversationColumns.CURRENT_SELF_ID }, - ConversationColumns._ID + "=?", - new String[] { conversationId }, - null, null, null); + try (Cursor cursor = dbWrapper.query(DatabaseHelper.CONVERSATIONS_TABLE, + new String[]{ConversationColumns.CURRENT_SELF_ID}, + ConversationColumns._ID + "=?", + new String[]{conversationId}, + null, null, null)) { Assert.inRange(cursor.getCount(), 0, 1); if (cursor.moveToFirst()) { return cursor.getString(0); } - } finally { - if (cursor != null) { - cursor.close(); - } } return null; } @@ -903,21 +866,15 @@ public class BugleDatabaseOperations { public static String getSmsServiceCenterForConversation(final DatabaseWrapper dbWrapper, final String conversationId) { Assert.isNotMainThread(); - Cursor cursor = null; - try { - cursor = dbWrapper.query(DatabaseHelper.CONVERSATIONS_TABLE, - new String[] { ConversationColumns.SMS_SERVICE_CENTER }, - ConversationColumns._ID + "=?", - new String[] { conversationId }, - null, null, null); + try (Cursor cursor = dbWrapper.query(DatabaseHelper.CONVERSATIONS_TABLE, + new String[]{ConversationColumns.SMS_SERVICE_CENTER}, + ConversationColumns._ID + "=?", + new String[]{conversationId}, + null, null, null)) { Assert.inRange(cursor.getCount(), 0, 1); if (cursor.moveToFirst()) { return cursor.getString(0); } - } finally { - if (cursor != null) { - cursor.close(); - } } return null; } @@ -927,20 +884,14 @@ public class BugleDatabaseOperations { final String participantId) { Assert.isNotMainThread(); ParticipantData participant = null; - Cursor cursor = null; - try { - cursor = dbWrapper.query(DatabaseHelper.PARTICIPANTS_TABLE, - ParticipantData.ParticipantsQuery.PROJECTION, - ParticipantColumns._ID + " =?", - new String[] { participantId }, null, null, null); + try (Cursor cursor = dbWrapper.query(DatabaseHelper.PARTICIPANTS_TABLE, + ParticipantData.ParticipantsQuery.PROJECTION, + ParticipantColumns._ID + " =?", + new String[]{participantId}, null, null, null)) { Assert.inRange(cursor.getCount(), 0, 1); if (cursor.moveToFirst()) { participant = ParticipantData.getFromCursor(cursor); } - } finally { - if (cursor != null) { - cursor.close(); - } } return participant; @@ -964,24 +915,18 @@ public class BugleDatabaseOperations { Assert.isNotMainThread(); final ArrayList participants = new ArrayList(); - Cursor cursor = null; - try { - cursor = dbWrapper.query(DatabaseHelper.PARTICIPANTS_TABLE, - ParticipantData.ParticipantsQuery.PROJECTION, - ParticipantColumns._ID + " IN ( " + "SELECT " - + ConversationParticipantsColumns.PARTICIPANT_ID + " AS " - + ParticipantColumns._ID - + " FROM " + DatabaseHelper.CONVERSATION_PARTICIPANTS_TABLE - + " WHERE " + ConversationParticipantsColumns.CONVERSATION_ID + " =? )", - new String[] { conversationId }, null, null, null); + try (Cursor cursor = dbWrapper.query(DatabaseHelper.PARTICIPANTS_TABLE, + ParticipantData.ParticipantsQuery.PROJECTION, + ParticipantColumns._ID + " IN ( " + "SELECT " + + ConversationParticipantsColumns.PARTICIPANT_ID + " AS " + + ParticipantColumns._ID + + " FROM " + DatabaseHelper.CONVERSATION_PARTICIPANTS_TABLE + + " WHERE " + ConversationParticipantsColumns.CONVERSATION_ID + " =? )", + new String[]{conversationId}, null, null, null)) { while (cursor.moveToNext()) { participants.add(ParticipantData.getFromCursor(cursor)); } - } finally { - if (cursor != null) { - cursor.close(); - } } return participants; @@ -1001,19 +946,13 @@ public class BugleDatabaseOperations { static MessagePartData readMessagePartData(final DatabaseWrapper dbWrapper, final String partId) { MessagePartData messagePartData = null; - Cursor cursor = null; - try { - cursor = dbWrapper.query(DatabaseHelper.PARTS_TABLE, - MessagePartData.getProjection(), PartColumns._ID + "=?", - new String[] { partId }, null, null, null); + try (Cursor cursor = dbWrapper.query(DatabaseHelper.PARTS_TABLE, + MessagePartData.getProjection(), PartColumns._ID + "=?", + new String[]{partId}, null, null, null)) { Assert.inRange(cursor.getCount(), 0, 1); if (cursor.moveToFirst()) { messagePartData = MessagePartData.createFromCursor(cursor); } - } finally { - if (cursor != null) { - cursor.close(); - } } return messagePartData; } @@ -1023,20 +962,14 @@ public class BugleDatabaseOperations { final Uri smsMessageUri) { Assert.isNotMainThread(); MessageData message = null; - Cursor cursor = null; - try { - cursor = dbWrapper.query(DatabaseHelper.MESSAGES_TABLE, - MessageData.getProjection(), MessageColumns.SMS_MESSAGE_URI + "=?", - new String[] { smsMessageUri.toString() }, null, null, null); + try (Cursor cursor = dbWrapper.query(DatabaseHelper.MESSAGES_TABLE, + MessageData.getProjection(), MessageColumns.SMS_MESSAGE_URI + "=?", + new String[]{smsMessageUri.toString()}, null, null, null)) { Assert.inRange(cursor.getCount(), 0, 1); if (cursor.moveToFirst()) { message = new MessageData(); message.bind(cursor); } - } finally { - if (cursor != null) { - cursor.close(); - } } return message; } @@ -1046,20 +979,14 @@ public class BugleDatabaseOperations { final String messageId) { Assert.isNotMainThread(); MessageData message = null; - Cursor cursor = null; - try { - cursor = dbWrapper.query(DatabaseHelper.MESSAGES_TABLE, - MessageData.getProjection(), MessageColumns._ID + "=?", - new String[] { messageId }, null, null, null); + try (Cursor cursor = dbWrapper.query(DatabaseHelper.MESSAGES_TABLE, + MessageData.getProjection(), MessageColumns._ID + "=?", + new String[]{messageId}, null, null, null)) { Assert.inRange(cursor.getCount(), 0, 1); if (cursor.moveToFirst()) { message = new MessageData(); message.bind(cursor); } - } finally { - if (cursor != null) { - cursor.close(); - } } return message; } @@ -1074,11 +1001,9 @@ public class BugleDatabaseOperations { final MessageData message, final boolean checkAttachmentFilesExist) { final ContentResolver contentResolver = Factory.get().getApplicationContext().getContentResolver(); - Cursor cursor = null; - try { - cursor = dbWrapper.query(DatabaseHelper.PARTS_TABLE, - MessagePartData.getProjection(), PartColumns.MESSAGE_ID + "=?", - new String[] { message.getMessageId() }, null, null, null); + try (Cursor cursor = dbWrapper.query(DatabaseHelper.PARTS_TABLE, + MessagePartData.getProjection(), PartColumns.MESSAGE_ID + "=?", + new String[]{message.getMessageId()}, null, null, null)) { while (cursor.moveToNext()) { final MessagePartData messagePartData = MessagePartData.createFromCursor(cursor); if (checkAttachmentFilesExist && messagePartData.isAttachment() && @@ -1104,10 +1029,6 @@ public class BugleDatabaseOperations { message.addPart(messagePartData); } } - } finally { - if (cursor != null) { - cursor.close(); - } } } @@ -1262,31 +1183,26 @@ public class BugleDatabaseOperations { final String conversationId) { Assert.isNotMainThread(); Assert.isTrue(dbWrapper.getDatabase().inTransaction()); - Cursor cursor = null; - try { + try (Cursor cursor = dbWrapper.query(DatabaseHelper.MESSAGES_TABLE, + REFRESH_CONVERSATION_MESSAGE_PROJECTION, + MessageColumns.CONVERSATION_ID + "=? AND " + + MessageColumns.STATUS + "!=" + MessageData.BUGLE_STATUS_OUTGOING_DRAFT, + new String[]{conversationId}, null, null, + MessageColumns.RECEIVED_TIMESTAMP + " DESC", "1" /* limit */)) { // TODO: The refreshConversationMetadataInTransaction method below uses this // same query; maybe they should share this logic? // Check to see if there are any (non-draft) messages in the conversation - cursor = dbWrapper.query(DatabaseHelper.MESSAGES_TABLE, - REFRESH_CONVERSATION_MESSAGE_PROJECTION, - MessageColumns.CONVERSATION_ID + "=? AND " + - MessageColumns.STATUS + "!=" + MessageData.BUGLE_STATUS_OUTGOING_DRAFT, - new String[] { conversationId }, null, null, - MessageColumns.RECEIVED_TIMESTAMP + " DESC", "1" /* limit */); + /* limit */ if (cursor.getCount() == 0) { dbWrapper.delete(DatabaseHelper.CONVERSATIONS_TABLE, - ConversationColumns._ID + "=?", new String[] { conversationId }); + ConversationColumns._ID + "=?", new String[]{conversationId}); LogUtil.i(TAG, "BugleDatabaseOperations: Deleted empty conversation " + conversationId); return true; } else { return false; } - } finally { - if (cursor != null) { - cursor.close(); - } } } @@ -1306,15 +1222,14 @@ public class BugleDatabaseOperations { boolean keepArchived) { Assert.isNotMainThread(); Assert.isTrue(dbWrapper.getDatabase().inTransaction()); - Cursor cursor = null; - try { + try (Cursor cursor = dbWrapper.query(DatabaseHelper.MESSAGES_TABLE, + REFRESH_CONVERSATION_MESSAGE_PROJECTION, + MessageColumns.CONVERSATION_ID + "=? AND " + + MessageColumns.STATUS + "!=" + MessageData.BUGLE_STATUS_OUTGOING_DRAFT, + new String[]{conversationId}, null, null, + MessageColumns.RECEIVED_TIMESTAMP + " DESC", "1" /* limit */)) { // Check to see if there are any (non-draft) messages in the conversation - cursor = dbWrapper.query(DatabaseHelper.MESSAGES_TABLE, - REFRESH_CONVERSATION_MESSAGE_PROJECTION, - MessageColumns.CONVERSATION_ID + "=? AND " + - MessageColumns.STATUS + "!=" + MessageData.BUGLE_STATUS_OUTGOING_DRAFT, - new String[] { conversationId }, null, null, - MessageColumns.RECEIVED_TIMESTAMP + " DESC", "1" /* limit */); + /* limit */ if (cursor.moveToFirst()) { // Refresh latest message in conversation @@ -1326,10 +1241,6 @@ public class BugleDatabaseOperations { latestMessageId, latestMessageTimestamp, senderBlocked || keepArchived, shouldAutoSwitchSelfId); } - } finally { - if (cursor != null) { - cursor.close(); - } } } @@ -1351,21 +1262,15 @@ public class BugleDatabaseOperations { if (!TextUtils.isEmpty(messageId)) { refresh = false; // Look for an existing conversation in the db with this conversation id - Cursor cursor = null; - try { - cursor = dbWrapper.query(DatabaseHelper.CONVERSATIONS_TABLE, - new String[] { ConversationColumns.LATEST_MESSAGE_ID }, - ConversationColumns._ID + "=?", - new String[] { conversationId }, - null, null, null); + try (Cursor cursor = dbWrapper.query(DatabaseHelper.CONVERSATIONS_TABLE, + new String[]{ConversationColumns.LATEST_MESSAGE_ID}, + ConversationColumns._ID + "=?", + new String[]{conversationId}, + null, null, null)) { Assert.inRange(cursor.getCount(), 0, 1); if (cursor.moveToFirst()) { refresh = TextUtils.equals(cursor.getString(0), messageId); } - } finally { - if (cursor != null) { - cursor.close(); - } } } if (refresh) { @@ -1457,18 +1362,13 @@ public class BugleDatabaseOperations { static boolean getConversationExists(final DatabaseWrapper dbWrapper, final String conversationId) { // Look for an existing conversation in the db with this conversation id - Cursor cursor = null; - try { - cursor = dbWrapper.query(DatabaseHelper.CONVERSATIONS_TABLE, - new String[] { /* No projection */}, - ConversationColumns._ID + "=?", - new String[] { conversationId }, - null, null, null); + try (Cursor cursor = dbWrapper.query(DatabaseHelper.CONVERSATIONS_TABLE, + new String[]{ /* No projection */}, + ConversationColumns._ID + "=?", + new String[]{conversationId}, + null, null, null)) { + /* No projection */ return cursor.getCount() == 1; - } finally { - if (cursor != null) { - cursor.close(); - } } } @@ -1578,16 +1478,14 @@ public class BugleDatabaseOperations { final String conversationId, final String conversationSelfId) { Assert.isNotMainThread(); MessageData message = null; - Cursor cursor = null; dbWrapper.beginTransaction(); - try { - cursor = dbWrapper.query(DatabaseHelper.MESSAGES_TABLE, - MessageData.getProjection(), - MessageColumns.STATUS + "=? AND " + MessageColumns.CONVERSATION_ID + "=?", - new String[] { + try (Cursor cursor = dbWrapper.query(DatabaseHelper.MESSAGES_TABLE, + MessageData.getProjection(), + MessageColumns.STATUS + "=? AND " + MessageColumns.CONVERSATION_ID + "=?", + new String[]{ Integer.toString(MessageData.BUGLE_STATUS_OUTGOING_DRAFT), conversationId - }, null, null, null); + }, null, null, null)) { Assert.inRange(cursor.getCount(), 0, 1); if (cursor.moveToFirst()) { message = new MessageData(); @@ -1603,9 +1501,6 @@ public class BugleDatabaseOperations { dbWrapper.setTransactionSuccessful(); } finally { dbWrapper.endTransaction(); - if (cursor != null) { - cursor.close(); - } } return message; } @@ -1770,20 +1665,14 @@ public class BugleDatabaseOperations { public static String getConversationFromOtherParticipantDestination( final DatabaseWrapper db, final String otherDestination) { Assert.isNotMainThread(); - Cursor cursor = null; - try { - cursor = db.query(DatabaseHelper.CONVERSATIONS_TABLE, - new String[] { ConversationColumns._ID }, - ConversationColumns.OTHER_PARTICIPANT_NORMALIZED_DESTINATION + "=?", - new String[] { otherDestination }, null, null, null); + try (Cursor cursor = db.query(DatabaseHelper.CONVERSATIONS_TABLE, + new String[]{ConversationColumns._ID}, + ConversationColumns.OTHER_PARTICIPANT_NORMALIZED_DESTINATION + "=?", + new String[]{otherDestination}, null, null, null)) { Assert.inRange(cursor.getCount(), 0, 1); if (cursor.moveToFirst()) { return cursor.getString(0); } - } finally { - if (cursor != null) { - cursor.close(); - } } return null; } diff --git a/src/com/android/messaging/datamodel/MessageNotificationState.java b/src/com/android/messaging/datamodel/MessageNotificationState.java index 1f04bc5..2bced65 100644 --- a/src/com/android/messaging/datamodel/MessageNotificationState.java +++ b/src/com/android/messaging/datamodel/MessageNotificationState.java @@ -1146,15 +1146,13 @@ public abstract class MessageNotificationState extends NotificationState { public static void checkFailedMessages() { final DatabaseWrapper db = DataModel.get().getDatabase(); - final Cursor messageDataCursor = db.query(DatabaseHelper.MESSAGES_TABLE, - MessageData.getProjection(), - FailedMessageQuery.FAILED_MESSAGES_WHERE_CLAUSE, - null /*selectionArgs*/, - null /*groupBy*/, - null /*having*/, - FailedMessageQuery.FAILED_ORDER_BY); - - try { + try (Cursor messageDataCursor = db.query(DatabaseHelper.MESSAGES_TABLE, + MessageData.getProjection(), + FailedMessageQuery.FAILED_MESSAGES_WHERE_CLAUSE, + null /*selectionArgs*/, + null /*groupBy*/, + null /*having*/, + FailedMessageQuery.FAILED_ORDER_BY)) { final Context context = Factory.get().getApplicationContext(); final Resources resources = context.getResources(); final NotificationManagerCompat notificationManager = @@ -1192,8 +1190,8 @@ public abstract class MessageNotificationState extends NotificationState { LogUtil.d(TAG, "Found " + failedMessages.size() + " failed messages"); } if (failedMessages.size() > 0) { - final NotificationCompat.Builder builder = - new NotificationCompat.Builder(context, + final Builder builder = + new Builder(context, NotificationsUtil.DEFAULT_CHANNEL_ID); CharSequence line1; @@ -1204,7 +1202,7 @@ public abstract class MessageNotificationState extends NotificationState { if (failedMessages.size() == 1) { messageDataCursor.moveToPosition(cursorPosition); messageData.bind(messageDataCursor); - final String conversationId = messageData.getConversationId(); + final String conversationId = messageData.getConversationId(); // We have a single conversation, go directly to that conversation. destinationIntent = UIIntents.get() @@ -1235,7 +1233,7 @@ public abstract class MessageNotificationState extends NotificationState { // We have notifications for multiple conversation, go to the conversation // list. destinationIntent = UIIntents.get() - .getPendingIntentForConversationListActivity(context); + .getPendingIntentForConversationListActivity(context); int line1StringId; int line2PluralsId; @@ -1266,13 +1264,13 @@ public abstract class MessageNotificationState extends NotificationState { 0); builder - .setContentTitle(line1) - .setTicker(line1) - .setWhen(when > 0 ? when : System.currentTimeMillis()) - .setSmallIcon(R.drawable.ic_failed_light) - .setDeleteIntent(pendingIntentForDelete) - .setContentIntent(destinationIntent) - .setSound(UriUtil.getUriForResourceId(context, R.raw.message_failure)); + .setContentTitle(line1) + .setTicker(line1) + .setWhen(when > 0 ? when : System.currentTimeMillis()) + .setSmallIcon(R.drawable.ic_failed_light) + .setDeleteIntent(pendingIntentForDelete) + .setContentIntent(destinationIntent) + .setSound(UriUtil.getUriForResourceId(context, R.raw.message_failure)); if (isRichContent && !TextUtils.isEmpty(line2)) { final NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(builder); @@ -1298,10 +1296,6 @@ public abstract class MessageNotificationState extends NotificationState { PendingIntentConstants.MSG_SEND_ERROR); } } - } finally { - if (messageDataCursor != null) { - messageDataCursor.close(); - } } } } diff --git a/src/com/android/messaging/datamodel/ParticipantRefresh.java b/src/com/android/messaging/datamodel/ParticipantRefresh.java index 002e10d..60a0d05 100644 --- a/src/com/android/messaging/datamodel/ParticipantRefresh.java +++ b/src/com/android/messaging/datamodel/ParticipantRefresh.java @@ -308,11 +308,9 @@ public class ParticipantRefresh { final DatabaseWrapper db = DataModel.get().getDatabase(); final HashSet existingSubIds = new HashSet(); - Cursor cursor = null; - try { - cursor = db.query(DatabaseHelper.PARTICIPANTS_TABLE, - ParticipantsQuery.PROJECTION, - SELF_PARTICIPANTS_CLAUSE, null, null, null, null); + try (Cursor cursor = db.query(DatabaseHelper.PARTICIPANTS_TABLE, + ParticipantsQuery.PROJECTION, + SELF_PARTICIPANTS_CLAUSE, null, null, null, null)) { if (cursor != null) { while (cursor.moveToNext()) { @@ -320,10 +318,6 @@ public class ParticipantRefresh { existingSubIds.add(subId); } } - } finally { - if (cursor != null) { - cursor.close(); - } } return existingSubIds; } @@ -445,9 +439,7 @@ public class ParticipantRefresh { // For self participant, try getting name/avatar from self profile in CP2 first. // TODO: in case of multi-sim, profile would not be able to be used for // different numbers. Need to figure out that. - Cursor selfCursor = null; - try { - selfCursor = ContactUtil.getSelf(db.getContext()).performSynchronousQuery(); + try (Cursor selfCursor = ContactUtil.getSelf(db.getContext()).performSynchronousQuery()) { if (selfCursor != null && selfCursor.getCount() > 0) { selfCursor.moveToNext(); final long selfContactId = selfCursor.getLong(ContactUtil.INDEX_CONTACT_ID); @@ -467,10 +459,6 @@ public class ParticipantRefresh { // However, we need to at least log the exception so we know something was wrong. LogUtil.e(LogUtil.BUGLE_DATAMODEL_TAG, "Participant refresh: failed to refresh " + "participant. exception=" + exception); - } finally { - if (selfCursor != null) { - selfCursor.close(); - } } return changed; } @@ -619,12 +607,10 @@ public class ParticipantRefresh { final String selection = ParticipantColumns.SIM_SLOT_ID + "=? AND " + SELF_PARTICIPANTS_CLAUSE; - Cursor cursor = null; - try { - cursor = db.query(DatabaseHelper.PARTICIPANTS_TABLE, - new String[] { ParticipantColumns._ID }, - selection, new String[] { String.valueOf(ParticipantData.INVALID_SLOT_ID) }, - null, null, null); + try (Cursor cursor = db.query(DatabaseHelper.PARTICIPANTS_TABLE, + new String[]{ParticipantColumns._ID}, + selection, new String[]{String.valueOf(ParticipantData.INVALID_SLOT_ID)}, + null, null, null)) { if (cursor != null) { while (cursor.moveToNext()) { @@ -632,10 +618,6 @@ public class ParticipantRefresh { inactiveSelf.add(participantId); } } - } finally { - if (cursor != null) { - cursor.close(); - } } return inactiveSelf; diff --git a/src/com/android/messaging/datamodel/action/DeleteConversationAction.java b/src/com/android/messaging/datamodel/action/DeleteConversationAction.java index 7113e4d..69d12e1 100644 --- a/src/com/android/messaging/datamodel/action/DeleteConversationAction.java +++ b/src/com/android/messaging/datamodel/action/DeleteConversationAction.java @@ -148,13 +148,11 @@ public class DeleteConversationAction extends Action implements Parcelable { Assert.notNull(conversationId); final List messageUris = new ArrayList<>(); - Cursor cursor = null; - try { - cursor = db.query(DatabaseHelper.MESSAGES_TABLE, - new String[] { MessageColumns.SMS_MESSAGE_URI }, - MessageColumns.CONVERSATION_ID + "=?", - new String[] { conversationId }, - null, null, null); + try (Cursor cursor = db.query(DatabaseHelper.MESSAGES_TABLE, + new String[]{MessageColumns.SMS_MESSAGE_URI}, + MessageColumns.CONVERSATION_ID + "=?", + new String[]{conversationId}, + null, null, null)) { while (cursor.moveToNext()) { String messageUri = cursor.getString(0); try { @@ -164,10 +162,6 @@ public class DeleteConversationAction extends Action implements Parcelable { + messageUri); } } - } finally { - if (cursor != null) { - cursor.close(); - } } for (Uri messageUri : messageUris) { int count = MmsUtils.deleteMessage(messageUri); diff --git a/src/com/android/messaging/datamodel/action/SyncMessageBatch.java b/src/com/android/messaging/datamodel/action/SyncMessageBatch.java index a623666..20c03fc 100644 --- a/src/com/android/messaging/datamodel/action/SyncMessageBatch.java +++ b/src/com/android/messaging/datamodel/action/SyncMessageBatch.java @@ -1,5 +1,6 @@ /* * Copyright (C) 2015 The Android Open Source Project + * Copyright (C) 2024 The LineageOS Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -298,21 +299,15 @@ class SyncMessageBatch { // with those details. String foundConversationId = null; - Cursor cursor = null; - try { + try (Cursor cursor = db.rawQuery("SELECT " + ConversationColumns._ID + + " FROM " + DatabaseHelper.CONVERSATIONS_TABLE + + " WHERE " + ConversationColumns._ID + "=" + conversationId, + null)) { // Look for an existing conversation in the db with the conversation id - cursor = db.rawQuery("SELECT " + ConversationColumns._ID - + " FROM " + DatabaseHelper.CONVERSATIONS_TABLE - + " WHERE " + ConversationColumns._ID + "=" + conversationId, - null); if (cursor != null && cursor.moveToFirst()) { Assert.isTrue(cursor.getCount() == 1); foundConversationId = cursor.getString(0); } - } finally { - if (cursor != null) { - cursor.close(); - } } ParticipantData foundSelfParticipant = diff --git a/src/com/android/messaging/datamodel/data/ConversationListItemData.java b/src/com/android/messaging/datamodel/data/ConversationListItemData.java index 4999282..d426744 100644 --- a/src/com/android/messaging/datamodel/data/ConversationListItemData.java +++ b/src/com/android/messaging/datamodel/data/ConversationListItemData.java @@ -466,23 +466,17 @@ public class ConversationListItemData { ConversationListItemData conversation = null; // Look for an existing conversation in the db with this conversation id - Cursor cursor = null; - try { + try (Cursor cursor = dbWrapper.query(getConversationListView(), + PROJECTION, + ConversationColumns._ID + "=?", + new String[]{conversationId}, + null, null, null)) { // TODO: Should we be able to read a row from just the conversation table? - cursor = dbWrapper.query(getConversationListView(), - PROJECTION, - ConversationColumns._ID + "=?", - new String[] { conversationId }, - null, null, null); Assert.inRange(cursor.getCount(), 0, 1); if (cursor.moveToFirst()) { conversation = new ConversationListItemData(); conversation.bind(cursor); } - } finally { - if (cursor != null) { - cursor.close(); - } } return conversation; diff --git a/src/com/android/messaging/datamodel/data/ParticipantData.java b/src/com/android/messaging/datamodel/data/ParticipantData.java index 239f382..6a7690e 100644 --- a/src/com/android/messaging/datamodel/data/ParticipantData.java +++ b/src/com/android/messaging/datamodel/data/ParticipantData.java @@ -152,22 +152,16 @@ public class ParticipantData implements Parcelable { public static ParticipantData getFromId(final DatabaseWrapper dbWrapper, final String participantId) { - Cursor cursor = null; - try { - cursor = dbWrapper.query(DatabaseHelper.PARTICIPANTS_TABLE, - ParticipantsQuery.PROJECTION, - ParticipantColumns._ID + " =?", - new String[] { participantId }, null, null, null); + try (Cursor cursor = dbWrapper.query(DatabaseHelper.PARTICIPANTS_TABLE, + ParticipantsQuery.PROJECTION, + ParticipantColumns._ID + " =?", + new String[]{participantId}, null, null, null)) { if (cursor.moveToFirst()) { return ParticipantData.getFromCursor(cursor); } else { return null; } - } finally { - if (cursor != null) { - cursor.close(); - } } } diff --git a/src/com/android/messaging/datamodel/media/ImageRequest.java b/src/com/android/messaging/datamodel/media/ImageRequest.java index ab8880d..3340797 100644 --- a/src/com/android/messaging/datamodel/media/ImageRequest.java +++ b/src/com/android/messaging/datamodel/media/ImageRequest.java @@ -1,5 +1,6 @@ /* * Copyright (C) 2015 The Android Open Source Project + * Copyright (C) 2024 The LineageOS Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -155,7 +156,7 @@ public abstract class ImageRequest if (unknownSize) { final InputStream inputStream = getInputStreamForResource(); if (inputStream != null) { - try { + try (inputStream) { options.inJustDecodeBounds = true; BitmapFactory.decodeStream(inputStream, null, options); // This is called when dimensions of image were unknown to allow db update @@ -164,8 +165,6 @@ public abstract class ImageRequest } else { mDescriptor.updateSourceDimensions(options.outWidth, options.outHeight); } - } finally { - inputStream.close(); } } else { throw new FileNotFoundException(); diff --git a/src/com/android/messaging/datamodel/media/VCardRequest.java b/src/com/android/messaging/datamodel/media/VCardRequest.java index d6e992c..62d78ac 100644 --- a/src/com/android/messaging/datamodel/media/VCardRequest.java +++ b/src/com/android/messaging/datamodel/media/VCardRequest.java @@ -1,5 +1,6 @@ /* * Copyright (C) 2015 The Android Open Source Project + * Copyright (C) 2024 The LineageOS Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -265,19 +266,14 @@ public class VCardRequest implements MediaRequest { for (final VCardEntry.PhotoData photo : photos) { final byte[] photoBytes = photo.getBytes(); if (photoBytes != null) { - final InputStream inputStream = new ByteArrayInputStream(photoBytes); - try { + try (InputStream inputStream = new ByteArrayInputStream(photoBytes)) { avatarUri = UriUtil.persistContentToScratchSpace(inputStream); if (avatarUri != null) { // Just load the first avatar and be done. Want more? wait for V2. break; } - } finally { - try { - inputStream.close(); - } catch (final IOException e) { - // Do nothing. - } + } catch (IOException e) { + // Do nothing. } } } diff --git a/src/com/android/messaging/mmslib/pdu/PduPersister.java b/src/com/android/messaging/mmslib/pdu/PduPersister.java index 933bd37..19e2e0f 100644 --- a/src/com/android/messaging/mmslib/pdu/PduPersister.java +++ b/src/com/android/messaging/mmslib/pdu/PduPersister.java @@ -1026,10 +1026,8 @@ public class PduPersister { } else if (scheme.equals(ContentResolver.SCHEME_CONTENT)) { final String[] projection = new String[] {MediaStore.MediaColumns.DATA}; - Cursor cursor = null; - try { - cursor = context.getContentResolver().query(uri, projection, null, - null, null); + try (Cursor cursor = context.getContentResolver().query(uri, projection, null, + null, null)) { if (null == cursor || 0 == cursor.getCount() || !cursor.moveToFirst()) { throw new IllegalArgumentException("Given Uri could not be found" + " in media store"); @@ -1040,10 +1038,6 @@ public class PduPersister { } catch (final SQLiteException e) { throw new IllegalArgumentException("Given Uri is not formatted in a way " + "so that it can be found in media store."); - } finally { - if (null != cursor) { - cursor.close(); - } } } else { throw new IllegalArgumentException("Given Uri scheme is not supported"); diff --git a/src/com/android/messaging/sms/ApnDatabase.java b/src/com/android/messaging/sms/ApnDatabase.java index 6be2bf7..241831d 100644 --- a/src/com/android/messaging/sms/ApnDatabase.java +++ b/src/com/android/messaging/sms/ApnDatabase.java @@ -184,12 +184,10 @@ public class ApnDatabase extends SQLiteOpenHelper { * @return The list of user changed apns */ public static List loadUserDataFromOldTable(final SQLiteDatabase db) { - Cursor cursor = null; - try { - cursor = db.query(APN_TABLE, - APN_FULL_PROJECTION, CURRENT_SELECTION, - null/*selectionArgs*/, - null/*groupBy*/, null/*having*/, null/*orderBy*/); + try (Cursor cursor = db.query(APN_TABLE, + APN_FULL_PROJECTION, CURRENT_SELECTION, + null/*selectionArgs*/, + null/*groupBy*/, null/*having*/, null/*orderBy*/)) { if (cursor != null) { final List result = Lists.newArrayList(); while (cursor.moveToNext()) { @@ -202,10 +200,6 @@ public class ApnDatabase extends SQLiteOpenHelper { } } catch (final SQLiteException e) { LogUtil.w(TAG, "ApnDatabase.loadUserDataFromOldTable: no old user data: " + e, e); - } finally { - if (cursor != null) { - cursor.close(); - } } return null; } @@ -243,13 +237,14 @@ public class ApnDatabase extends SQLiteOpenHelper { } } } - Cursor cursor = null; - try { - cursor = db.query(APN_TABLE, - ID_PROJECTION, - selectionBuilder.toString(), - selectionArgs.toArray(new String[0]), - null/*groupBy*/, null/*having*/, null/*orderBy*/); + try (Cursor cursor = db.query(APN_TABLE, + ID_PROJECTION, + selectionBuilder.toString(), + selectionArgs.toArray(new String[0]), + null/*groupBy*/, null/*having*/, null/*orderBy*/)) { + /*groupBy*/ + /*having*/ + /*orderBy*/ if (cursor != null && cursor.moveToFirst()) { db.update(APN_TABLE, row, ID_SELECTION, new String[]{cursor.getString(0)}); } else { @@ -263,10 +258,6 @@ public class ApnDatabase extends SQLiteOpenHelper { } } catch (final SQLiteException e) { LogUtil.e(TAG, "ApnDatabase.saveUserDataFromOldTable: query error " + e, e); - } finally { - if (cursor != null) { - cursor.close(); - } } } } diff --git a/src/com/android/messaging/sms/BugleApnSettingsLoader.java b/src/com/android/messaging/sms/BugleApnSettingsLoader.java index 73ee8b8..79aa68b 100644 --- a/src/com/android/messaging/sms/BugleApnSettingsLoader.java +++ b/src/com/android/messaging/sms/BugleApnSettingsLoader.java @@ -601,18 +601,12 @@ public class BugleApnSettingsLoader implements ApnSettingsLoader { */ public static String getFirstTryApn(final SQLiteDatabase database, final String mccMnc) { String key = null; - Cursor cursor = null; - try { - cursor = queryLocalDatabase(database, mccMnc, null/*apnName*/); + try (Cursor cursor = queryLocalDatabase(database, mccMnc, null/*apnName*/)) { if (cursor.moveToFirst()) { key = cursor.getString(ApnDatabase.COLUMN_ID); } } catch (final Exception e) { // Nothing to do - } finally { - if (cursor != null) { - cursor.close(); - } } return key; } diff --git a/src/com/android/messaging/sms/BugleCarrierConfigValuesLoader.java b/src/com/android/messaging/sms/BugleCarrierConfigValuesLoader.java index a333849..2c75349 100644 --- a/src/com/android/messaging/sms/BugleCarrierConfigValuesLoader.java +++ b/src/com/android/messaging/sms/BugleCarrierConfigValuesLoader.java @@ -125,19 +125,13 @@ public class BugleCarrierConfigValuesLoader implements CarrierConfigValuesLoader // Get a subscription-dependent context for loading the mms_config.xml final Context subContext = getSubDepContext(mContext, subId); // Load and parse the XML - XmlResourceParser parser = null; - try { - parser = subContext.getResources().getXml(R.xml.mms_config); + try (XmlResourceParser parser = subContext.getResources().getXml(R.xml.mms_config)) { final ApnsXmlProcessor processor = ApnsXmlProcessor.get(parser); processor.setMmsConfigHandler((mccMnc, key, value, type) -> update(values, type, key, value)); processor.process(); } catch (final Resources.NotFoundException e) { LogUtil.w(LogUtil.BUGLE_TAG, "Can not find mms_config.xml"); - } finally { - if (parser != null) { - parser.close(); - } } } diff --git a/src/com/android/messaging/sms/MmsSmsUtils.java b/src/com/android/messaging/sms/MmsSmsUtils.java index 7719359..ecee84a 100644 --- a/src/com/android/messaging/sms/MmsSmsUtils.java +++ b/src/com/android/messaging/sms/MmsSmsUtils.java @@ -1,5 +1,6 @@ /* * Copyright (C) 2015 The Android Open Source Project + * Copyright (C) 2024 The LineageOS Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -196,15 +197,13 @@ public class MmsSmsUtils { final Cursor cursor = SqliteWrapper.query(context, context.getContentResolver(), uri, ID_PROJECTION, null, null, null); if (cursor != null) { - try { + try (cursor) { if (cursor.moveToFirst()) { return cursor.getLong(0); } else { LogUtil.e(LogUtil.BUGLE_DATAMODEL_TAG, "getOrCreateThreadId returned no rows!"); } - } finally { - cursor.close(); } } diff --git a/src/com/android/messaging/sms/MmsUtils.java b/src/com/android/messaging/sms/MmsUtils.java index ad08282..eb155f7 100644 --- a/src/com/android/messaging/sms/MmsUtils.java +++ b/src/com/android/messaging/sms/MmsUtils.java @@ -748,14 +748,12 @@ public class MmsUtils { ALL_THREADS_URI, RECIPIENTS_PROJECTION, "_id=?", new String[] { String.valueOf(threadId) }, null); if (thread != null) { - try { + try (thread) { if (thread.moveToFirst()) { // recipientIds will be a space-separated list of ids into the // canonical addresses table. return thread.getString(RECIPIENT_IDS); } - } finally { - thread.close(); } } return null; @@ -1520,18 +1518,12 @@ public class MmsUtils { final SQLiteDatabase database = ApnDatabase.getApnDatabase().getWritableDatabase(); // Do we already have the table? - Cursor cursor = null; - try { - cursor = database.query(ApnDatabase.APN_TABLE, - ApnDatabase.APN_PROJECTION, - null, null, null, null, null, null); + try (Cursor cursor = database.query(ApnDatabase.APN_TABLE, + ApnDatabase.APN_PROJECTION, + null, null, null, null, null, null)) { } catch (final Exception e) { // Apparently there's no table, create it now. ApnDatabase.forceBuildAndLoadApnTables(); - } finally { - if (cursor != null) { - cursor.close(); - } } } sUseSystemApn = turnOn; @@ -1626,12 +1618,10 @@ public class MmsUtils { null/*selectionArgs*/, null/*sortOrder*/); if (cursor != null) { - try { + try (cursor) { if (cursor.moveToFirst()) { return DatabaseMessages.MmsAddr.get(cursor); } - } finally { - cursor.close(); } } return null; @@ -2033,12 +2023,10 @@ public class MmsUtils { new String(rawTransactionId) }; - Cursor cursor = null; - try { - cursor = SqliteWrapper.query( - context, context.getContentResolver(), - Mms.CONTENT_URI, new String[] { Mms._ID }, - selection, selectionArgs, null); + try (Cursor cursor = SqliteWrapper.query( + context, context.getContentResolver(), + Mms.CONTENT_URI, new String[]{Mms._ID}, + selection, selectionArgs, null)) { final int dupCount = cursor.getCount(); if (dupCount > 0) { // We already received the same notification before. @@ -2052,8 +2040,6 @@ public class MmsUtils { } } catch (final SQLiteException e) { LogUtil.e(TAG, "query failure: " + e, e); - } finally { - cursor.close(); } } return null; @@ -2503,12 +2489,9 @@ public class MmsUtils { if (dumpFile != null) { try { final FileOutputStream fos = new FileOutputStream(dumpFile); - final BufferedOutputStream bos = new BufferedOutputStream(fos); - try { + try (BufferedOutputStream bos = new BufferedOutputStream(fos)) { bos.write(rawPdu); bos.flush(); - } finally { - bos.close(); } DebugUtils.ensureReadable(dumpFile); } catch (final IOException e) { diff --git a/src/com/android/messaging/ui/contact/ContactRecipientAdapter.java b/src/com/android/messaging/ui/contact/ContactRecipientAdapter.java index e43cf4e..1429a3d 100644 --- a/src/com/android/messaging/ui/contact/ContactRecipientAdapter.java +++ b/src/com/android/messaging/ui/contact/ContactRecipientAdapter.java @@ -166,7 +166,7 @@ public final class ContactRecipientAdapter extends BaseRecipientAdapter { cursorResult.enterpriseCursor}; for (Cursor cursor : cursors) { if (cursor != null) { - try { + try (cursor) { final List tempEntries = new ArrayList<>(); HashSet existingContactIds = new HashSet<>(); while (cursor.moveToNext()) { @@ -185,8 +185,6 @@ public final class ContactRecipientAdapter extends BaseRecipientAdapter { Collections.sort(tempEntries, mComparator); } entries.addAll(tempEntries); - } finally { - cursor.close(); } } } diff --git a/src/com/android/messaging/util/ContactUtil.java b/src/com/android/messaging/util/ContactUtil.java index 855f26c..1ee2ec9 100644 --- a/src/com/android/messaging/util/ContactUtil.java +++ b/src/com/android/messaging/util/ContactUtil.java @@ -1,5 +1,6 @@ /* * Copyright (C) 2015 The Android Open Source Project + * Copyright (C) 2024 The LineageOS Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -445,17 +446,11 @@ public class ContactUtil { return null; } String firstName = null; - Cursor nameCursor = null; - try { - nameCursor = ContactUtil.lookupStructuredName(context, contactId, true) - .performSynchronousQuery(); + try (Cursor nameCursor = ContactUtil.lookupStructuredName(context, contactId, true) + .performSynchronousQuery()) { if (nameCursor != null && nameCursor.moveToFirst()) { firstName = nameCursor.getString(ContactUtil.INDEX_STRUCTURED_NAME_GIVEN_NAME); } - } finally { - if (nameCursor != null) { - nameCursor.close(); - } } return firstName; } diff --git a/src/com/android/messaging/util/DebugUtils.java b/src/com/android/messaging/util/DebugUtils.java index f50426b..d33629d 100644 --- a/src/com/android/messaging/util/DebugUtils.java +++ b/src/com/android/messaging/util/DebugUtils.java @@ -56,15 +56,12 @@ public class DebugUtils { final File inputFile = getDebugFile(dumpFileName, false); if (inputFile != null) { final FileInputStream fis = new FileInputStream(inputFile); - final BufferedInputStream bis = new BufferedInputStream(fis); - try { + try (BufferedInputStream bis = new BufferedInputStream(fis)) { // dump file data = ByteStreams.toByteArray(bis); if (data == null || data.length < 1) { LogUtil.e(LogUtil.BUGLE_TAG, "receiveFromDumpFile: empty data"); } - } finally { - bis.close(); } } } catch (final IOException e) { diff --git a/src/com/android/messaging/util/ImageUtils.java b/src/com/android/messaging/util/ImageUtils.java index 8a462b4..2430970 100644 --- a/src/com/android/messaging/util/ImageUtils.java +++ b/src/com/android/messaging/util/ImageUtils.java @@ -222,18 +222,12 @@ public class ImageUtils { public static String getContentType(final ContentResolver cr, final Uri uri) { // Figure out the content type of media. String contentType = null; - Cursor cursor = null; if (UriUtil.isMediaStoreUri(uri)) { - try { - cursor = cr.query(uri, MEDIA_CONTENT_PROJECTION, null, null, null); + try (Cursor cursor = cr.query(uri, MEDIA_CONTENT_PROJECTION, null, null, null)) { if (cursor != null && cursor.moveToFirst()) { contentType = cursor.getString(INDEX_CONTENT_TYPE); } - } finally { - if (cursor != null) { - cursor.close(); - } } } if (contentType == null) { @@ -315,7 +309,7 @@ public class ImageUtils { */ public static boolean isGif(InputStream inputStream) { if (inputStream != null) { - try { + try (inputStream) { byte[] gifHeaderBytes = new byte[6]; int value = inputStream.read(gifHeaderBytes, 0, 6); if (value == 6) { @@ -324,12 +318,6 @@ public class ImageUtils { } } catch (IOException e) { return false; - } finally { - try { - inputStream.close(); - } catch (IOException e) { - // Ignore - } } } return false; diff --git a/src/com/android/messaging/util/MediaMetadataRetrieverWrapper.java b/src/com/android/messaging/util/MediaMetadataRetrieverWrapper.java index 1a93e9d..2654a5e 100644 --- a/src/com/android/messaging/util/MediaMetadataRetrieverWrapper.java +++ b/src/com/android/messaging/util/MediaMetadataRetrieverWrapper.java @@ -1,5 +1,6 @@ /* * Copyright (C) 2015 The Android Open Source Project + * Copyright (C) 2024 The LineageOS Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,17 +38,14 @@ public class MediaMetadataRetrieverWrapper { public void setDataSource(Uri uri) throws IOException { ContentResolver resolver = Factory.get().getApplicationContext().getContentResolver(); - AssetFileDescriptor fd = resolver.openAssetFileDescriptor(uri, "r"); - if (fd == null) { - throw new IOException("openAssetFileDescriptor returned null for " + uri); - } - try { + try (AssetFileDescriptor fd = resolver.openAssetFileDescriptor(uri, "r")) { + if (fd == null) { + throw new IOException("openAssetFileDescriptor returned null for " + uri); + } mRetriever.setDataSource(fd.getFileDescriptor()); } catch (RuntimeException e) { release(); throw new IOException(e); - } finally { - fd.close(); } } diff --git a/src/com/android/messaging/util/UriUtil.java b/src/com/android/messaging/util/UriUtil.java index f92155f..29219a9 100644 --- a/src/com/android/messaging/util/UriUtil.java +++ b/src/com/android/messaging/util/UriUtil.java @@ -1,5 +1,6 @@ /* * Copyright (C) 2015 The Android Open Source Project + * Copyright (C) 2024 The LineageOS Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -155,21 +156,13 @@ public class UriUtil { public static long getContentSize(final Uri uri) { Assert.isNotMainThread(); if (isLocalResourceUri(uri)) { - ParcelFileDescriptor pfd = null; - try { - pfd = Factory.get().getApplicationContext() - .getContentResolver().openFileDescriptor(uri, "r"); + try (ParcelFileDescriptor pfd = Factory.get().getApplicationContext() + .getContentResolver().openFileDescriptor(uri, "r")) { return Math.max(pfd.getStatSize(), 0); } catch (final FileNotFoundException e) { LogUtil.e(LogUtil.BUGLE_TAG, "Error getting content size", e); - } finally { - if (pfd != null) { - try { - pfd.close(); - } catch (final IOException e) { - // Do nothing. - } - } + } catch (final IOException e) { + // Do nothing. } } else { Assert.fail("Unsupported uri type!"); diff --git a/src/com/android/messaging/widget/WidgetConversationProvider.java b/src/com/android/messaging/widget/WidgetConversationProvider.java index d3e6128..6f76c84 100644 --- a/src/com/android/messaging/widget/WidgetConversationProvider.java +++ b/src/com/android/messaging/widget/WidgetConversationProvider.java @@ -270,23 +270,18 @@ public class WidgetConversationProvider extends BaseWidgetProvider { return null; } final Uri uri = MessagingContentProvider.buildConversationMetadataUri(conversationId); - Cursor cursor = null; - try { - cursor = context.getContentResolver().query(uri, - ConversationListItemData.PROJECTION, - null, // selection - null, // selection args - null); // sort order + try (Cursor cursor = context.getContentResolver().query(uri, + ConversationListItemData.PROJECTION, + null, // selection + null, // selection args + null // sort order + )) { if (cursor != null && cursor.getCount() > 0) { final ConversationListItemData conv = new ConversationListItemData(); cursor.moveToFirst(); conv.bind(cursor); return conv; } - } finally { - if (cursor != null) { - cursor.close(); - } } return null; }