Skip to content

Commit

Permalink
fix(android): code optimizations (#13605)
Browse files Browse the repository at this point in the history
* fix(android): code optimizations

* tableview null check
  • Loading branch information
m1ga authored Dec 23, 2022
1 parent 80fafef commit a16d76c
Show file tree
Hide file tree
Showing 27 changed files with 72 additions and 100 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -338,9 +338,7 @@ public boolean visit(AnnotationMirror annotation, Object arg)
proxyProperties.put("proxyAttrs", proxyAttrs);

if (isModule) {
StringBuilder b = new StringBuilder();
b.append(packageName).append(".").append(proxyClassName);
Map<Object, Object> module = getModule(b.toString());
Map<Object, Object> module = getModule(packageName + "." + proxyClassName);
module.put("apiName", apiName);
}

Expand Down Expand Up @@ -509,7 +507,7 @@ protected void visitDynamicProperty(AnnotationMirror annotation, ExecutableEleme
Map<Object, Object> dynamicProperty = new HashMap<>(params);

String methodName = utils.getName(element);
String defaultName = new String(methodName);
String defaultName = methodName;
if (defaultName.startsWith("get") || defaultName.startsWith("set")) {
defaultName = Character.toLowerCase(defaultName.charAt(3)) + defaultName.substring(4);
} else if (defaultName.startsWith("is")) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@
import android.content.Intent;
import android.os.Bundle;

@SuppressWarnings("deprecation")
public class TiJSIntervalService extends TiJSService
{
private static final String TAG = "TiJSIntervalService";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ public String generateRRULEString()
weeklyRecurrencesString.append(",");
}
}
finalRRule.append(weeklyRecurrencesString.toString());
finalRRule.append(weeklyRecurrencesString);
finalRRule.append(";");
break;
case MONTHLY:
Expand Down Expand Up @@ -202,14 +202,14 @@ private void fillFrequencyFields()
days = matchExpression(".*(BYYEARDAY=[0-9]*).*", 10);
if (days != null) {
//daysOfTheYear
this.daysOfTheYear = new int[] { Integer.valueOf(days) };
this.daysOfTheYear = new int[] { Integer.parseInt(days) };
}
break;
case MONTHLY:
//daysOfTheMonth
days = matchExpression(".*(BYMONTHDAY=(-)*[0-9]*).*", 11);
if (days != null) {
this.daysOfTheMonth = new int[] { Integer.valueOf(days) };
this.daysOfTheMonth = new int[] { Integer.parseInt(days) };
}
//daysOfTheWeek
byDay = matchExpression(".*(BYDAY=[,0-9A-Z]*).*", 6);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ private Object internalGetFieldByName(String fieldName, int type)
try {
Integer ndx = columnNames.get(fieldName.toLowerCase());
if (ndx != null)
result = internalGetField(ndx.intValue(), type);
result = internalGetField(ndx, type);
} catch (SQLException e) {
String msg = "Field name " + fieldName + " not found. msg=" + e.getMessage();
Log.e(TAG, msg);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ public TiDeviceOrientationMonitor(Handler handler)
if (value instanceof SensorManager) {
this.sensorManager = (SensorManager) value;
} else {
Log.i(TAG, "Unable to aquire SensorManager.");
Log.w(TAG, "Unable to aquire SensorManager.");
}

// Create an event handler for the Android "OrientationEventListener".
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -152,24 +152,23 @@ public void handleCreationDict(KrollDict properties)
if (hasCustomDateSettings || hasCustomTimeSettings) {
try {
// Generate a "skeleton" pattern without any separators using given options.
StringBuilder stringBuilder = new StringBuilder(32);
stringBuilder.append(getPatternForWeekdayId(weekdayFormatId));
stringBuilder.append(getPatternForYearId(yearFormatId));
stringBuilder.append(getPatternForMonthId(monthFormatId));
stringBuilder.append(getPatternForDayId(dayFormatId));
stringBuilder.append(getPatternForEraId(eraFormatId));
stringBuilder.append(getPatternForHourId(hourFormatId, hourCycleFormatId));
stringBuilder.append(getPatternForMinuteId(minuteFormatId));
stringBuilder.append(getPatternForSecondId(secondFormatId));
stringBuilder.append(getPatternForMillisecondDigits(millisecondDigits));
stringBuilder.append(getPatternForDayPeriodId(dayPeriodFormatId));
stringBuilder.append(getPatternForTimeZoneId(timeZoneFormatId));
String stringBuilder = getPatternForWeekdayId(weekdayFormatId)
+ getPatternForYearId(yearFormatId)
+ getPatternForMonthId(monthFormatId)
+ getPatternForDayId(dayFormatId)
+ getPatternForEraId(eraFormatId)
+ getPatternForHourId(hourFormatId, hourCycleFormatId)
+ getPatternForMinuteId(minuteFormatId)
+ getPatternForSecondId(secondFormatId)
+ getPatternForMillisecondDigits(millisecondDigits)
+ getPatternForDayPeriodId(dayPeriodFormatId)
+ getPatternForTimeZoneId(timeZoneFormatId);

// Have Android generate a localized date/time pattern string from above skeleton pattern.
// This will inject needed separators and auto-swap components like month/day according to locale.
// Note: Android 8 sometimes inserts invalid pattern char 'b' for AM/PM. Should be 'a' instead.
String datePattern = android.text.format.DateFormat.getBestDateTimePattern(
locale, stringBuilder.toString());
locale, stringBuilder);
datePattern = datePattern.replace('b', 'a');
this.dateFormat = new SimpleDateFormat(datePattern, locale);
} catch (Exception ex) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ protected void measureVideo(int videoWidth, int videoHeight, int widthMeasureSpe
}
constantDeprecationWarning(mScalingMode);
}
Log.i(TAG, "setting size: " + width + 'x' + height, Log.DEBUG_MODE);
Log.d(TAG, "setting size: " + width + 'x' + height, Log.DEBUG_MODE);
setMeasuredDimension(width, height);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ public String stopRecording()
totalFileBytes - WAV_FILE_HEADER_RIFF_SUBCHUNK_BYTE_COUNT,
RECORDER_SAMPLE_RATE,
channelCount,
RECORDER_BPP * RECORDER_SAMPLE_RATE * channelCount / 8);
(long) RECORDER_BPP * RECORDER_SAMPLE_RATE * channelCount / 8);
resultFile = this.tempFileReference;
}
} catch (Exception ex) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public class TiCamera
public TiCamera()
{
if (camera == null) {
Log.i(TAG, "Camera created.", Log.DEBUG_MODE);
Log.d(TAG, "Camera created.", Log.DEBUG_MODE);
camera = Camera.open();
}
}
Expand All @@ -40,15 +40,15 @@ public Camera getCamera()
ShutterCallback shutterCallback = new ShutterCallback() {
public void onShutter()
{
Log.i(TAG, "onShutter() called. Capturing image.", Log.DEBUG_MODE);
Log.d(TAG, "onShutter() called. Capturing image.", Log.DEBUG_MODE);
}
};

// need the callback but we don't want to do anything with this currently
PictureCallback rawCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera)
{
Log.i(TAG, "Picture taken: raw picture available", Log.DEBUG_MODE);
Log.d(TAG, "Picture taken: raw picture available", Log.DEBUG_MODE);
}
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -555,12 +555,10 @@ public void onBufferingUpdate(MediaPlayer mp, int percent)

private void startProgressTimer()
{
if (progressTimer == null) {
progressTimer = new Timer(true);
} else {
if (progressTimer != null) {
progressTimer.cancel();
progressTimer = new Timer(true);
}
progressTimer = new Timer(true);

progressTimer.schedule(new TimerTask() {
@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);

Log.i(TAG, "TiVideoActivity onCreate", Log.DEBUG_MODE);
Log.d(TAG, "TiVideoActivity onCreate", Log.DEBUG_MODE);

final Intent intent = getIntent();

Expand All @@ -67,7 +67,7 @@ protected void onCreate(Bundle savedInstanceState)
}
}

Log.i(TAG, "exiting onCreate", Log.DEBUG_MODE);
Log.d(TAG, "exiting onCreate", Log.DEBUG_MODE);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -537,7 +537,7 @@ public void onRequestPermissionsResult(
@NonNull String[] permissions, @NonNull int[] grantResults)
{
Boolean isGranted = grantResults[0] == PackageManager.PERMISSION_GRANTED;

KrollDict event = new KrollDict();
event.put("success", isGranted);
event.put("type", "remote");
Expand Down Expand Up @@ -753,7 +753,7 @@ private boolean stringEqual(String s1, String s2, boolean isCaseSensitive)
return true;
}
if (s1 != null && s2 != null) {
if ((isCaseSensitive && s1.equals(s2)) || (!isCaseSensitive && s1.toLowerCase().equals(s2.toLowerCase()))) {
if ((isCaseSensitive && s1.equals(s2)) || (!isCaseSensitive && s1.equalsIgnoreCase(s2))) {
return true;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -946,7 +946,7 @@ public void open(String method, String url)
setRequestHeader("X-Requested-With", "XMLHttpRequest");

} else {
Log.i(TAG, "Twitter: not sending X-Requested-With header", Log.DEBUG_MODE);
Log.d(TAG, "Twitter: not sending X-Requested-With header", Log.DEBUG_MODE);
}
}

Expand Down Expand Up @@ -1517,7 +1517,7 @@ private void addFilePart(String name, ContentBody contentBody) throws IOExceptio

public void completeSendingMultipart()
{
printWriter.append("--" + boundary + "--").append(LINE_FEED);
printWriter.append("--").append(boundary).append("--").append(LINE_FEED);
}

private void handleURLEncodedData(UrlEncodedFormEntity form) throws IOException
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -574,7 +574,7 @@ public void onResume(Activity activity)
{
super.onResume(activity);
if (batteryStateReceiver != null) {
Log.i(TAG, "Reregistering battery changed receiver", Log.DEBUG_MODE);
Log.d(TAG, "Reregistering battery changed receiver", Log.DEBUG_MODE);
registerBatteryReceiver(batteryStateReceiver);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -379,7 +379,7 @@ public void onPropertyChanged(String name, Object value)
for (final WeakReference ref : clones) {
final TableViewRowProxy clone = (TableViewRowProxy) ref.get();

if (ref != null) {
if (ref != null && clone != null) {
clone.onPropertyChanged(name, value);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,13 +49,12 @@ private void configureDrawable()
path.moveTo(0.0f, 1.0f);
path.lineTo(1.0f, 2.0f);
path.lineTo(1.0f, 0.0f);
path.close();
} else {
path.lineTo(1.0f, 1.0f);
path.lineTo(0.0f, 2.0f);
path.lineTo(0.0f, 0.0f);
path.close();
}
path.close();

setWillNotDraw(false);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -301,7 +301,7 @@ public void run()
}
if (paused && !Thread.currentThread().isInterrupted()) {
try {
Log.i(TAG, "Pausing", Log.DEBUG_MODE);
Log.d(TAG, "Pausing", Log.DEBUG_MODE);
// User backed-out while animation running
if (loader == null) {
break;
Expand All @@ -312,7 +312,7 @@ public void run()
wait();
}

Log.i(TAG, "Waking from pause.", Log.DEBUG_MODE);
Log.d(TAG, "Waking from pause.", Log.DEBUG_MODE);
// In the meantime, while paused, user could have backed out, which leads
// to release(), which in turn leads to nullified imageSources.
if (imageSources == null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -443,12 +443,9 @@ private void setPageCacheSize(int value)
{
// Do not allow given size to be less than min. (iOS min size is 3.)
if (value < ScrollableViewProxy.MIN_CACHE_SIZE) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("ScrollableView 'cacheSize' cannot be set less than ");
stringBuilder.append(ScrollableViewProxy.MIN_CACHE_SIZE);
stringBuilder.append(". Given value: ");
stringBuilder.append(value);
Log.w(TAG, stringBuilder.toString());
String stringBuilder = "ScrollableView 'cacheSize' cannot be set less than "
+ ScrollableViewProxy.MIN_CACHE_SIZE + ". Given value: " + value;
Log.w(TAG, stringBuilder);
value = ScrollableViewProxy.MIN_CACHE_SIZE;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,8 @@ public void appendItems(Object dataItems, @Kroll.argument(optional = true) Kroll
{
final List<ListItemProxy> items = processItems(dataItems);

for (final ListItemProxy item : items) {

// Add to current items.
this.items.add(item);
}
// Add to current items.
this.items.addAll(items);

// Notify ListView of new items.
update();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -566,7 +566,6 @@ public Drawable updateIconTint(TiViewProxy tabProxy, Drawable drawable, boolean
properties.getString(TiC.PROPERTY_ACTIVE_TINT_COLOR));
color = TiColorHelper.parseColor(colorString, activity);
}
drawable.setColorFilter(color, PorterDuff.Mode.SRC_IN);
} else {
color = ColorUtils.setAlphaComponent(this.colorOnSurfaceInt, 153); // 60% opacity
if (tabProperties.containsKeyAndNotNull(TiC.PROPERTY_TINT_COLOR)
Expand All @@ -575,9 +574,8 @@ public Drawable updateIconTint(TiViewProxy tabProxy, Drawable drawable, boolean
properties.getString(TiC.PROPERTY_TINT_COLOR));
color = TiColorHelper.parseColor(colorString, activity);
}
drawable.setColorFilter(color, PorterDuff.Mode.SRC_IN);
}

drawable.setColorFilter(color, PorterDuff.Mode.SRC_IN);
return drawable;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -170,17 +170,17 @@ public boolean shouldOverrideUrlLoading(final WebView view, String url)
proxy.setPropertyAndFire(TiC.PROPERTY_URL, url);
return true;
} else if (url.startsWith(WebView.SCHEME_TEL)) {
Log.i(TAG, "Launching dialer for " + url, Log.DEBUG_MODE);
Log.d(TAG, "Launching dialer for " + url, Log.DEBUG_MODE);
Intent dialer = Intent.createChooser(new Intent(Intent.ACTION_DIAL, Uri.parse(url)), "Choose Dialer");
proxy.getActivity().startActivity(dialer);
return true;
} else if (url.startsWith(WebView.SCHEME_MAILTO)) {
Log.i(TAG, "Launching mailer for " + url, Log.DEBUG_MODE);
Log.d(TAG, "Launching mailer for " + url, Log.DEBUG_MODE);
Intent mailer = Intent.createChooser(new Intent(Intent.ACTION_SENDTO, Uri.parse(url)), "Send Message");
proxy.getActivity().startActivity(mailer);
return true;
} else if (url.startsWith(WebView.SCHEME_GEO)) {
Log.i(TAG, "Launching app for " + url, Log.DEBUG_MODE);
Log.d(TAG, "Launching app for " + url, Log.DEBUG_MODE);
/*geo:latitude,longitude
geo:latitude,longitude?z=zoom
geo:0,0?q=my+street+address
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1074,7 +1074,7 @@ public void onPropertyChanged(String name, Object value)
Object newValue = value;

if (isLocaleProperty(name)) {
Log.i(TAG, "Updating locale: " + name, Log.DEBUG_MODE);
Log.d(TAG, "Updating locale: " + name, Log.DEBUG_MODE);
Pair<String, String> update = updateLocaleProperty(name, TiConvert.toString(value));
if (update != null) {
propertyName = update.first;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -657,7 +657,7 @@ public TiBlob imageAsResized(Number width, Number height)
int scaleWidth = imgWidth / dstWidth;
int scaleHeight = imgHeight / dstHeight;

int targetScale = (scaleWidth < scaleHeight) ? scaleWidth : scaleHeight;
int targetScale = Math.min(scaleWidth, scaleHeight);
int sampleSize = 1;
while (targetScale >= 2) {
sampleSize *= 2;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -225,13 +225,13 @@ public static boolean isLocationEnabled()

List<String> providers = getLocationManager().getProviders(true);
if (providers != null && providers.size() > 0) {
Log.i(TAG, "Enabled location provider count: " + providers.size(), Log.DEBUG_MODE);
Log.d(TAG, "Enabled location provider count: " + providers.size(), Log.DEBUG_MODE);
for (String name : providers) {
Log.i(TAG, "Location [" + name + "] service available", Log.DEBUG_MODE);
Log.d(TAG, "Location [" + name + "] service available", Log.DEBUG_MODE);
}
enabled = true;
} else {
Log.i(TAG, "No available providers", Log.DEBUG_MODE);
Log.d(TAG, "No available providers", Log.DEBUG_MODE);
}

return enabled;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -435,7 +435,7 @@ private static Typeface loadTypeface(Context context, String fontFamily)
try {
String[] fontFiles = mgr.list(customFontPath);
for (String f : fontFiles) {
if (f.toLowerCase().equals(fontFamily.toLowerCase())
if (f.equalsIgnoreCase(fontFamily)
|| f.toLowerCase().startsWith(fontFamily.toLowerCase() + ".")) {
Typeface tf = Typeface.createFromAsset(mgr, customFontPath + "/" + f);
synchronized (mCustomTypeFaces)
Expand Down Expand Up @@ -852,7 +852,7 @@ public static KrollDict viewToImage(KrollDict proxyDict, View view)
}

if (view.getParent() == null) {
Log.i(TAG, "View does not have parent, calling layout", Log.DEBUG_MODE);
Log.d(TAG, "View does not have parent, calling layout", Log.DEBUG_MODE);
view.layout(0, 0, width, height);
}

Expand Down
Loading

0 comments on commit a16d76c

Please sign in to comment.