2
0
mirror of https://github.com/KDE/kdeconnect-android synced 2025-08-28 12:47:43 +00:00

Use try-with-resources in places where it looked safe

This commit is contained in:
Albert Vaca 2018-10-30 12:30:21 +01:00
parent b54b69032f
commit a9ab77471e
5 changed files with 128 additions and 185 deletions

View File

@ -57,49 +57,31 @@ public class ContactsHelper {
@TargetApi(Build.VERSION_CODES.HONEYCOMB) @TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static Map<String, String> phoneNumberLookup(Context context, String number) { public static Map<String, String> phoneNumberLookup(Context context, String number) {
//Log.e("PhoneNumberLookup", number);
Map<String, String> contactInfo = new HashMap<>(); Map<String, String> contactInfo = new HashMap<>();
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number)); Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
Cursor cursor; String[] columns = new String[]{
try { PhoneLookup.DISPLAY_NAME,
cursor = context.getContentResolver().query( PhoneLookup.PHOTO_URI
uri, /*, PhoneLookup.TYPE
new String[]{ , PhoneLookup.LABEL
PhoneLookup.DISPLAY_NAME, , PhoneLookup.ID */
ContactsContract.PhoneLookup.PHOTO_URI };
/*, PhoneLookup.TYPE try (Cursor cursor = context.getContentResolver().query(uri, columns,null, null, null)) {
, PhoneLookup.LABEL // Take the first match only
, PhoneLookup.ID */ if (cursor != null && cursor.moveToFirst()) {
}, int nameIndex = cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME);
null, null, null); if (nameIndex != -1) {
} catch (Exception e) { contactInfo.put("name", cursor.getString(nameIndex));
return contactInfo; }
nameIndex = cursor.getColumnIndex(PhoneLookup.PHOTO_URI);
if (nameIndex != -1) {
contactInfo.put("photoID", cursor.getString(nameIndex));
}
}
} catch (Exception ignored) {
} }
// Take the first match only
if (cursor != null && cursor.moveToFirst()) {
int nameIndex = cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME);
if (nameIndex != -1) {
contactInfo.put("name", cursor.getString(nameIndex));
}
nameIndex = cursor.getColumnIndex(PhoneLookup.PHOTO_URI);
if (nameIndex != -1) {
contactInfo.put("photoID", cursor.getString(nameIndex));
}
try {
cursor.close();
} catch (Exception ignored) {
}
if (!contactInfo.isEmpty()) {
return contactInfo;
}
}
return contactInfo; return contactInfo;
} }
@ -157,34 +139,28 @@ public class ContactsHelper {
ArrayList<uID> toReturn = new ArrayList<>(); ArrayList<uID> toReturn = new ArrayList<>();
// Define the columns we want to read from the Contacts database // Define the columns we want to read from the Contacts database
final String[] projection = new String[]{ final String[] columns = new String[]{
ContactsContract.Contacts.LOOKUP_KEY ContactsContract.Contacts.LOOKUP_KEY
}; };
Uri contactsUri = ContactsContract.Contacts.CONTENT_URI; Uri contactsUri = ContactsContract.Contacts.CONTENT_URI;
Cursor contactsCursor = context.getContentResolver().query( try (Cursor contactsCursor = context.getContentResolver().query(contactsUri, columns, null, null, null)) {
contactsUri, if (contactsCursor != null && contactsCursor.moveToFirst()) {
projection, do {
null, null, null); uID contactID;
if (contactsCursor != null && contactsCursor.moveToFirst()) {
do {
uID contactID;
int idIndex = contactsCursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY); int idIndex = contactsCursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY);
if (idIndex != -1) { if (idIndex != -1) {
contactID = new uID(contactsCursor.getString(idIndex)); contactID = new uID(contactsCursor.getString(idIndex));
} else { } else {
// Something went wrong with this contact // Something went wrong with this contact
// If you are experiencing this, please open a bug report indicating how you got here // If you are experiencing this, please open a bug report indicating how you got here
Log.e("ContactsHelper", "Got a contact which does not have a LOOKUP_KEY"); Log.e("ContactsHelper", "Got a contact which does not have a LOOKUP_KEY");
continue; continue;
} }
toReturn.add(contactID); toReturn.add(contactID);
} while (contactsCursor.moveToNext()); } while (contactsCursor.moveToNext());
try {
contactsCursor.close();
} catch (Exception ignored) {
} }
} }
@ -221,14 +197,11 @@ public class ContactsHelper {
ContactsContract.Contacts.CONTENT_MULTI_VCARD_URI, ContactsContract.Contacts.CONTENT_MULTI_VCARD_URI,
Uri.encode(keys.toString())); Uri.encode(keys.toString()));
InputStream input; ;
StringBuilder vcardJumble = new StringBuilder(); StringBuilder vcardJumble = new StringBuilder();
try { try (InputStream input = context.getContentResolver().openInputStream(vcardURI)) {
input = context.getContentResolver().openInputStream(vcardURI);
BufferedReader bufferedInput = new BufferedReader(new InputStreamReader(input)); BufferedReader bufferedInput = new BufferedReader(new InputStreamReader(input));
String line; String line;
while ((line = bufferedInput.readLine()) != null) { while ((line = bufferedInput.readLine()) != null) {
vcardJumble.append(line).append('\n'); vcardJumble.append(line).append('\n');
} }
@ -263,9 +236,8 @@ public class ContactsHelper {
for (uID ID : IDs) { for (uID ID : IDs) {
String lookupKey = ID.toString(); String lookupKey = ID.toString();
Uri vcardURI = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey); Uri vcardURI = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
InputStream input;
try { try (InputStream input = context.getContentResolver().openInputStream(vcardURI)) {
input = context.getContentResolver().openInputStream(vcardURI);
if (input == null) if (input == null)
{ {
@ -281,13 +253,10 @@ public class ContactsHelper {
} }
toReturn.put(ID, new VCardBuilder(vcard.toString())); toReturn.put(ID, new VCardBuilder(vcard.toString()));
input.close();
} catch (IOException e) { } catch (IOException e) {
// If you are experiencing this, please open a bug report indicating how you got here // If you are experiencing this, please open a bug report indicating how you got here
e.printStackTrace(); e.printStackTrace();
continue; } catch (NullPointerException e) {
} catch (NullPointerException e)
{
// If you are experiencing this, please open a bug report indicating how you got here // If you are experiencing this, please open a bug report indicating how you got here
e.printStackTrace(); e.printStackTrace();
} }
@ -345,63 +314,59 @@ public class ContactsHelper {
contactsArgs.add(ID.toString()); contactsArgs.add(ID.toString());
} }
Cursor contactsCursor = context.getContentResolver().query( try (Cursor contactsCursor = context.getContentResolver().query(
contactsUri, contactsUri,
lookupProjection.toArray(new String[0]), lookupProjection.toArray(new String[0]),
contactsSelection.toString(), contactsSelection.toString(),
contactsArgs.toArray(new String[0]), null contactsArgs.toArray(new String[0]),
); null
)) {
if (contactsCursor != null && contactsCursor.moveToFirst()) {
do {
Map<String, Object> requestedData = new HashMap<>();
if (contactsCursor != null && contactsCursor.moveToFirst()) { int lookupKeyIdx = contactsCursor.getColumnIndexOrThrow(uID.COLUMN);
do { String lookupKey = contactsCursor.getString(lookupKeyIdx);
Map<String, Object> requestedData = new HashMap<>();
int lookupKeyIdx = contactsCursor.getColumnIndexOrThrow(uID.COLUMN); // For each column, collect the data from that column
String lookupKey = contactsCursor.getString(lookupKeyIdx); for (String column : contactsProjection) {
int index = contactsCursor.getColumnIndex(column);
// For each column, collect the data from that column // Since we might be getting various kinds of data, Object is the best we can do
for (String column : contactsProjection) { Object data;
int index = contactsCursor.getColumnIndex(column); int type;
// Since we might be getting various kinds of data, Object is the best we can do if (index == -1) {
Object data; // This contact didn't have the requested column? Something is very wrong.
int type; // If you are experiencing this, please open a bug report indicating how you got here
if (index == -1) { Log.e("ContactsHelper", "Got a contact which does not have a requested column");
// This contact didn't have the requested column? Something is very wrong.
// If you are experiencing this, please open a bug report indicating how you got here
Log.e("ContactsHelper", "Got a contact which does not have a requested column");
continue;
}
type = contactsCursor.getType(index);
switch (type) {
case Cursor.FIELD_TYPE_INTEGER:
data = contactsCursor.getInt(index);
break;
case Cursor.FIELD_TYPE_FLOAT:
data = contactsCursor.getFloat(index);
break;
case Cursor.FIELD_TYPE_STRING:
data = contactsCursor.getString(index);
break;
case Cursor.FIELD_TYPE_BLOB:
data = contactsCursor.getBlob(index);
break;
default:
Log.e("ContactsHelper", "Got an undefined type of column " + column);
continue; continue;
}
type = contactsCursor.getType(index);
switch (type) {
case Cursor.FIELD_TYPE_INTEGER:
data = contactsCursor.getInt(index);
break;
case Cursor.FIELD_TYPE_FLOAT:
data = contactsCursor.getFloat(index);
break;
case Cursor.FIELD_TYPE_STRING:
data = contactsCursor.getString(index);
break;
case Cursor.FIELD_TYPE_BLOB:
data = contactsCursor.getBlob(index);
break;
default:
Log.e("ContactsHelper", "Got an undefined type of column " + column);
continue;
}
requestedData.put(column, data);
} }
requestedData.put(column, data); toReturn.put(new uID(lookupKey), requestedData);
} } while (contactsCursor.moveToNext());
toReturn.put(new uID(lookupKey), requestedData);
} while (contactsCursor.moveToNext());
try {
contactsCursor.close();
} catch (Exception ignored) {
} }
} }
return toReturn; return toReturn;
} }

View File

@ -124,29 +124,26 @@ public class SMSHelper {
Uri smsUri = getSMSUri(); Uri smsUri = getSMSUri();
Cursor smsCursor = context.getContentResolver().query( try (Cursor smsCursor = context.getContentResolver().query(
smsUri, smsUri,
Message.smsColumns, Message.smsColumns,
selection, selection,
selectionArgs, selectionArgs,
null); null)
) {
if (smsCursor != null && smsCursor.moveToFirst()) { if (smsCursor != null && smsCursor.moveToFirst()) {
do { do {
HashMap<String, String> messageInfo = new HashMap<>(); HashMap<String, String> messageInfo = new HashMap<>();
for (int columnIdx = 0; columnIdx < smsCursor.getColumnCount(); columnIdx++) { for (int columnIdx = 0; columnIdx < smsCursor.getColumnCount(); columnIdx++) {
String colName = smsCursor.getColumnName(columnIdx); String colName = smsCursor.getColumnName(columnIdx);
String body = smsCursor.getString(columnIdx); String body = smsCursor.getString(columnIdx);
messageInfo.put(colName, body); messageInfo.put(colName, body);
} }
toReturn.add(new Message(messageInfo)); toReturn.add(new Message(messageInfo));
} while (smsCursor.moveToNext()); } while (smsCursor.moveToNext());
} else { } else {
// No SMSes available? // No SMSes available?
} }
if (smsCursor != null) {
smsCursor.close();
} }
return toReturn; return toReturn;
@ -164,32 +161,29 @@ public class SMSHelper {
Uri conversationUri = getConversationUri(); Uri conversationUri = getConversationUri();
Cursor conversationsCursor = context.getContentResolver().query( try (Cursor conversationsCursor = context.getContentResolver().query(
conversationUri, conversationUri,
Message.smsColumns, Message.smsColumns,
null, null,
null, null,
null); null)
) {
if (conversationsCursor != null && conversationsCursor.moveToFirst()) {
int threadColumn = conversationsCursor.getColumnIndexOrThrow(ThreadID.lookupColumn);
do {
int thread = conversationsCursor.getInt(threadColumn);
if (conversationsCursor != null && conversationsCursor.moveToFirst()) { HashMap<String, String> messageInfo = new HashMap<>();
int threadColumn = conversationsCursor.getColumnIndexOrThrow(ThreadID.lookupColumn); for (int columnIdx = 0; columnIdx < conversationsCursor.getColumnCount(); columnIdx++) {
do { String colName = conversationsCursor.getColumnName(columnIdx);
int thread = conversationsCursor.getInt(threadColumn); String body = conversationsCursor.getString(columnIdx);
messageInfo.put(colName, body);
HashMap<String, String> messageInfo = new HashMap<>(); }
for (int columnIdx = 0; columnIdx < conversationsCursor.getColumnCount(); columnIdx++) { toReturn.put(new ThreadID(thread), new Message(messageInfo));
String colName = conversationsCursor.getColumnName(columnIdx); } while (conversationsCursor.moveToNext());
String body = conversationsCursor.getString(columnIdx); } else {
messageInfo.put(colName, body); // No conversations available?
} }
toReturn.put(new ThreadID(thread), new Message(messageInfo));
} while (conversationsCursor.moveToNext());
} else {
// No conversations available?
}
if (conversationsCursor != null) {
conversationsCursor.close();
} }
return toReturn; return toReturn;

View File

@ -80,11 +80,8 @@ public class StorageHelper {
File storage = new File("/storage/"); File storage = new File("/storage/");
if (storage.exists() && storage.isDirectory()) { if (storage.exists() && storage.isDirectory()) {
String mounts = null; String mounts = null;
try { try (Scanner scanner = new Scanner(new File("/proc/mounts"))) {
Scanner scanner = new Scanner(new File("/proc/mounts"));
mounts = scanner.useDelimiter("\\A").next(); mounts = scanner.useDelimiter("\\A").next();
scanner.close();
//Log.e("Mounts",mounts);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
@ -116,9 +113,7 @@ public class StorageHelper {
//Legacy code for Android < 4.0 that still didn't have /storage //Legacy code for Android < 4.0 that still didn't have /storage
ArrayList<String> entries = new ArrayList<>(); ArrayList<String> entries = new ArrayList<>();
BufferedReader buf_reader = null; try (BufferedReader buf_reader = new BufferedReader(new FileReader("/proc/mounts"))){
try {
buf_reader = new BufferedReader(new FileReader("/proc/mounts"));
String entry; String entry;
while ((entry = buf_reader.readLine()) != null) { while ((entry = buf_reader.readLine()) != null) {
//Log.e("getStorageList", entry); //Log.e("getStorageList", entry);
@ -129,13 +124,6 @@ public class StorageHelper {
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} finally {
if (buf_reader != null) {
try {
buf_reader.close();
} catch (IOException ex) {
}
}
} }
for (String line : entries) { for (String line : entries) {

View File

@ -82,8 +82,7 @@ class AppDatabase {
void setEnabled(String packageName, boolean isEnabled) { void setEnabled(String packageName, boolean isEnabled) {
String[] columns = new String[]{KEY_IS_ENABLED}; String[] columns = new String[]{KEY_IS_ENABLED};
Cursor res = ourDatabase.query(DATABASE_TABLE, columns, KEY_PACKAGE_NAME + " =? ", new String[]{packageName}, null, null, null); try (Cursor res = ourDatabase.query(DATABASE_TABLE, columns, KEY_PACKAGE_NAME + " =? ", new String[]{packageName}, null, null, null)) {
try {
ContentValues cv = new ContentValues(); ContentValues cv = new ContentValues();
cv.put(KEY_IS_ENABLED, isEnabled ? "true" : "false"); cv.put(KEY_IS_ENABLED, isEnabled ? "true" : "false");
if (res.getCount() > 0) { if (res.getCount() > 0) {
@ -92,8 +91,6 @@ class AppDatabase {
cv.put(KEY_PACKAGE_NAME, packageName); cv.put(KEY_PACKAGE_NAME, packageName);
ourDatabase.insert(DATABASE_TABLE, null, cv); ourDatabase.insert(DATABASE_TABLE, null, cv);
} }
} finally {
res.close();
} }
} }
@ -103,8 +100,7 @@ class AppDatabase {
boolean isEnabled(String packageName) { boolean isEnabled(String packageName) {
String[] columns = new String[]{KEY_IS_ENABLED}; String[] columns = new String[]{KEY_IS_ENABLED};
Cursor res = ourDatabase.query(DATABASE_TABLE, columns, KEY_PACKAGE_NAME + " =? ", new String[]{packageName}, null, null, null); try (Cursor res = ourDatabase.query(DATABASE_TABLE, columns, KEY_PACKAGE_NAME + " =? ", new String[]{packageName}, null, null, null)) {
try {
boolean result; boolean result;
if (res.getCount() > 0) { if (res.getCount() > 0) {
res.moveToFirst(); res.moveToFirst();
@ -113,8 +109,6 @@ class AppDatabase {
result = getDefaultStatus(packageName); result = getDefaultStatus(packageName);
} }
return result; return result;
} finally {
res.close();
} }
} }

View File

@ -40,6 +40,8 @@ import org.kde.kdeconnect_tp.R;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
class ShareNotification { class ShareNotification {
@ -104,14 +106,14 @@ class ShareNotification {
//If it's an image, try to show it in the notification //If it's an image, try to show it in the notification
if (mimeType.startsWith("image/")) { if (mimeType.startsWith("image/")) {
try { try (InputStream inputStream = device.getContext().getContentResolver().openInputStream(destinationUri)) {
Bitmap image = BitmapFactory.decodeStream(device.getContext().getContentResolver().openInputStream(destinationUri)); Bitmap image = BitmapFactory.decodeStream(inputStream);
if (image != null) { if (image != null) {
builder.setLargeIcon(image); builder.setLargeIcon(image);
builder.setStyle(new NotificationCompat.BigPictureStyle() builder.setStyle(new NotificationCompat.BigPictureStyle()
.bigPicture(image)); .bigPicture(image));
} }
} catch (FileNotFoundException ignored) { } catch (IOException ignored) {
} }
} }
if (!"file".equals(destinationUri.getScheme())) { if (!"file".equals(destinationUri.getScheme())) {