Use try-with-resources where possible.

This commit is contained in:
Andreas Schildbach 2019-10-26 10:38:56 +02:00
parent 4c8114497a
commit d08464cb7f
7 changed files with 20 additions and 70 deletions

View file

@ -403,16 +403,12 @@ public abstract class OeffiMainActivity extends OeffiActivity {
} }
private void processMessages(final String network) { private void processMessages(final String network) {
BufferedReader reader = null;
String line = null; String line = null;
final File indexFile = new File(getFilesDir(), "messages.txt"); final File indexFile = new File(getFilesDir(), "messages.txt");
try (final BufferedReader reader = new BufferedReader(new InputStreamReader(
try { indexFile.exists() ? new FileInputStream(indexFile) : getAssets().open("messages.txt"),
reader = new BufferedReader(new InputStreamReader( Charsets.UTF_8))) {
indexFile.exists() ? new FileInputStream(indexFile) : getAssets().open("messages.txt"),
Charsets.UTF_8));
while (true) { while (true) {
line = reader.readLine(); line = reader.readLine();
if (line == null) if (line == null)
@ -430,13 +426,6 @@ public abstract class OeffiMainActivity extends OeffiActivity {
} }
} catch (final IOException x) { } catch (final IOException x) {
// ignore // ignore
} finally {
if (reader != null) {
try {
reader.close();
} catch (final IOException x2) {
}
}
} }
} }
@ -556,8 +545,8 @@ public abstract class OeffiMainActivity extends OeffiActivity {
request.url(url.build()); request.url(url.build());
final Call call = Application.OKHTTP_CLIENT.newCall(request.build()); final Call call = Application.OKHTTP_CLIENT.newCall(request.build());
call.enqueue(new Callback() { call.enqueue(new Callback() {
public void onResponse(final Call call, final Response response) throws IOException { public void onResponse(final Call call, final Response r) throws IOException {
try { try (final Response response = r) {
if (response.isSuccessful()) { if (response.isSuccessful()) {
final Bundle message = new Bundle(); final Bundle message = new Bundle();
message.putString("action", action); message.putString("action", action);
@ -609,8 +598,6 @@ public abstract class OeffiMainActivity extends OeffiActivity {
log.info("Got '{}: {}' when fetching message from: '{}'", response.code(), log.info("Got '{}: {}' when fetching message from: '{}'", response.code(),
response.message(), url); response.message(), url);
} }
} finally {
response.close();
} }
} }

View file

@ -378,12 +378,9 @@ public class NetworkPickerActivity extends Activity implements ActivityCompat.On
final Map<String, NetworkListEntry> entriesMap = new LinkedHashMap<>(); final Map<String, NetworkListEntry> entriesMap = new LinkedHashMap<>();
final List<NetworkListEntry> entries = new LinkedList<>(); final List<NetworkListEntry> entries = new LinkedList<>();
BufferedReader reader = null;
String line = null; String line = null;
try (final BufferedReader reader =
try { new BufferedReader(new InputStreamReader(getAssets().open(INDEX_FILENAME)))) {
reader = new BufferedReader(new InputStreamReader(getAssets().open(INDEX_FILENAME)));
while (true) { while (true) {
line = reader.readLine(); line = reader.readLine();
if (line == null) if (line == null)
@ -403,12 +400,6 @@ public class NetworkPickerActivity extends Activity implements ActivityCompat.On
} }
} catch (final Exception x) { } catch (final Exception x) {
throw new RuntimeException("problem parsing: '" + line + "'", x); throw new RuntimeException("problem parsing: '" + line + "'", x);
} finally {
try {
if (reader != null)
reader.close();
} catch (final IOException x2) {
}
} }
// last used networks // last used networks

View file

@ -191,9 +191,8 @@ public class PlanContentProvider extends ContentProvider {
private Cursor readIndexIntoCursor(final InputStream is, @Nullable final String idFilter, private Cursor readIndexIntoCursor(final InputStream is, @Nullable final String idFilter,
@Nullable final String query) throws IOException, NumberFormatException { @Nullable final String query) throws IOException, NumberFormatException {
final BufferedReader reader = new BufferedReader(new InputStreamReader(is));
try { try (final BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {
final MatrixCursor cursor = new MatrixCursor( final MatrixCursor cursor = new MatrixCursor(
new String[] { BaseColumns._ID, KEY_PLAN_ID, KEY_PLAN_NAME, KEY_PLAN_LAT, KEY_PLAN_LON, new String[] { BaseColumns._ID, KEY_PLAN_ID, KEY_PLAN_NAME, KEY_PLAN_LAT, KEY_PLAN_LON,
KEY_PLAN_VALID_FROM, KEY_PLAN_DISCLAIMER, KEY_PLAN_REMOTE_URL, KEY_PLAN_NETWORK_LOGO }); KEY_PLAN_VALID_FROM, KEY_PLAN_DISCLAIMER, KEY_PLAN_REMOTE_URL, KEY_PLAN_NETWORK_LOGO });
@ -240,8 +239,6 @@ public class PlanContentProvider extends ContentProvider {
} }
return cursor; return cursor;
} finally {
reader.close();
} }
} }
@ -263,9 +260,7 @@ public class PlanContentProvider extends ContentProvider {
private Cursor readStationsIntoCursor(final InputStream is, @Nullable final String planIdFilter, private Cursor readStationsIntoCursor(final InputStream is, @Nullable final String planIdFilter,
@Nullable final String networkFilter, @Nullable final String localIdFilter) @Nullable final String networkFilter, @Nullable final String localIdFilter)
throws IOException, NumberFormatException { throws IOException, NumberFormatException {
final BufferedReader reader = new BufferedReader(new InputStreamReader(is)); try (final BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {
try {
final MatrixCursor cursor = new MatrixCursor(new String[] { BaseColumns._ID, KEY_STATION_NETWORK, final MatrixCursor cursor = new MatrixCursor(new String[] { BaseColumns._ID, KEY_STATION_NETWORK,
KEY_STATION_ID, KEY_STATION_LABEL, KEY_STATION_PLAN_ID, KEY_STATION_X, KEY_STATION_Y }); KEY_STATION_ID, KEY_STATION_LABEL, KEY_STATION_PLAN_ID, KEY_STATION_X, KEY_STATION_Y });
@ -327,8 +322,6 @@ public class PlanContentProvider extends ContentProvider {
} }
return cursor; return cursor;
} finally {
reader.close();
} }
} }

View file

@ -146,8 +146,8 @@ public class PlansAdapter extends RecyclerView.Adapter<PlanViewHolder> {
final Call call = cachingOkHttpClient.newCall(request); final Call call = cachingOkHttpClient.newCall(request);
holder.setCall(call); holder.setCall(call);
call.enqueue(new Callback() { call.enqueue(new Callback() {
public void onResponse(final Call call, final Response response) throws IOException { public void onResponse(final Call call, final Response r) throws IOException {
try { try (final Response response = r) {
final Drawable thumb; final Drawable thumb;
if (response.isSuccessful()) if (response.isSuccessful())
thumb = new BitmapDrawable(res, response.body().byteStream()); thumb = new BitmapDrawable(res, response.body().byteStream());
@ -163,8 +163,6 @@ public class PlansAdapter extends RecyclerView.Adapter<PlanViewHolder> {
} }
}); });
} }
} finally {
response.close();
} }
} }

View file

@ -72,8 +72,8 @@ public class DecodeForeignActivity extends Activity {
request.url(HttpUrl.parse(uri.toString())); request.url(HttpUrl.parse(uri.toString()));
final Call call = Application.OKHTTP_CLIENT.newCall(request.build()); final Call call = Application.OKHTTP_CLIENT.newCall(request.build());
call.enqueue(new Callback() { call.enqueue(new Callback() {
public void onResponse(final Call call, final Response response) throws IOException { public void onResponse(final Call call, final Response r) throws IOException {
try { try (final Response response = r) {
if (response.isSuccessful()) { if (response.isSuccessful()) {
final Matcher mRefresh = PATTERN_META_REFRESH.matcher(response.body().string()); final Matcher mRefresh = PATTERN_META_REFRESH.matcher(response.body().string());
if (mRefresh.find()) { if (mRefresh.find()) {
@ -99,8 +99,6 @@ public class DecodeForeignActivity extends Activity {
} else { } else {
onFail(); onFail();
} }
} finally {
response.close();
} }
} }

View file

@ -103,8 +103,8 @@ public class Downloader {
private final File tempFile = new File(cacheDir, private final File tempFile = new File(cacheDir,
targetFile.getName() + ".part." + String.format("%04x", random.nextInt(0x10000))); targetFile.getName() + ".part." + String.format("%04x", random.nextInt(0x10000)));
public void onResponse(final Call call, final Response response) throws IOException { public void onResponse(final Call call, final Response r) throws IOException {
try { try (final Response response = r) {
final int status = response.code(); final int status = response.code();
if (status == HttpURLConnection.HTTP_OK) { if (status == HttpURLConnection.HTTP_OK) {
final ResponseBody body = response.body(); final ResponseBody body = response.body();
@ -136,7 +136,6 @@ public class Downloader {
future.set(status); future.set(status);
semaphore.release(); semaphore.release();
} finally { } finally {
response.close();
tempFile.delete(); tempFile.delete();
} }
} }
@ -160,9 +159,7 @@ public class Downloader {
final String etag = headers.get("ETag"); final String etag = headers.get("ETag");
final File metaFile = metaFile(file); final File metaFile = metaFile(file);
if (expires != null || etag != null) { if (expires != null || etag != null) {
PrintWriter writer = null; try (final PrintWriter writer = new PrintWriter(metaFile)) {
try {
writer = new PrintWriter(metaFile);
if (expires != null) if (expires != null)
writer.println("Expires: " + expires); writer.println("Expires: " + expires);
if (lastModified != null) if (lastModified != null)
@ -171,9 +168,6 @@ public class Downloader {
writer.println("ETag: " + etag); writer.println("ETag: " + etag);
} catch (final IOException x) { } catch (final IOException x) {
log.warn("Problem saving expiration time " + metaFile, x); log.warn("Problem saving expiration time " + metaFile, x);
} finally {
if (writer != null)
writer.close();
} }
} else { } else {
metaFile.delete(); metaFile.delete();
@ -186,9 +180,7 @@ public class Downloader {
final File metaFile = metaFile(file); final File metaFile = metaFile(file);
if (metaFile.exists()) { if (metaFile.exists()) {
String line = null; String line = null;
BufferedReader reader = null; try (final BufferedReader reader = new BufferedReader(new FileReader(metaFile), 128)) {
try {
reader = new BufferedReader(new FileReader(metaFile), 128);
while (true) { while (true) {
line = reader.readLine(); line = reader.readLine();
if (line == null) if (line == null)
@ -204,13 +196,6 @@ public class Downloader {
throw new RuntimeException("Problem loading meta data " + metaFile, x); throw new RuntimeException("Problem loading meta data " + metaFile, x);
} catch (final Exception x) { } catch (final Exception x) {
throw new RuntimeException("Problem parsing meta data: '" + line + "'", x); throw new RuntimeException("Problem parsing meta data: '" + line + "'", x);
} finally {
try {
if (reader != null)
reader.close();
} catch (final IOException x) {
// Ignore
}
} }
} }
return builder.build(); return builder.build();

View file

@ -335,8 +335,8 @@ public class ErrorReporter implements Thread.UncaughtExceptionHandler {
final Call call = Application.OKHTTP_CLIENT.newCall(request.build()); final Call call = Application.OKHTTP_CLIENT.newCall(request.build());
final Handler callbackHandler = new Handler(Looper.myLooper()); final Handler callbackHandler = new Handler(Looper.myLooper());
call.enqueue(new Callback() { call.enqueue(new Callback() {
public void onResponse(final Call call, final Response response) throws IOException { public void onResponse(final Call call, final Response r) throws IOException {
try { try (final Response response = r) {
final CharSequence page = response.body().string(); final CharSequence page = response.body().string();
final Matcher m = PATTERN_VERSION.matcher(page); final Matcher m = PATTERN_VERSION.matcher(page);
if (m.find()) { if (m.find()) {
@ -348,8 +348,6 @@ public class ErrorReporter implements Thread.UncaughtExceptionHandler {
else else
callback(null); callback(null);
} }
} finally {
response.close();
} }
} }