Require Android API 19, so fully use Java 7 try-with-resources, as well as a few other Java 7 features. Reduce deprecation warning count in android

This commit is contained in:
Sean Owen 2017-09-11 14:05:37 +01:00
parent b10dabfe07
commit 04595508b6
35 changed files with 220 additions and 346 deletions

View file

@ -138,6 +138,10 @@ public class IntentIntegrator {
BS_PACKAGE // Barcode Scanner BS_PACKAGE // Barcode Scanner
// What else supports this intent? // What else supports this intent?
); );
// Should be FLAG_ACTIVITY_NEW_DOCUMENT in API 21+.
// Defined once here because the current value is deprecated, so generates just one warning
private static final int FLAG_NEW_DOC = Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET;
private final Activity activity; private final Activity activity;
private final Fragment fragment; private final Fragment fragment;
@ -320,7 +324,7 @@ public class IntentIntegrator {
} }
intentScan.setPackage(targetAppPackage); intentScan.setPackage(targetAppPackage);
intentScan.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intentScan.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intentScan.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); intentScan.addFlags(FLAG_NEW_DOC);
attachMoreExtras(intentScan); attachMoreExtras(intentScan);
startActivityForResult(intentScan, REQUEST_CODE); startActivityForResult(intentScan, REQUEST_CODE);
return null; return null;
@ -466,7 +470,7 @@ public class IntentIntegrator {
} }
intent.setPackage(targetAppPackage); intent.setPackage(targetAppPackage);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); intent.addFlags(FLAG_NEW_DOC);
attachMoreExtras(intent); attachMoreExtras(intent);
if (fragment == null) { if (fragment == null) {
activity.startActivity(intent); activity.startActivity(intent);

View file

@ -31,7 +31,7 @@
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-sdk android:minSdkVersion="16" android:targetSdkVersion="22"/> <uses-sdk android:minSdkVersion="19" android:targetSdkVersion="22"/>
<uses-feature android:name="android.hardware.camera.any"/> <uses-feature android:name="android.hardware.camera.any"/>
<uses-feature android:name="android.hardware.camera.autofocus" android:required="false"/> <uses-feature android:name="android.hardware.camera.autofocus" android:required="false"/>

View file

@ -86,13 +86,8 @@ final class BeepManager implements MediaPlayer.OnErrorListener, Closeable {
private MediaPlayer buildMediaPlayer(Context activity) { private MediaPlayer buildMediaPlayer(Context activity) {
MediaPlayer mediaPlayer = new MediaPlayer(); MediaPlayer mediaPlayer = new MediaPlayer();
try { try (AssetFileDescriptor file = activity.getResources().openRawResourceFd(R.raw.beep)) {
AssetFileDescriptor file = activity.getResources().openRawResourceFd(R.raw.beep); mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());
try {
mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());
} finally {
file.close();
}
mediaPlayer.setOnErrorListener(this); mediaPlayer.setOnErrorListener(this);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setLooping(false); mediaPlayer.setLooping(false);

View file

@ -361,7 +361,7 @@ public final class CaptureActivity extends Activity implements SurfaceHolder.Cal
@Override @Override
public boolean onOptionsItemSelected(MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
Intent intent = new Intent(Intent.ACTION_VIEW); Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); intent.addFlags(Intents.FLAG_NEW_DOC);
switch (item.getItemId()) { switch (item.getItemId()) {
case R.id.menu_share: case R.id.menu_share:
intent.setClassName(this, ShareActivity.class.getName()); intent.setClassName(this, ShareActivity.class.getName());
@ -642,7 +642,7 @@ public final class CaptureActivity extends Activity implements SurfaceHolder.Cal
// Hand back whatever action they requested - this can be changed to Intents.Scan.ACTION when // Hand back whatever action they requested - this can be changed to Intents.Scan.ACTION when
// the deprecated intent is retired. // the deprecated intent is retired.
Intent intent = new Intent(getIntent().getAction()); Intent intent = new Intent(getIntent().getAction());
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); intent.addFlags(Intents.FLAG_NEW_DOC);
intent.putExtra(Intents.Scan.RESULT, rawResult.toString()); intent.putExtra(Intents.Scan.RESULT, rawResult.toString());
intent.putExtra(Intents.Scan.RESULT_FORMAT, rawResult.getBarcodeFormat().toString()); intent.putExtra(Intents.Scan.RESULT_FORMAT, rawResult.getBarcodeFormat().toString());
byte[] rawBytes = rawResult.getRawBytes(); byte[] rawBytes = rawResult.getRawBytes();

View file

@ -110,7 +110,7 @@ public final class CaptureActivityHandler extends Handler {
String url = (String) message.obj; String url = (String) message.obj;
Intent intent = new Intent(Intent.ACTION_VIEW); Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); intent.addFlags(Intents.FLAG_NEW_DOC);
intent.setData(Uri.parse(url)); intent.setData(Uri.parse(url));
ResolveInfo resolveInfo = ResolveInfo resolveInfo =
@ -122,10 +122,13 @@ public final class CaptureActivityHandler extends Handler {
} }
// Needed for default Android browser / Chrome only apparently // Needed for default Android browser / Chrome only apparently
if ("com.android.browser".equals(browserPackageName) || "com.android.chrome".equals(browserPackageName)) { switch (browserPackageName) {
intent.setPackage(browserPackageName); case "com.android.browser":
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); case "com.android.chrome":
intent.putExtra(Browser.EXTRA_APPLICATION_ID, browserPackageName); intent.setPackage(browserPackageName);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Browser.EXTRA_APPLICATION_ID, browserPackageName);
break;
} }
try { try {

View file

@ -144,22 +144,12 @@ public final class HttpHelper {
private static CharSequence consume(URLConnection connection, int maxChars) throws IOException { private static CharSequence consume(URLConnection connection, int maxChars) throws IOException {
String encoding = getEncoding(connection); String encoding = getEncoding(connection);
StringBuilder out = new StringBuilder(); StringBuilder out = new StringBuilder();
Reader in = null; try (Reader in = new InputStreamReader(connection.getInputStream(), encoding)) {
try {
in = new InputStreamReader(connection.getInputStream(), encoding);
char[] buffer = new char[1024]; char[] buffer = new char[1024];
int charsRead; int charsRead;
while (out.length() < maxChars && (charsRead = in.read(buffer)) > 0) { while (out.length() < maxChars && (charsRead = in.read(buffer)) > 0) {
out.append(buffer, 0, charsRead); out.append(buffer, 0, charsRead);
} }
} finally {
if (in != null) {
try {
in.close();
} catch (IOException | NullPointerException ioe) {
// continue
}
}
} }
return out; return out;
} }

View file

@ -16,6 +16,8 @@
package com.google.zxing.client.android; package com.google.zxing.client.android;
import android.content.Intent;
/** /**
* This class provides the constants to use when sending an Intent to Barcode Scanner. * This class provides the constants to use when sending an Intent to Barcode Scanner.
* These strings are effectively API and cannot be changed. * These strings are effectively API and cannot be changed.
@ -128,14 +130,14 @@ public final class Intents {
public static final String RESULT = "SCAN_RESULT"; public static final String RESULT = "SCAN_RESULT";
/** /**
* Call {@link android.content.Intent#getStringExtra(String)} with {@link #RESULT_FORMAT} * Call {@link android.content.Intent#getStringExtra(String)} with {@code RESULT_FORMAT}
* to determine which barcode format was found. * to determine which barcode format was found.
* See {@link com.google.zxing.BarcodeFormat} for possible values. * See {@link com.google.zxing.BarcodeFormat} for possible values.
*/ */
public static final String RESULT_FORMAT = "SCAN_RESULT_FORMAT"; public static final String RESULT_FORMAT = "SCAN_RESULT_FORMAT";
/** /**
* Call {@link android.content.Intent#getStringExtra(String)} with {@link #RESULT_UPC_EAN_EXTENSION} * Call {@link android.content.Intent#getStringExtra(String)} with {@code RESULT_UPC_EAN_EXTENSION}
* to return the content of any UPC extension barcode that was also found. Only applicable * to return the content of any UPC extension barcode that was also found. Only applicable
* to {@link com.google.zxing.BarcodeFormat#UPC_A} and {@link com.google.zxing.BarcodeFormat#EAN_13} * to {@link com.google.zxing.BarcodeFormat#UPC_A} and {@link com.google.zxing.BarcodeFormat#EAN_13}
* formats. * formats.
@ -143,20 +145,20 @@ public final class Intents {
public static final String RESULT_UPC_EAN_EXTENSION = "SCAN_RESULT_UPC_EAN_EXTENSION"; public static final String RESULT_UPC_EAN_EXTENSION = "SCAN_RESULT_UPC_EAN_EXTENSION";
/** /**
* Call {@link android.content.Intent#getByteArrayExtra(String)} with {@link #RESULT_BYTES} * Call {@link android.content.Intent#getByteArrayExtra(String)} with {@code RESULT_BYTES}
* to get a {@code byte[]} of raw bytes in the barcode, if available. * to get a {@code byte[]} of raw bytes in the barcode, if available.
*/ */
public static final String RESULT_BYTES = "SCAN_RESULT_BYTES"; public static final String RESULT_BYTES = "SCAN_RESULT_BYTES";
/** /**
* Key for the value of {@link com.google.zxing.ResultMetadataType#ORIENTATION}, if available. * Key for the value of {@link com.google.zxing.ResultMetadataType#ORIENTATION}, if available.
* Call {@link android.content.Intent#getIntArrayExtra(String)} with {@link #RESULT_ORIENTATION}. * Call {@link android.content.Intent#getIntArrayExtra(String)} with {@code RESULT_ORIENTATION}.
*/ */
public static final String RESULT_ORIENTATION = "SCAN_RESULT_ORIENTATION"; public static final String RESULT_ORIENTATION = "SCAN_RESULT_ORIENTATION";
/** /**
* Key for the value of {@link com.google.zxing.ResultMetadataType#ERROR_CORRECTION_LEVEL}, if available. * Key for the value of {@link com.google.zxing.ResultMetadataType#ERROR_CORRECTION_LEVEL}, if available.
* Call {@link android.content.Intent#getStringExtra(String)} with {@link #RESULT_ERROR_CORRECTION_LEVEL}. * Call {@link android.content.Intent#getStringExtra(String)} with {@code RESULT_ERROR_CORRECTION_LEVEL}.
*/ */
public static final String RESULT_ERROR_CORRECTION_LEVEL = "SCAN_RESULT_ERROR_CORRECTION_LEVEL"; public static final String RESULT_ERROR_CORRECTION_LEVEL = "SCAN_RESULT_ERROR_CORRECTION_LEVEL";
@ -293,4 +295,9 @@ public final class Intents {
private Share() { private Share() {
} }
} }
// Not the best place for this, but, better than a new class
// Should be FLAG_ACTIVITY_NEW_DOCUMENT in API 21+.
// Defined once here because the current value is deprecated, so generates just one warning
public static final int FLAG_NEW_DOC = Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET;
} }

View file

@ -20,6 +20,7 @@ import android.content.Intent;
import android.net.Uri; import android.net.Uri;
import android.view.View; import android.view.View;
import android.widget.AdapterView; import android.widget.AdapterView;
import com.google.zxing.client.android.Intents;
import com.google.zxing.client.android.LocaleManager; import com.google.zxing.client.android.LocaleManager;
import java.util.List; import java.util.List;
@ -54,7 +55,7 @@ final class BrowseBookListener implements AdapterView.OnItemClickListener {
LocaleManager.getBookSearchCountryTLD(activity) + LocaleManager.getBookSearchCountryTLD(activity) +
"/books?id=" + volumeId + "&pg=" + pageId + "&vq=" + query; "/books?id=" + volumeId + "&pg=" + pageId + "&vq=" + query;
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(readBookURI)); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(readBookURI));
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); intent.addFlags(Intents.FLAG_NEW_DOC);
activity.startActivity(intent); activity.startActivity(intent);
} }
} }

View file

@ -175,12 +175,9 @@ public final class SearchBookContentsActivity extends Activity {
} }
CharSequence content = HttpHelper.downloadViaHttp(uri, HttpHelper.ContentType.JSON); CharSequence content = HttpHelper.downloadViaHttp(uri, HttpHelper.ContentType.JSON);
return new JSONObject(content.toString()); return new JSONObject(content.toString());
} catch (IOException ioe) { } catch (IOException | JSONException ioe) {
Log.w(TAG, "Error accessing book search", ioe); Log.w(TAG, "Error accessing book search", ioe);
return null; return null;
} catch (JSONException je) {
Log.w(TAG, "Error accessing book search", je);
return null;
} }
} }

View file

@ -16,6 +16,8 @@
package com.google.zxing.client.android.encode; package com.google.zxing.client.android.encode;
import android.telephony.PhoneNumberUtils;
import java.util.Collection; import java.util.Collection;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
@ -93,4 +95,9 @@ abstract class ContactEncoder {
} }
} }
static String formatPhone(String phoneData) {
// Just collect the call to a deprecated method in one place
return PhoneNumberUtils.formatNumber(phoneData);
}
} }

View file

@ -40,7 +40,6 @@ import android.widget.ImageView;
import android.widget.TextView; import android.widget.TextView;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.util.regex.Pattern; import java.util.regex.Pattern;
@ -150,22 +149,12 @@ public final class EncodeActivity extends Activity {
Log.w(TAG, "Could not delete " + barcodeFile); Log.w(TAG, "Could not delete " + barcodeFile);
// continue anyway // continue anyway
} }
FileOutputStream fos = null; try (FileOutputStream fos = new FileOutputStream(barcodeFile)) {
try {
fos = new FileOutputStream(barcodeFile);
bitmap.compress(Bitmap.CompressFormat.PNG, 0, fos); bitmap.compress(Bitmap.CompressFormat.PNG, 0, fos);
} catch (FileNotFoundException fnfe) { } catch (IOException ioe) {
Log.w(TAG, "Couldn't access file " + barcodeFile + " due to " + fnfe); Log.w(TAG, "Couldn't access file " + barcodeFile + " due to " + ioe);
showErrorMessage(R.string.msg_unmount_usb); showErrorMessage(R.string.msg_unmount_usb);
return; return;
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException ioe) {
// do nothing
}
}
} }
Intent intent = new Intent(Intent.ACTION_SEND, Uri.parse("mailto:")); Intent intent = new Intent(Intent.ACTION_SEND, Uri.parse("mailto:"));
@ -173,7 +162,7 @@ public final class EncodeActivity extends Activity {
intent.putExtra(Intent.EXTRA_TEXT, contents); intent.putExtra(Intent.EXTRA_TEXT, contents);
intent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + barcodeFile.getAbsolutePath())); intent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + barcodeFile.getAbsolutePath()));
intent.setType("image/png"); intent.setType("image/png");
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); intent.addFlags(Intents.FLAG_NEW_DOC);
startActivity(Intent.createChooser(intent, null)); startActivity(Intent.createChooser(intent, null));
} }

View file

@ -16,8 +16,6 @@
package com.google.zxing.client.android.encode; package com.google.zxing.client.android.encode;
import android.telephony.PhoneNumberUtils;
import java.util.List; import java.util.List;
import java.util.regex.Pattern; import java.util.regex.Pattern;
@ -82,7 +80,7 @@ final class MECARDContactEncoder extends ContactEncoder {
private static final Pattern NOT_DIGITS_OR_PLUS = Pattern.compile("[^0-9+]+"); private static final Pattern NOT_DIGITS_OR_PLUS = Pattern.compile("[^0-9+]+");
@Override @Override
public CharSequence format(CharSequence value, int index) { public CharSequence format(CharSequence value, int index) {
return NOT_DIGITS_OR_PLUS.matcher(PhoneNumberUtils.formatNumber(value.toString())).replaceAll(""); return NOT_DIGITS_OR_PLUS.matcher(ContactEncoder.formatPhone(value.toString())).replaceAll("");
} }
} }

View file

@ -35,7 +35,6 @@ import android.graphics.Bitmap;
import android.net.Uri; import android.net.Uri;
import android.os.Bundle; import android.os.Bundle;
import android.provider.ContactsContract; import android.provider.ContactsContract;
import android.telephony.PhoneNumberUtils;
import android.util.Log; import android.util.Log;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
@ -185,9 +184,7 @@ final class QRCodeEncoder {
} }
byte[] vcard; byte[] vcard;
String vcardString; String vcardString;
InputStream stream = null; try (InputStream stream = activity.getContentResolver().openInputStream(uri)) {
try {
stream = activity.getContentResolver().openInputStream(uri);
if (stream == null) { if (stream == null) {
throw new WriterException("Can't open stream for " + uri); throw new WriterException("Can't open stream for " + uri);
} }
@ -201,14 +198,6 @@ final class QRCodeEncoder {
vcardString = new String(vcard, 0, vcard.length, "UTF-8"); vcardString = new String(vcard, 0, vcard.length, "UTF-8");
} catch (IOException ioe) { } catch (IOException ioe) {
throw new WriterException(ioe); throw new WriterException(ioe);
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
// continue
}
}
} }
Log.d(TAG, "Encoding share intent content:"); Log.d(TAG, "Encoding share intent content:");
Log.d(TAG, vcardString); Log.d(TAG, vcardString);
@ -247,7 +236,7 @@ final class QRCodeEncoder {
String phoneData = ContactEncoder.trim(intent.getStringExtra(Intents.Encode.DATA)); String phoneData = ContactEncoder.trim(intent.getStringExtra(Intents.Encode.DATA));
if (phoneData != null) { if (phoneData != null) {
contents = "tel:" + phoneData; contents = "tel:" + phoneData;
displayContents = PhoneNumberUtils.formatNumber(phoneData); displayContents = ContactEncoder.formatPhone(phoneData);
title = activity.getString(R.string.contents_phone); title = activity.getString(R.string.contents_phone);
} }
break; break;
@ -256,7 +245,7 @@ final class QRCodeEncoder {
String smsData = ContactEncoder.trim(intent.getStringExtra(Intents.Encode.DATA)); String smsData = ContactEncoder.trim(intent.getStringExtra(Intents.Encode.DATA));
if (smsData != null) { if (smsData != null) {
contents = "sms:" + smsData; contents = "sms:" + smsData;
displayContents = PhoneNumberUtils.formatNumber(smsData); displayContents = ContactEncoder.formatPhone(smsData);
title = activity.getString(R.string.contents_sms); title = activity.getString(R.string.contents_sms);
} }
break; break;

View file

@ -16,8 +16,6 @@
package com.google.zxing.client.android.encode; package com.google.zxing.client.android.encode;
import android.telephony.PhoneNumberUtils;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -40,7 +38,7 @@ final class VCardTelDisplayFormatter implements Formatter {
@Override @Override
public CharSequence format(CharSequence value, int index) { public CharSequence format(CharSequence value, int index) {
value = PhoneNumberUtils.formatNumber(value.toString()); value = ContactEncoder.formatPhone(value.toString());
Map<String,Set<String>> metadata = Map<String,Set<String>> metadata =
metadataForIndex == null || metadataForIndex.size() <= index ? null : metadataForIndex.get(index); metadataForIndex == null || metadataForIndex.size() <= index ? null : metadataForIndex.get(index);
value = formatMetadata(value, metadata); value = formatMetadata(value, metadata);

View file

@ -128,7 +128,7 @@ public final class HistoryActivity extends ListActivity {
builder.show(); builder.show();
} else { } else {
Intent intent = new Intent(Intent.ACTION_SEND, Uri.parse("mailto:")); Intent intent = new Intent(Intent.ACTION_SEND, Uri.parse("mailto:"));
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); intent.addFlags(Intents.FLAG_NEW_DOC);
String subject = getResources().getString(R.string.history_email_title); String subject = getResources().getString(R.string.history_email_title);
intent.putExtra(Intent.EXTRA_SUBJECT, subject); intent.putExtra(Intent.EXTRA_SUBJECT, subject);
intent.putExtra(Intent.EXTRA_TEXT, subject); intent.putExtra(Intent.EXTRA_TEXT, subject);

View file

@ -39,7 +39,7 @@ import java.io.File;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStreamWriter; import java.io.OutputStreamWriter;
import java.nio.charset.Charset; import java.nio.charset.StandardCharsets;
import java.text.DateFormat; import java.text.DateFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -81,29 +81,24 @@ public final class HistoryManager {
public boolean hasHistoryItems() { public boolean hasHistoryItems() {
SQLiteOpenHelper helper = new DBHelper(activity); SQLiteOpenHelper helper = new DBHelper(activity);
SQLiteDatabase db = null; try (SQLiteDatabase db = helper.getReadableDatabase();
Cursor cursor = null; Cursor cursor = db.query(DBHelper.TABLE_NAME, COUNT_COLUMN, null, null, null, null, null)) {
try {
db = helper.getReadableDatabase();
cursor = db.query(DBHelper.TABLE_NAME, COUNT_COLUMN, null, null, null, null, null);
cursor.moveToFirst(); cursor.moveToFirst();
return cursor.getInt(0) > 0; return cursor.getInt(0) > 0;
} catch (SQLException sqle) { } catch (SQLException sqle) {
Log.w(TAG, sqle); Log.w(TAG, sqle);
return false; return false;
} finally {
close(cursor, db);
} }
} }
public List<HistoryItem> buildHistoryItems() { public List<HistoryItem> buildHistoryItems() {
SQLiteOpenHelper helper = new DBHelper(activity); SQLiteOpenHelper helper = new DBHelper(activity);
List<HistoryItem> items = new ArrayList<>(); List<HistoryItem> items = new ArrayList<>();
SQLiteDatabase db = null; try (SQLiteDatabase db = helper.getReadableDatabase();
Cursor cursor = null; Cursor cursor = db.query(DBHelper.TABLE_NAME,
try { COLUMNS,
db = helper.getReadableDatabase(); null, null, null, null,
cursor = db.query(DBHelper.TABLE_NAME, COLUMNS, null, null, null, null, DBHelper.TIMESTAMP_COL + " DESC"); DBHelper.TIMESTAMP_COL + " DESC")) {
while (cursor.moveToNext()) { while (cursor.moveToNext()) {
String text = cursor.getString(0); String text = cursor.getString(0);
String display = cursor.getString(1); String display = cursor.getString(1);
@ -115,20 +110,17 @@ public final class HistoryManager {
} }
} catch (CursorIndexOutOfBoundsException cioobe) { } catch (CursorIndexOutOfBoundsException cioobe) {
Log.w(TAG, cioobe); Log.w(TAG, cioobe);
// continue
} finally {
close(cursor, db);
} }
return items; return items;
} }
public HistoryItem buildHistoryItem(int number) { public HistoryItem buildHistoryItem(int number) {
SQLiteOpenHelper helper = new DBHelper(activity); SQLiteOpenHelper helper = new DBHelper(activity);
SQLiteDatabase db = null; try (SQLiteDatabase db = helper.getReadableDatabase();
Cursor cursor = null; Cursor cursor = db.query(DBHelper.TABLE_NAME,
try { COLUMNS,
db = helper.getReadableDatabase(); null, null, null, null,
cursor = db.query(DBHelper.TABLE_NAME, COLUMNS, null, null, null, null, DBHelper.TIMESTAMP_COL + " DESC"); DBHelper.TIMESTAMP_COL + " DESC")) {
cursor.move(number + 1); cursor.move(number + 1);
String text = cursor.getString(0); String text = cursor.getString(0);
String display = cursor.getString(1); String display = cursor.getString(1);
@ -137,27 +129,20 @@ public final class HistoryManager {
String details = cursor.getString(4); String details = cursor.getString(4);
Result result = new Result(text, null, null, BarcodeFormat.valueOf(format), timestamp); Result result = new Result(text, null, null, BarcodeFormat.valueOf(format), timestamp);
return new HistoryItem(result, display, details); return new HistoryItem(result, display, details);
} finally {
close(cursor, db);
} }
} }
public void deleteHistoryItem(int number) { public void deleteHistoryItem(int number) {
SQLiteOpenHelper helper = new DBHelper(activity); SQLiteOpenHelper helper = new DBHelper(activity);
SQLiteDatabase db = null; try (SQLiteDatabase db = helper.getWritableDatabase();
Cursor cursor = null; Cursor cursor = db.query(DBHelper.TABLE_NAME,
try { ID_COL_PROJECTION,
db = helper.getWritableDatabase(); null, null, null, null,
cursor = db.query(DBHelper.TABLE_NAME, DBHelper.TIMESTAMP_COL + " DESC")) {
ID_COL_PROJECTION,
null, null, null, null,
DBHelper.TIMESTAMP_COL + " DESC");
cursor.move(number + 1); cursor.move(number + 1);
db.delete(DBHelper.TABLE_NAME, DBHelper.ID_COL + '=' + cursor.getString(0), null); db.delete(DBHelper.TABLE_NAME, DBHelper.ID_COL + '=' + cursor.getString(0), null);
} catch (SQLException sqle) { } catch (SQLException sqle) {
Log.w(TAG, sqle); Log.w(TAG, sqle);
} finally {
close(cursor, db);
} }
} }
@ -181,13 +166,9 @@ public final class HistoryManager {
values.put(DBHelper.TIMESTAMP_COL, System.currentTimeMillis()); values.put(DBHelper.TIMESTAMP_COL, System.currentTimeMillis());
SQLiteOpenHelper helper = new DBHelper(activity); SQLiteOpenHelper helper = new DBHelper(activity);
SQLiteDatabase db = null; try (SQLiteDatabase db = helper.getWritableDatabase()) {
try {
db = helper.getWritableDatabase();
// Insert the new entry into the DB. // Insert the new entry into the DB.
db.insert(DBHelper.TABLE_NAME, DBHelper.TIMESTAMP_COL, values); db.insert(DBHelper.TABLE_NAME, DBHelper.TIMESTAMP_COL, values);
} finally {
close(null, db);
} }
} }
@ -195,18 +176,15 @@ public final class HistoryManager {
// As we're going to do an update only we don't need need to worry // As we're going to do an update only we don't need need to worry
// about the preferences; if the item wasn't saved it won't be udpated // about the preferences; if the item wasn't saved it won't be udpated
SQLiteOpenHelper helper = new DBHelper(activity); SQLiteOpenHelper helper = new DBHelper(activity);
SQLiteDatabase db = null; try (SQLiteDatabase db = helper.getWritableDatabase();
Cursor cursor = null; Cursor cursor = db.query(DBHelper.TABLE_NAME,
try { ID_DETAIL_COL_PROJECTION,
db = helper.getWritableDatabase(); DBHelper.TEXT_COL + "=?",
cursor = db.query(DBHelper.TABLE_NAME, new String[] { itemID },
ID_DETAIL_COL_PROJECTION, null,
DBHelper.TEXT_COL + "=?", null,
new String[] { itemID }, DBHelper.TIMESTAMP_COL + " DESC",
null, "1")) {
null,
DBHelper.TIMESTAMP_COL + " DESC",
"1");
String oldID = null; String oldID = null;
String oldDetails = null; String oldDetails = null;
if (cursor.moveToNext()) { if (cursor.moveToNext()) {
@ -229,35 +207,25 @@ public final class HistoryManager {
db.update(DBHelper.TABLE_NAME, values, DBHelper.ID_COL + "=?", new String[] { oldID }); db.update(DBHelper.TABLE_NAME, values, DBHelper.ID_COL + "=?", new String[] { oldID });
} }
} }
} finally {
close(cursor, db);
} }
} }
private void deletePrevious(String text) { private void deletePrevious(String text) {
SQLiteOpenHelper helper = new DBHelper(activity); SQLiteOpenHelper helper = new DBHelper(activity);
SQLiteDatabase db = null; try (SQLiteDatabase db = helper.getWritableDatabase()) {
try {
db = helper.getWritableDatabase();
db.delete(DBHelper.TABLE_NAME, DBHelper.TEXT_COL + "=?", new String[] { text }); db.delete(DBHelper.TABLE_NAME, DBHelper.TEXT_COL + "=?", new String[] { text });
} catch (SQLException sqle) { } catch (SQLException sqle) {
Log.w(TAG, sqle); Log.w(TAG, sqle);
} finally {
close(null, db);
} }
} }
public void trimHistory() { public void trimHistory() {
SQLiteOpenHelper helper = new DBHelper(activity); SQLiteOpenHelper helper = new DBHelper(activity);
SQLiteDatabase db = null; try (SQLiteDatabase db = helper.getWritableDatabase();
Cursor cursor = null; Cursor cursor = db.query(DBHelper.TABLE_NAME,
try { ID_COL_PROJECTION,
db = helper.getWritableDatabase(); null, null, null, null,
cursor = db.query(DBHelper.TABLE_NAME, DBHelper.TIMESTAMP_COL + " DESC")) {
ID_COL_PROJECTION,
null, null, null, null,
DBHelper.TIMESTAMP_COL + " DESC");
cursor.move(MAX_ITEMS); cursor.move(MAX_ITEMS);
while (cursor.moveToNext()) { while (cursor.moveToNext()) {
String id = cursor.getString(0); String id = cursor.getString(0);
@ -265,12 +233,7 @@ public final class HistoryManager {
db.delete(DBHelper.TABLE_NAME, DBHelper.ID_COL + '=' + id, null); db.delete(DBHelper.TABLE_NAME, DBHelper.ID_COL + '=' + id, null);
} }
} catch (SQLException sqle) { } catch (SQLException sqle) {
// We're seeing an error here when called in CaptureActivity.onCreate() in rare cases
// and don't understand it. First theory is that it's transient so can be safely ignored.
Log.w(TAG, sqle); Log.w(TAG, sqle);
// continue
} finally {
close(cursor, db);
} }
} }
@ -291,15 +254,11 @@ public final class HistoryManager {
*/ */
CharSequence buildHistory() { CharSequence buildHistory() {
SQLiteOpenHelper helper = new DBHelper(activity); SQLiteOpenHelper helper = new DBHelper(activity);
SQLiteDatabase db = null; try (SQLiteDatabase db = helper.getWritableDatabase();
Cursor cursor = null; Cursor cursor = db.query(DBHelper.TABLE_NAME,
try { COLUMNS,
db = helper.getWritableDatabase(); null, null, null, null,
cursor = db.query(DBHelper.TABLE_NAME, DBHelper.TIMESTAMP_COL + " DESC")) {
COLUMNS,
null, null, null, null,
DBHelper.TIMESTAMP_COL + " DESC");
DateFormat format = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM); DateFormat format = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
StringBuilder historyText = new StringBuilder(1000); StringBuilder historyText = new StringBuilder(1000);
while (cursor.moveToNext()) { while (cursor.moveToNext()) {
@ -318,21 +277,15 @@ public final class HistoryManager {
historyText.append('"').append(massageHistoryField(cursor.getString(4))).append("\"\r\n"); historyText.append('"').append(massageHistoryField(cursor.getString(4))).append("\"\r\n");
} }
return historyText; return historyText;
} finally {
close(cursor, db);
} }
} }
void clearHistory() { void clearHistory() {
SQLiteOpenHelper helper = new DBHelper(activity); SQLiteOpenHelper helper = new DBHelper(activity);
SQLiteDatabase db = null; try (SQLiteDatabase db = helper.getWritableDatabase()) {
try {
db = helper.getWritableDatabase();
db.delete(DBHelper.TABLE_NAME, null, null); db.delete(DBHelper.TABLE_NAME, null, null);
} catch (SQLException sqle) { } catch (SQLException sqle) {
Log.w(TAG, sqle); Log.w(TAG, sqle);
} finally {
close(null, db);
} }
} }
@ -344,36 +297,17 @@ public final class HistoryManager {
return null; return null;
} }
File historyFile = new File(historyRoot, "history-" + System.currentTimeMillis() + ".csv"); File historyFile = new File(historyRoot, "history-" + System.currentTimeMillis() + ".csv");
OutputStreamWriter out = null; try (OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(historyFile), StandardCharsets.UTF_8)) {
try {
out = new OutputStreamWriter(new FileOutputStream(historyFile), Charset.forName("UTF-8"));
out.write(history); out.write(history);
return Uri.parse("file://" + historyFile.getAbsolutePath()); return Uri.parse("file://" + historyFile.getAbsolutePath());
} catch (IOException ioe) { } catch (IOException ioe) {
Log.w(TAG, "Couldn't access file " + historyFile + " due to " + ioe); Log.w(TAG, "Couldn't access file " + historyFile + " due to " + ioe);
return null; return null;
} finally {
if (out != null) {
try {
out.close();
} catch (IOException ioe) {
// do nothing
}
}
} }
} }
private static String massageHistoryField(String value) { private static String massageHistoryField(String value) {
return value == null ? "" : DOUBLE_QUOTE.matcher(value).replaceAll("\"\""); return value == null ? "" : DOUBLE_QUOTE.matcher(value).replaceAll("\"\"");
} }
private static void close(Cursor cursor, SQLiteDatabase database) {
if (cursor != null) {
cursor.close();
}
if (database != null) {
database.close();
}
}
} }

View file

@ -22,7 +22,6 @@ import com.google.zxing.client.result.ParsedResult;
import android.app.Activity; import android.app.Activity;
import android.graphics.Typeface; import android.graphics.Typeface;
import android.telephony.PhoneNumberUtils;
import android.text.Spannable; import android.text.Spannable;
import android.text.SpannableString; import android.text.SpannableString;
import android.text.style.StyleSpan; import android.text.style.StyleSpan;
@ -183,7 +182,7 @@ public final class AddressBookResultHandler extends ResultHandler {
if (numbers != null) { if (numbers != null) {
for (String number : numbers) { for (String number : numbers) {
if (number != null) { if (number != null) {
ParsedResult.maybeAppend(PhoneNumberUtils.formatNumber(number), contents); ParsedResult.maybeAppend(formatPhone(number), contents);
} }
} }
} }

View file

@ -16,6 +16,7 @@
package com.google.zxing.client.android.result; package com.google.zxing.client.android.result;
import android.telephony.PhoneNumberUtils;
import com.google.zxing.Result; import com.google.zxing.Result;
import com.google.zxing.client.android.Contents; import com.google.zxing.client.android.Contents;
import com.google.zxing.client.android.Intents; import com.google.zxing.client.android.Intents;
@ -450,7 +451,7 @@ public abstract class ResultHandler {
*/ */
final void rawLaunchIntent(Intent intent) { final void rawLaunchIntent(Intent intent) {
if (intent != null) { if (intent != null) {
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); intent.addFlags(Intents.FLAG_NEW_DOC);
Log.d(TAG, "Launching intent: " + intent + " with extras: " + intent.getExtras()); Log.d(TAG, "Launching intent: " + intent + " with extras: " + intent.getExtras());
activity.startActivity(intent); activity.startActivity(intent);
} }
@ -510,4 +511,9 @@ public abstract class ResultHandler {
return url.replace("%s", text); return url.replace("%s", text);
} }
static String formatPhone(String phoneData) {
// Just collect the call to a deprecated method in one place
return PhoneNumberUtils.formatNumber(phoneData);
}
} }

View file

@ -21,7 +21,6 @@ import com.google.zxing.client.result.ParsedResult;
import com.google.zxing.client.result.SMSParsedResult; import com.google.zxing.client.result.SMSParsedResult;
import android.app.Activity; import android.app.Activity;
import android.telephony.PhoneNumberUtils;
/** /**
* Handles SMS addresses, offering a choice of composing a new SMS or MMS message. * Handles SMS addresses, offering a choice of composing a new SMS or MMS message.
@ -69,7 +68,7 @@ public final class SMSResultHandler extends ResultHandler {
String[] rawNumbers = smsResult.getNumbers(); String[] rawNumbers = smsResult.getNumbers();
String[] formattedNumbers = new String[rawNumbers.length]; String[] formattedNumbers = new String[rawNumbers.length];
for (int i = 0; i < rawNumbers.length; i++) { for (int i = 0; i < rawNumbers.length; i++) {
formattedNumbers[i] = PhoneNumberUtils.formatNumber(rawNumbers[i]); formattedNumbers[i] = formatPhone(rawNumbers[i]);
} }
StringBuilder contents = new StringBuilder(50); StringBuilder contents = new StringBuilder(50);
ParsedResult.maybeAppend(formattedNumbers, contents); ParsedResult.maybeAppend(formattedNumbers, contents);

View file

@ -21,7 +21,6 @@ import com.google.zxing.client.result.ParsedResult;
import com.google.zxing.client.result.TelParsedResult; import com.google.zxing.client.result.TelParsedResult;
import android.app.Activity; import android.app.Activity;
import android.telephony.PhoneNumberUtils;
/** /**
* Offers relevant actions for telephone numbers. * Offers relevant actions for telephone numbers.
@ -72,7 +71,7 @@ public final class TelResultHandler extends ResultHandler {
public CharSequence getDisplayContents() { public CharSequence getDisplayContents() {
String contents = getResult().getDisplayResult(); String contents = getResult().getDisplayResult();
contents = contents.replace("\r", ""); contents = contents.replace("\r", "");
return PhoneNumberUtils.formatNumber(contents); return formatPhone(contents);
} }
@Override @Override

View file

@ -22,6 +22,7 @@ import android.os.AsyncTask;
import android.view.View; import android.view.View;
import android.widget.Adapter; import android.widget.Adapter;
import android.widget.ListView; import android.widget.ListView;
import com.google.zxing.client.android.Intents;
import java.util.List; import java.util.List;
@ -55,7 +56,7 @@ public final class AppPickerActivity extends ListActivity {
if (position >= 0 && position < adapter.getCount()) { if (position >= 0 && position < adapter.getCount()) {
String packageName = ((AppInfo) adapter.getItem(position)).getPackageName(); String packageName = ((AppInfo) adapter.getItem(position)).getPackageName();
Intent intent = new Intent(); Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); intent.addFlags(Intents.FLAG_NEW_DOC);
intent.putExtra("url", "market://details?id=" + packageName); // Browser.BookmarkColumns.URL intent.putExtra("url", "market://details?id=" + packageName); // Browser.BookmarkColumns.URL
setResult(RESULT_OK, intent); setResult(RESULT_OK, intent);
} else { } else {

View file

@ -26,6 +26,7 @@ import android.net.Uri;
import android.util.Log; import android.util.Log;
import android.view.View; import android.view.View;
import android.widget.ListView; import android.widget.ListView;
import com.google.zxing.client.android.Intents;
/** /**
* This class is only needed because I can't successfully send an ACTION_PICK intent to * This class is only needed because I can't successfully send an ACTION_PICK intent to
@ -52,19 +53,16 @@ public final class BookmarkPickerActivity extends ListActivity {
protected void onResume() { protected void onResume() {
super.onResume(); super.onResume();
titleURLs.clear(); titleURLs.clear();
Cursor cursor = getContentResolver().query(BOOKMARKS_URI, BOOKMARK_PROJECTION, try (Cursor cursor = getContentResolver().query(BOOKMARKS_URI, BOOKMARK_PROJECTION,
BOOKMARK_SELECTION, null, null); BOOKMARK_SELECTION, null, null)) {
if (cursor == null) { if (cursor == null) {
Log.w(TAG, "No cursor returned for bookmark query"); Log.w(TAG, "No cursor returned for bookmark query");
finish(); finish();
return; return;
} }
try {
while (cursor.moveToNext()) { while (cursor.moveToNext()) {
titleURLs.add(new String[] { cursor.getString(0), cursor.getString(1) }); titleURLs.add(new String[] { cursor.getString(0), cursor.getString(1) });
} }
} finally {
cursor.close();
} }
setListAdapter(new BookmarkAdapter(this, titleURLs)); setListAdapter(new BookmarkAdapter(this, titleURLs));
} }
@ -74,7 +72,7 @@ public final class BookmarkPickerActivity extends ListActivity {
protected void onListItemClick(ListView l, View view, int position, long id) { protected void onListItemClick(ListView l, View view, int position, long id) {
String[] titleURL = titleURLs.get(position); String[] titleURL = titleURLs.get(position);
Intent intent = new Intent(); Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); intent.addFlags(Intents.FLAG_NEW_DOC);
intent.putExtra("title", titleURL[0]); // Browser.BookmarkColumns.TITLE intent.putExtra("title", titleURL[0]); // Browser.BookmarkColumns.TITLE
intent.putExtra("url", titleURL[1]); // Browser.BookmarkColumns.URL intent.putExtra("url", titleURL[1]); // Browser.BookmarkColumns.URL
setResult(RESULT_OK, intent); setResult(RESULT_OK, intent);

View file

@ -56,7 +56,7 @@ public final class ShareActivity extends Activity {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI); Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); intent.addFlags(Intents.FLAG_NEW_DOC);
startActivityForResult(intent, PICK_CONTACT); startActivityForResult(intent, PICK_CONTACT);
} }
}; };
@ -65,7 +65,7 @@ public final class ShareActivity extends Activity {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK); Intent intent = new Intent(Intent.ACTION_PICK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); intent.addFlags(Intents.FLAG_NEW_DOC);
intent.setClassName(ShareActivity.this, BookmarkPickerActivity.class.getName()); intent.setClassName(ShareActivity.this, BookmarkPickerActivity.class.getName());
startActivityForResult(intent, PICK_BOOKMARK); startActivityForResult(intent, PICK_BOOKMARK);
} }
@ -75,7 +75,7 @@ public final class ShareActivity extends Activity {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK); Intent intent = new Intent(Intent.ACTION_PICK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); intent.addFlags(Intents.FLAG_NEW_DOC);
intent.setClassName(ShareActivity.this, AppPickerActivity.class.getName()); intent.setClassName(ShareActivity.this, AppPickerActivity.class.getName());
startActivityForResult(intent, PICK_APP); startActivityForResult(intent, PICK_APP);
} }
@ -108,7 +108,7 @@ public final class ShareActivity extends Activity {
private void launchSearch(String text) { private void launchSearch(String text) {
Intent intent = new Intent(Intents.Encode.ACTION); Intent intent = new Intent(Intents.Encode.ACTION);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); intent.addFlags(Intents.FLAG_NEW_DOC);
intent.putExtra(Intents.Encode.TYPE, Contents.Type.TEXT); intent.putExtra(Intents.Encode.TYPE, Contents.Type.TEXT);
intent.putExtra(Intents.Encode.DATA, text); intent.putExtra(Intents.Encode.DATA, text);
intent.putExtra(Intents.Encode.FORMAT, BarcodeFormat.QR_CODE.toString()); intent.putExtra(Intents.Encode.FORMAT, BarcodeFormat.QR_CODE.toString());
@ -161,7 +161,7 @@ public final class ShareActivity extends Activity {
return; // Show error? return; // Show error?
} }
Intent intent = new Intent(Intents.Encode.ACTION); Intent intent = new Intent(Intents.Encode.ACTION);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); intent.addFlags(Intents.FLAG_NEW_DOC);
intent.putExtra(Intents.Encode.TYPE, Contents.Type.TEXT); intent.putExtra(Intents.Encode.TYPE, Contents.Type.TEXT);
intent.putExtra(Intents.Encode.DATA, text); intent.putExtra(Intents.Encode.DATA, text);
intent.putExtra(Intents.Encode.FORMAT, BarcodeFormat.QR_CODE.toString()); intent.putExtra(Intents.Encode.FORMAT, BarcodeFormat.QR_CODE.toString());
@ -181,32 +181,16 @@ public final class ShareActivity extends Activity {
} }
ContentResolver resolver = getContentResolver(); ContentResolver resolver = getContentResolver();
Cursor cursor;
try {
// We're seeing about six reports a week of this exception although I don't understand why.
cursor = resolver.query(contactUri, null, null, null, null);
} catch (IllegalArgumentException ignored) {
return;
}
if (cursor == null) {
return;
}
String id; String id;
String name; String name;
boolean hasPhone; boolean hasPhone;
try { try (Cursor cursor = resolver.query(contactUri, null, null, null, null)) {
if (!cursor.moveToFirst()) { if (cursor == null || !cursor.moveToFirst()) {
return; return;
} }
id = cursor.getString(cursor.getColumnIndex(BaseColumns._ID)); id = cursor.getString(cursor.getColumnIndex(BaseColumns._ID));
name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
hasPhone = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0; hasPhone = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0;
} finally {
cursor.close();
} }
// Don't require a name to be present, this contact might be just a phone number. // Don't require a name to be present, this contact might be just a phone number.
@ -216,13 +200,12 @@ public final class ShareActivity extends Activity {
} }
if (hasPhone) { if (hasPhone) {
Cursor phonesCursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, try (Cursor phonesCursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + '=' + id, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + '=' + id,
null, null,
null); null)) {
if (phonesCursor != null) { if (phonesCursor != null) {
try {
int foundPhone = 0; int foundPhone = 0;
int phonesNumberColumn = phonesCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER); int phonesNumberColumn = phonesCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
int phoneTypeColumn = phonesCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE); int phoneTypeColumn = phonesCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE);
@ -235,38 +218,30 @@ public final class ShareActivity extends Activity {
bundle.putInt(Contents.PHONE_TYPE_KEYS[foundPhone], type); bundle.putInt(Contents.PHONE_TYPE_KEYS[foundPhone], type);
foundPhone++; foundPhone++;
} }
} finally {
phonesCursor.close();
} }
} }
} }
Cursor methodsCursor = resolver.query(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI, try (Cursor methodsCursor = resolver.query(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI,
null, null,
ContactsContract.CommonDataKinds.StructuredPostal.CONTACT_ID + '=' + id, ContactsContract.CommonDataKinds.StructuredPostal.CONTACT_ID + '=' + id,
null, null,
null); null)) {
if (methodsCursor != null) { if (methodsCursor != null && methodsCursor.moveToNext()) {
try { String data = methodsCursor.getString(
if (methodsCursor.moveToNext()) { methodsCursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS));
String data = methodsCursor.getString( if (data != null && !data.isEmpty()) {
methodsCursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS)); bundle.putString(ContactsContract.Intents.Insert.POSTAL, massageContactData(data));
if (data != null && !data.isEmpty()) {
bundle.putString(ContactsContract.Intents.Insert.POSTAL, massageContactData(data));
}
} }
} finally {
methodsCursor.close();
} }
} }
Cursor emailCursor = resolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, try (Cursor emailCursor = resolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null, null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + '=' + id, ContactsContract.CommonDataKinds.Email.CONTACT_ID + '=' + id,
null, null,
null); null)) {
if (emailCursor != null) { if (emailCursor != null) {
try {
int foundEmail = 0; int foundEmail = 0;
int emailColumn = emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA); int emailColumn = emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA);
while (emailCursor.moveToNext() && foundEmail < Contents.EMAIL_KEYS.length) { while (emailCursor.moveToNext() && foundEmail < Contents.EMAIL_KEYS.length) {
@ -276,13 +251,11 @@ public final class ShareActivity extends Activity {
} }
foundEmail++; foundEmail++;
} }
} finally {
emailCursor.close();
} }
} }
Intent intent = new Intent(Intents.Encode.ACTION); Intent intent = new Intent(Intents.Encode.ACTION);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); intent.addFlags(Intents.FLAG_NEW_DOC);
intent.putExtra(Intents.Encode.TYPE, Contents.Type.CONTACT); intent.putExtra(Intents.Encode.TYPE, Contents.Type.CONTACT);
intent.putExtra(Intents.Encode.DATA, bundle); intent.putExtra(Intents.Encode.DATA, bundle);
intent.putExtra(Intents.Encode.FORMAT, BarcodeFormat.QR_CODE.toString()); intent.putExtra(Intents.Encode.FORMAT, BarcodeFormat.QR_CODE.toString());

View file

@ -26,17 +26,17 @@ enum NetworkType {
if (networkTypeString == null) { if (networkTypeString == null) {
return NO_PASSWORD; return NO_PASSWORD;
} }
if ("WPA".equals(networkTypeString) || switch (networkTypeString) {
"WPA2".equals(networkTypeString)) { case "WPA":
return WPA; case "WPA2":
return WPA;
case "WEP":
return WEP;
case "nopass":
return NO_PASSWORD;
default:
throw new IllegalArgumentException(networkTypeString);
} }
if ("WEP".equals(networkTypeString)) {
return WEP;
}
if ("nopass".equals(networkTypeString)) {
return NO_PASSWORD;
}
throw new IllegalArgumentException(networkTypeString);
} }
} }

View file

@ -24,6 +24,7 @@ import com.google.zxing.aztec.encoder.Encoder;
import com.google.zxing.common.BitMatrix; import com.google.zxing.common.BitMatrix;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Map; import java.util.Map;
/** /**
@ -31,8 +32,6 @@ import java.util.Map;
*/ */
public final class AztecWriter implements Writer { public final class AztecWriter implements Writer {
private static final Charset DEFAULT_CHARSET = Charset.forName("ISO-8859-1");
@Override @Override
public BitMatrix encode(String contents, BarcodeFormat format, int width, int height) { public BitMatrix encode(String contents, BarcodeFormat format, int width, int height) {
return encode(contents, format, width, height, null); return encode(contents, format, width, height, null);
@ -40,7 +39,7 @@ public final class AztecWriter implements Writer {
@Override @Override
public BitMatrix encode(String contents, BarcodeFormat format, int width, int height, Map<EncodeHintType,?> hints) { public BitMatrix encode(String contents, BarcodeFormat format, int width, int height, Map<EncodeHintType,?> hints) {
Charset charset = DEFAULT_CHARSET; Charset charset = StandardCharsets.ISO_8859_1;
int eccPercent = Encoder.DEFAULT_EC_PERCENT; int eccPercent = Encoder.DEFAULT_EC_PERCENT;
int layers = Encoder.DEFAULT_AZTEC_LAYERS; int layers = Encoder.DEFAULT_AZTEC_LAYERS;
if (hints != null) { if (hints != null) {

View file

@ -21,7 +21,7 @@ import com.google.zxing.Result;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.net.URI; import java.net.URI;
import java.nio.charset.Charset; import java.nio.charset.StandardCharsets;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
@ -256,12 +256,12 @@ public final class VCardResultParser extends ResultParser {
byte[] fragmentBytes = fragmentBuffer.toByteArray(); byte[] fragmentBytes = fragmentBuffer.toByteArray();
String fragment; String fragment;
if (charset == null) { if (charset == null) {
fragment = new String(fragmentBytes, Charset.forName("UTF-8")); fragment = new String(fragmentBytes, StandardCharsets.UTF_8);
} else { } else {
try { try {
fragment = new String(fragmentBytes, charset); fragment = new String(fragmentBytes, charset);
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
fragment = new String(fragmentBytes, Charset.forName("UTF-8")); fragment = new String(fragmentBytes, StandardCharsets.UTF_8);
} }
} }
fragmentBuffer.reset(); fragmentBuffer.reset();

View file

@ -18,7 +18,7 @@ package com.google.zxing.datamatrix.encoder;
import com.google.zxing.Dimension; import com.google.zxing.Dimension;
import java.nio.charset.Charset; import java.nio.charset.StandardCharsets;
final class EncoderContext { final class EncoderContext {
@ -34,7 +34,7 @@ final class EncoderContext {
EncoderContext(String msg) { EncoderContext(String msg) {
//From this point on Strings are not Unicode anymore! //From this point on Strings are not Unicode anymore!
byte[] msgBinary = msg.getBytes(Charset.forName("ISO-8859-1")); byte[] msgBinary = msg.getBytes(StandardCharsets.ISO_8859_1);
StringBuilder sb = new StringBuilder(msgBinary.length); StringBuilder sb = new StringBuilder(msgBinary.length);
for (int i = 0, c = msgBinary.length; i < c; i++) { for (int i = 0, c = msgBinary.length; i < c; i++) {
char ch = (char) (msgBinary[i] & 0xff); char ch = (char) (msgBinary[i] & 0xff);

View file

@ -168,13 +168,7 @@ public final class QRCodeMultiReader extends QRCodeReader implements MultipleBar
public int compare(Result a, Result b) { public int compare(Result a, Result b) {
int aNumber = (int) a.getResultMetadata().get(ResultMetadataType.STRUCTURED_APPEND_SEQUENCE); int aNumber = (int) a.getResultMetadata().get(ResultMetadataType.STRUCTURED_APPEND_SEQUENCE);
int bNumber = (int) b.getResultMetadata().get(ResultMetadataType.STRUCTURED_APPEND_SEQUENCE); int bNumber = (int) b.getResultMetadata().get(ResultMetadataType.STRUCTURED_APPEND_SEQUENCE);
if (aNumber < bNumber) { return Integer.compare(aNumber, bNumber);
return -1;
}
if (aNumber > bNumber) {
return 1;
}
return 0;
} }
} }

View file

@ -153,16 +153,15 @@ final class UPCEANExtension5Support {
break; break;
case '9': case '9':
// Reference: http://www.jollytech.com // Reference: http://www.jollytech.com
if ("90000".equals(raw)) { switch (raw) {
// No suggested retail price case "90000":
return null; // No suggested retail price
} return null;
if ("99991".equals(raw)) { case "99991":
// Complementary // Complementary
return "0.00"; return "0.00";
} case "99990":
if ("99990".equals(raw)) { return "Used";
return "Used";
} }
// Otherwise... unknown currency? // Otherwise... unknown currency?
currency = ""; currency = "";

View file

@ -24,6 +24,7 @@ import com.google.zxing.pdf417.PDF417ResultMetadata;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.math.BigInteger; import java.math.BigInteger;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays; import java.util.Arrays;
/** /**
@ -70,8 +71,6 @@ final class DecodedBitStreamParser {
private static final char[] MIXED_CHARS = private static final char[] MIXED_CHARS =
"0123456789&\r\t,:#-.$/+%*=^".toCharArray(); "0123456789&\r\t,:#-.$/+%*=^".toCharArray();
private static final Charset DEFAULT_ENCODING = Charset.forName("ISO-8859-1");
/** /**
* Table containing values for the exponent of 900. * Table containing values for the exponent of 900.
* This is used in the numeric compaction decode algorithm. * This is used in the numeric compaction decode algorithm.
@ -94,7 +93,7 @@ final class DecodedBitStreamParser {
static DecoderResult decode(int[] codewords, String ecLevel) throws FormatException { static DecoderResult decode(int[] codewords, String ecLevel) throws FormatException {
StringBuilder result = new StringBuilder(codewords.length * 2); StringBuilder result = new StringBuilder(codewords.length * 2);
Charset encoding = DEFAULT_ENCODING; Charset encoding = StandardCharsets.ISO_8859_1;
// Get compaction mode // Get compaction mode
int codeIndex = 1; int codeIndex = 1;
int code = codewords[codeIndex++]; int code = codewords[codeIndex++];

View file

@ -271,26 +271,25 @@ final class DetectionResult {
if (rowIndicatorColumn == null) { if (rowIndicatorColumn == null) {
rowIndicatorColumn = detectionResultColumns[barcodeColumnCount + 1]; rowIndicatorColumn = detectionResultColumns[barcodeColumnCount + 1];
} }
Formatter formatter = new Formatter(); try (Formatter formatter = new Formatter()) {
for (int codewordsRow = 0; codewordsRow < rowIndicatorColumn.getCodewords().length; codewordsRow++) { for (int codewordsRow = 0; codewordsRow < rowIndicatorColumn.getCodewords().length; codewordsRow++) {
formatter.format("CW %3d:", codewordsRow); formatter.format("CW %3d:", codewordsRow);
for (int barcodeColumn = 0; barcodeColumn < barcodeColumnCount + 2; barcodeColumn++) { for (int barcodeColumn = 0; barcodeColumn < barcodeColumnCount + 2; barcodeColumn++) {
if (detectionResultColumns[barcodeColumn] == null) { if (detectionResultColumns[barcodeColumn] == null) {
formatter.format(" | "); formatter.format(" | ");
continue; continue;
}
Codeword codeword = detectionResultColumns[barcodeColumn].getCodewords()[codewordsRow];
if (codeword == null) {
formatter.format(" | ");
continue;
}
formatter.format(" %3d|%3d", codeword.getRowNumber(), codeword.getValue());
} }
Codeword codeword = detectionResultColumns[barcodeColumn].getCodewords()[codewordsRow]; formatter.format("%n");
if (codeword == null) {
formatter.format(" | ");
continue;
}
formatter.format(" %3d|%3d", codeword.getRowNumber(), codeword.getValue());
} }
formatter.format("%n"); return formatter.toString();
} }
String result = formatter.toString();
formatter.close();
return result;
} }
} }

View file

@ -79,18 +79,17 @@ class DetectionResultColumn {
@Override @Override
public String toString() { public String toString() {
Formatter formatter = new Formatter(); try (Formatter formatter = new Formatter()) {
int row = 0; int row = 0;
for (Codeword codeword : codewords) { for (Codeword codeword : codewords) {
if (codeword == null) { if (codeword == null) {
formatter.format("%3d: | %n", row++); formatter.format("%3d: | %n", row++);
continue; continue;
}
formatter.format("%3d: %3d|%3d%n", row++, codeword.getRowNumber(), codeword.getValue());
} }
formatter.format("%3d: %3d|%3d%n", row++, codeword.getRowNumber(), codeword.getValue()); return formatter.toString();
} }
String result = formatter.toString();
formatter.close();
return result;
} }
} }

View file

@ -610,23 +610,22 @@ public final class PDF417ScanningDecoder {
} }
public static String toString(BarcodeValue[][] barcodeMatrix) { public static String toString(BarcodeValue[][] barcodeMatrix) {
Formatter formatter = new Formatter(); try (Formatter formatter = new Formatter()) {
for (int row = 0; row < barcodeMatrix.length; row++) { for (int row = 0; row < barcodeMatrix.length; row++) {
formatter.format("Row %2d: ", row); formatter.format("Row %2d: ", row);
for (int column = 0; column < barcodeMatrix[row].length; column++) { for (int column = 0; column < barcodeMatrix[row].length; column++) {
BarcodeValue barcodeValue = barcodeMatrix[row][column]; BarcodeValue barcodeValue = barcodeMatrix[row][column];
if (barcodeValue.getValue().length == 0) { if (barcodeValue.getValue().length == 0) {
formatter.format(" ", (Object[]) null); formatter.format(" ", (Object[]) null);
} else { } else {
formatter.format("%4d(%2d)", barcodeValue.getValue()[0], formatter.format("%4d(%2d)", barcodeValue.getValue()[0],
barcodeValue.getConfidence(barcodeValue.getValue()[0])); barcodeValue.getConfidence(barcodeValue.getValue()[0]));
}
} }
formatter.format("%n");
} }
formatter.format("%n"); return formatter.toString();
} }
String result = formatter.toString();
formatter.close();
return result;
} }
} }

View file

@ -26,6 +26,7 @@ import com.google.zxing.common.CharacterSetECI;
import java.math.BigInteger; import java.math.BigInteger;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder; import java.nio.charset.CharsetEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays; import java.util.Arrays;
/** /**
@ -126,7 +127,7 @@ final class PDF417HighLevelEncoder {
private static final byte[] MIXED = new byte[128]; private static final byte[] MIXED = new byte[128];
private static final byte[] PUNCTUATION = new byte[128]; private static final byte[] PUNCTUATION = new byte[128];
private static final Charset DEFAULT_ENCODING = Charset.forName("ISO-8859-1"); private static final Charset DEFAULT_ENCODING = StandardCharsets.ISO_8859_1;
private PDF417HighLevelEncoder() { private PDF417HighLevelEncoder() {
} }

View file

@ -651,9 +651,8 @@ public class FinderPatternFinder {
} }
@Override @Override
public int compare(FinderPattern center1, FinderPattern center2) { public int compare(FinderPattern center1, FinderPattern center2) {
float dA = Math.abs(center2.getEstimatedModuleSize() - average); return Float.compare(Math.abs(center2.getEstimatedModuleSize() - average),
float dB = Math.abs(center1.getEstimatedModuleSize() - average); Math.abs(center1.getEstimatedModuleSize() - average));
return dA < dB ? -1 : dA > dB ? 1 : 0;
} }
} }
@ -667,13 +666,12 @@ public class FinderPatternFinder {
} }
@Override @Override
public int compare(FinderPattern center1, FinderPattern center2) { public int compare(FinderPattern center1, FinderPattern center2) {
if (center2.getCount() == center1.getCount()) { int countCompare = Integer.compare(center2.getCount(), center1.getCount());
float dA = Math.abs(center2.getEstimatedModuleSize() - average); if (countCompare == 0) {
float dB = Math.abs(center1.getEstimatedModuleSize() - average); return Float.compare(Math.abs(center1.getEstimatedModuleSize() - average),
return dA < dB ? 1 : dA > dB ? -1 : 0; Math.abs(center2.getEstimatedModuleSize() - average));
} else {
return center2.getCount() - center1.getCount();
} }
return countCompare;
} }
} }