Miscellaneous code cleanup

pull/542/head
TacoTheDank 6 years ago
parent 895d66b663
commit abd403fecf

@ -1,2 +1 @@
<manifest package="org.isoron.androidbase"
xmlns:android="http://schemas.android.com/apk/res/android"/>
<manifest package="org.isoron.androidbase" />

@ -44,8 +44,8 @@ public class AndroidDirFinder
@Nullable
public File getFilesDir(@Nullable String relativePath)
{
File externalFilesDirs[] =
ContextCompat.getExternalFilesDirs(context, null);
File[] externalFilesDirs =
ContextCompat.getExternalFilesDirs(context, null);
if (externalFilesDirs == null)
{
Log.e("BaseSystem",

@ -22,8 +22,6 @@ package org.isoron.androidbase;
import android.content.*;
import android.support.annotation.*;
import org.isoron.androidbase.*;
import java.io.*;
import java.security.*;
import java.security.cert.Certificate;

@ -68,7 +68,7 @@ public abstract class BaseRootView extends FrameLayout
@NonNull
public Toolbar getToolbar()
{
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
Toolbar toolbar = findViewById(R.id.toolbar);
if (toolbar == null) throw new RuntimeException(
"Your BaseRootView should have a " +
"toolbar with id R.id.toolbar");

@ -26,7 +26,6 @@ import android.net.*;
import android.os.*;
import android.support.annotation.*;
import android.support.design.widget.*;
import android.support.v4.content.res.*;
import android.support.v7.app.*;
import android.support.v7.view.ActionMode;
import android.support.v7.widget.Toolbar;
@ -69,16 +68,8 @@ public class BaseScreen
@Deprecated
public static int getDefaultActionBarColor(Context context)
{
if (SDK_INT < LOLLIPOP)
{
return ResourcesCompat.getColor(context.getResources(),
R.color.grey_900, context.getTheme());
}
else
{
StyledResources res = new StyledResources(context);
return res.getColor(R.attr.colorPrimary);
}
StyledResources res = new StyledResources(context);
return res.getColor(R.attr.colorPrimary);
}
@Deprecated
@ -86,7 +77,7 @@ public class BaseScreen
int color)
{
Toolbar toolbar = (Toolbar) activity.findViewById(R.id.toolbar);
Toolbar toolbar = activity.findViewById(R.id.toolbar);
if (toolbar == null) return;
activity.setSupportActionBar(toolbar);
@ -151,7 +142,6 @@ public class BaseScreen
* @param resultCode the result code sent by the other activity.
* @param data an Intent containing extra data sent by the other
* activity.
* @see {@link android.app.Activity#onActivityResult(int, int, Intent)}
*/
public void onResult(int requestCode, int resultCode, Intent data)
{
@ -215,7 +205,7 @@ public class BaseScreen
{
snackbar = Snackbar.make(rootView, stringId, Snackbar.LENGTH_SHORT);
int tvId = android.support.design.R.id.snackbar_text;
TextView tv = (TextView) snackbar.getView().findViewById(tvId);
TextView tv = snackbar.getView().findViewById(tvId);
tv.setTextColor(Color.WHITE);
}
else snackbar.setText(stringId);
@ -270,8 +260,6 @@ public class BaseScreen
private void setStatusBarColor(int baseColor)
{
if (SDK_INT < LOLLIPOP) return;
int darkerColor = ColorUtils.mixColors(baseColor, Color.BLACK, 0.75f);
activity.getWindow().setStatusBarColor(darkerColor);
}

@ -57,7 +57,7 @@ public abstract class ColorUtils
public static int setMinValue(int color, float newValue)
{
float hsv[] = new float[3];
float[] hsv = new float[3];
Color.colorToHSV(color, hsv);
hsv[2] = Math.max(hsv[2], newValue);
return Color.HSVToColor(hsv);

@ -50,7 +50,7 @@ public abstract class FileUtils
}
@Nullable
public static File getDir(@NonNull File potentialParentDirs[],
public static File getDir(@NonNull File[] potentialParentDirs,
@Nullable String relativePath)
{
if (relativePath == null) relativePath = "";
@ -85,8 +85,8 @@ public abstract class FileUtils
@Nullable
public static File getSDCardDir(@Nullable String relativePath)
{
File parents[] =
new File[]{ Environment.getExternalStorageDirectory() };
File[] parents =
new File[]{Environment.getExternalStorageDirectory()};
return getDir(parents, relativePath);
}
}

@ -1,2 +1 @@
<manifest package="com.android"
xmlns:android="http://schemas.android.com/apk/res/android"/>
<manifest package="com.android" />

@ -56,6 +56,10 @@ android {
sourceCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = "1.8"
}
testOptions {
unitTests.all {
testLogging {

@ -70,7 +70,7 @@ class HabitsApplication : Application() {
notificationTray.startListening()
val prefs = component.preferences
prefs.setLastAppVersion(BuildConfig.VERSION_CODE)
prefs.lastAppVersion = BuildConfig.VERSION_CODE
val taskRunner = component.taskRunner
taskRunner.execute {
@ -93,11 +93,11 @@ class HabitsApplication : Application() {
lateinit var component: HabitsApplicationComponent
fun isTestMode(): Boolean {
try {
return try {
Class.forName("org.isoron.uhabits.BaseAndroidTest")
return true
true
} catch (e: ClassNotFoundException) {
return false
false
}
}
}

@ -36,12 +36,12 @@ class AndroidThemeSwitcher
) : ThemeSwitcher(preferences) {
override fun getSystemTheme(): Int {
if(SDK_INT < 29) return THEME_LIGHT;
if(SDK_INT < 29) return THEME_LIGHT
val uiMode = activity.resources.configuration.uiMode
return if ((uiMode and UI_MODE_NIGHT_MASK) == UI_MODE_NIGHT_YES) {
THEME_DARK;
THEME_DARK
} else {
THEME_LIGHT;
THEME_LIGHT
}
}

@ -50,8 +50,7 @@ abstract class HabitsActivity : BaseActivity() {
private fun getHabitFromIntent(habitList: HabitList): Habit? {
val data = intent.data ?: return null
val habit = habitList.getById(ContentUris.parseId(data))
return habitList.getById(ContentUris.parseId(data))
?: throw RuntimeException("habit not found")
return habit
}
}

@ -27,19 +27,19 @@ import org.isoron.uhabits.activities.common.dialogs.*
import org.isoron.uhabits.activities.habits.list.*
import org.isoron.uhabits.activities.habits.list.views.*
import org.isoron.uhabits.activities.habits.show.*
import org.isoron.uhabits.core.ui.*
import org.isoron.uhabits.core.ui.screens.habits.list.*
@ActivityScope
@Component(modules = arrayOf(
ActivityContextModule::class,
BaseActivityModule::class,
AboutModule::class,
HabitsActivityModule::class,
ListHabitsModule::class,
ShowHabitModule::class,
HabitModule::class
), dependencies = arrayOf(HabitsApplicationComponent::class))
@Component(modules = [
ActivityContextModule::class,
BaseActivityModule::class,
AboutModule::class,
HabitsActivityModule::class,
ListHabitsModule::class,
ShowHabitModule::class,
HabitModule::class
], dependencies = [HabitsApplicationComponent::class])
interface HabitsActivityComponent {
val aboutRootView: AboutRootView
val aboutScreen: AboutScreen

@ -48,12 +48,8 @@ public class HistoryEditorDialog extends AppCompatDialogFragment
@NonNull
private Controller controller;
private HabitList habitList;
private TaskRunner taskRunner;
private Preferences prefs;
public HistoryEditorDialog()
{
this.controller = new Controller() {};
@ -73,9 +69,9 @@ public class HistoryEditorDialog extends AppCompatDialogFragment
HabitsApplication app =
(HabitsApplication) getActivity().getApplicationContext();
habitList = app.getComponent().getHabitList();
HabitList habitList = app.getComponent().getHabitList();
taskRunner = app.getComponent().getTaskRunner();
prefs = app.getComponent().getPreferences();
Preferences prefs = app.getComponent().getPreferences();
historyChart = new HistoryChart(context);
historyChart.setController(controller);

@ -30,6 +30,7 @@ import org.isoron.androidbase.utils.*
import org.isoron.uhabits.*
import org.isoron.uhabits.core.ui.screens.habits.list.*
import javax.inject.*
import kotlin.math.*
class NumberPickerFactory
@Inject constructor(
@ -46,7 +47,7 @@ class NumberPickerFactory
val picker2 = view.findViewById<NumberPicker>(R.id.picker2)
val tvUnit = view.findViewById<TextView>(R.id.tvUnit)
val intValue = Math.round(value * 100).toInt()
val intValue = (value * 100).roundToInt()
picker.minValue = 0
picker.maxValue = Integer.MAX_VALUE / 100

@ -83,9 +83,7 @@ public class WeekdayPickerDialog extends AppCompatDialogFragment implements
selectedDays,
this)
.setPositiveButton(android.R.string.yes, this)
.setNegativeButton(android.R.string.cancel, (dialog, which) -> {
dismiss();
});
.setNegativeButton(android.R.string.cancel, (dialog, which) -> dismiss());
return builder.create();
}

@ -21,8 +21,9 @@ package org.isoron.uhabits.activities.common.views;
import android.os.*;
import android.support.v4.os.*;
import android.support.v4.view.*;
public class BundleSavedState extends android.support.v4.view.AbsSavedState
public class BundleSavedState extends AbsSavedState
{
public static final Parcelable.Creator<BundleSavedState> CREATOR =
ParcelableCompat.newCreator(

@ -335,7 +335,7 @@ public class FrequencyChart extends ScrollableChart
for (int i = 0; i < 40; i++)
{
Integer values[] = new Integer[7];
Integer[] values = new Integer[7];
for (int j = 0; j < 7; j++)
values[j] = rand.nextInt(5);

@ -71,7 +71,7 @@ public class HistoryChart extends ScrollableChart
*/
private int todayPositionInColumn;
private int colors[];
private int[] colors;
private RectF baseLocation;

@ -40,8 +40,6 @@ public class StreakChart extends View
{
private Paint paint;
private long minLength;
private long maxLength;
private int[] colors;
@ -274,7 +272,7 @@ public class StreakChart extends View
private void updateMaxMinLengths()
{
maxLength = 0;
minLength = Long.MAX_VALUE;
long minLength = Long.MAX_VALUE;
shouldShowLabels = true;
for (Streak s : streaks)

@ -52,10 +52,9 @@ class TaskProgressBar(
super.onDetachedFromWindow()
}
fun update() {
private fun update() {
val callback = {
val activeTaskCount = runner.activeTaskCount
val newVisibility = when (activeTaskCount) {
val newVisibility = when (runner.activeTaskCount) {
0 -> GONE
else -> VISIBLE
}

@ -132,7 +132,7 @@ public class EditHabitDialog extends AppCompatDialogFragment
if (originalHabit != null) return R.string.edit_habit;
else return R.string.create_habit;
}
//TODO: Fix unresolved "create" methods
protected void saveHabit(@NonNull Habit habit)
{
if (originalHabit == null)

@ -21,10 +21,10 @@ package org.isoron.uhabits.activities.habits.edit.views;
import android.content.*;
import android.support.annotation.*;
import android.support.v7.widget.*;
import android.text.*;
import android.util.*;
import android.view.*;
import android.widget.*;
import org.isoron.androidbase.utils.*;
import org.isoron.uhabits.*;
@ -35,7 +35,7 @@ import static org.isoron.uhabits.utils.AttributeSetUtils.*;
* An EditText that shows an example usage when there is no text
* currently set. The example disappears when the widget gains focus.
*/
public class ExampleEditText extends EditText
public class ExampleEditText extends AppCompatEditText
implements View.OnFocusChangeListener
{

@ -91,8 +91,8 @@ public class FrequencyPanel extends FrameLayout
public void onFrequencySelected(int position)
{
if (position < 0 || position > 4) throw new IllegalArgumentException();
int freqNums[] = { 1, 1, 2, 5, 3 };
int freqDens[] = { 1, 7, 7, 7, 7 };
int[] freqNums = {1, 1, 2, 5, 3};
int[] freqDens = {1, 7, 7, 7, 7};
setFrequency(new Frequency(freqNums[position], freqDens[position]));
}

@ -89,7 +89,7 @@ public class ReminderPanel extends FrameLayout
tvReminderTime.setText(time);
llReminderDays.setVisibility(View.VISIBLE);
boolean weekdays[] = reminder.getDays().toArray();
boolean[] weekdays = reminder.getDays().toArray();
tvReminderDays.setText(AndroidDateUtils.formatWeekdayList(ctx, weekdays));
}

@ -29,12 +29,12 @@ import org.isoron.uhabits.core.utils.*
class ListHabitsActivity : HabitsActivity() {
var pureBlack: Boolean = false
private var pureBlack: Boolean = false
lateinit var adapter: HabitCardListAdapter
lateinit var rootView: ListHabitsRootView
private lateinit var rootView: ListHabitsRootView
lateinit var screen: ListHabitsScreen
lateinit var prefs: Preferences
lateinit var midnightTimer: MidnightTimer
private lateinit var midnightTimer: MidnightTimer
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)

@ -32,10 +32,8 @@ import org.isoron.uhabits.activities.habits.list.views.*
import org.isoron.uhabits.core.models.*
import org.isoron.uhabits.core.preferences.*
import org.isoron.uhabits.core.tasks.*
import org.isoron.uhabits.core.ui.screens.habits.list.*
import org.isoron.uhabits.core.utils.*
import org.isoron.uhabits.utils.*
import java.lang.Math.*
import javax.inject.*
const val MAX_CHECKMARK_COUNT = 60
@ -52,11 +50,11 @@ class ListHabitsRootView @Inject constructor(
) : BaseRootView(context), ModelObservable.Listener {
val listView: HabitCardListView = habitCardListViewFactory.create()
val llEmpty = EmptyListView(context)
val tbar = buildToolbar()
val progressBar = TaskProgressBar(context, runner)
val hintView: HintView
val header = HeaderView(context, preferences, midnightTimer)
private val llEmpty = EmptyListView(context)
private val tbar = buildToolbar()
private val progressBar = TaskProgressBar(context, runner)
private val hintView: HintView
private val header = HeaderView(context, preferences, midnightTimer)
init {
val hints = resources.getStringArray(R.array.hints)
@ -113,7 +111,7 @@ class ListHabitsRootView @Inject constructor(
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
val count = getCheckmarkCount()
header.buttonCount = count
header.setMaxDataOffset(max(MAX_CHECKMARK_COUNT - count, 0))
header.setMaxDataOffset((MAX_CHECKMARK_COUNT - count).coerceAtLeast(0))
listView.checkmarkCount = count
super.onSizeChanged(w, h, oldw, oldh)
}
@ -121,9 +119,9 @@ class ListHabitsRootView @Inject constructor(
private fun getCheckmarkCount(): Int {
val nameWidth = dim(R.dimen.habitNameWidth)
val buttonWidth = dim(R.dimen.checkmarkWidth)
val labelWidth = max((measuredWidth / 3).toFloat(), nameWidth)
val labelWidth = (measuredWidth / 3).toFloat().coerceAtLeast(nameWidth)
val buttonCount = ((measuredWidth - labelWidth) / buttonWidth).toInt()
return min(MAX_CHECKMARK_COUNT, max(0, buttonCount))
return MAX_CHECKMARK_COUNT.coerceAtMost(0.coerceAtLeast(buttonCount))
}
private fun updateEmptyView() {

@ -166,7 +166,7 @@ class ListHabitsScreen
activity.startActivity(intent)
}
fun showImportScreen() {
private fun showImportScreen() {
val intent = intentFactory.openDocument()
activity.startActivityForResult(intent, REQUEST_OPEN_DOCUMENT)
}
@ -213,26 +213,30 @@ class ListHabitsScreen
@StringRes
private fun getExecuteString(command: Command): Int? {
when (command) {
is ArchiveHabitsCommand -> return R.string.toast_habit_archived
is ChangeHabitColorCommand -> return R.string.toast_habit_changed
is CreateHabitCommand -> return R.string.toast_habit_created
is DeleteHabitsCommand -> return R.string.toast_habit_deleted
is EditHabitCommand -> return R.string.toast_habit_changed
is UnarchiveHabitsCommand -> return R.string.toast_habit_unarchived
else -> return null
return when (command) {
is ArchiveHabitsCommand -> R.string.toast_habit_archived
is ChangeHabitColorCommand -> R.string.toast_habit_changed
is CreateHabitCommand -> R.string.toast_habit_created
is DeleteHabitsCommand -> R.string.toast_habit_deleted
is EditHabitCommand -> R.string.toast_habit_changed
is UnarchiveHabitsCommand -> R.string.toast_habit_unarchived
else -> null
}
}
private fun onImportData(file: File, onFinished: () -> Unit) {
taskRunner.execute(importTaskFactory.create(file) { result ->
if (result == ImportDataTask.SUCCESS) {
adapter.refresh()
showMessage(R.string.habits_imported)
} else if (result == ImportDataTask.NOT_RECOGNIZED) {
showMessage(R.string.file_not_recognized)
} else {
showMessage(R.string.could_not_import)
when (result) {
ImportDataTask.SUCCESS -> {
adapter.refresh()
showMessage(R.string.habits_imported)
}
ImportDataTask.NOT_RECOGNIZED -> {
showMessage(R.string.file_not_recognized)
}
else -> {
showMessage(R.string.could_not_import)
}
}
onFinished()
})

@ -95,7 +95,7 @@ class ListHabitsSelectionMenu @Inject constructor(
itemEdit.isVisible = behavior.canEdit()
itemArchive.isVisible = behavior.canArchive()
itemUnarchive.isVisible = behavior.canUnarchive()
setTitle(Integer.toString(listAdapter.selected.size))
setTitle(listAdapter.selected.size.toString())
itemNotify.isVisible = prefs.isDeveloper
return true

@ -60,7 +60,7 @@ class CheckmarkButtonView(
setOnLongClickListener(this)
}
fun performToggle() {
private fun performToggle() {
onToggle()
value = when (value) {
CHECKED_EXPLICITLY -> UNCHECKED

@ -20,7 +20,6 @@
package org.isoron.uhabits.activities.habits.list.views
import android.content.*
import android.view.*
import android.view.Gravity.*
import android.view.ViewGroup.LayoutParams.*
import android.widget.*
@ -31,7 +30,7 @@ import org.isoron.uhabits.utils.*
class EmptyListView(context: Context) : LinearLayout(context) {
init {
orientation = VERTICAL
gravity = Gravity.CENTER
gravity = CENTER
visibility = BaseRootView.GONE
addView(TextView(context).apply {

@ -178,7 +178,7 @@ public class HabitCardListAdapter
Habit habit = cache.getHabitByPosition(position);
double score = cache.getScore(habit.getId());
int checkmarks[] = cache.getCheckmarks(habit.getId());
int[] checkmarks = cache.getCheckmarks(habit.getId());
boolean selected = this.selected.contains(habit);
listView.bindCardView(holder, habit, score, checkmarks, selected);

@ -38,12 +38,12 @@ class HabitCardListController @Inject constructor(
private val selectionMenu: Lazy<ListHabitsSelectionMenu>
) : HabitCardListView.Controller, ModelObservable.Listener {
private val NORMAL_MODE = NormalMode()
private val SELECTION_MODE = SelectionMode()
private val normalMode = NormalMode()
private val selectionMode = SelectionMode()
private var activeMode: Mode
init {
this.activeMode = NORMAL_MODE
this.activeMode = normalMode
adapter.observable.addListener(this)
}
@ -59,12 +59,12 @@ class HabitCardListController @Inject constructor(
behavior.onReorderHabit(habitFrom, habitTo)
}
override fun onItemClick(position: Int) {
activeMode.onItemClick(position)
override fun onItemClick(pos: Int) {
activeMode.onItemClick(pos)
}
override fun onItemLongClick(position: Int) {
activeMode.onItemLongClick(position)
override fun onItemLongClick(pos: Int) {
activeMode.onItemLongClick(pos)
}
override fun onModelChange() {
@ -82,9 +82,9 @@ class HabitCardListController @Inject constructor(
activeMode.startDrag(position)
}
protected fun toggleSelection(position: Int) {
private fun toggleSelection(position: Int) {
adapter.toggleSelection(position)
activeMode = if (adapter.isSelectionEmpty) NORMAL_MODE else SELECTION_MODE
activeMode = if (adapter.isSelectionEmpty) normalMode else selectionMode
}
private fun cancelSelection() {
@ -115,8 +115,7 @@ class HabitCardListController @Inject constructor(
*/
internal inner class NormalMode : Mode {
override fun onItemClick(position: Int) {
val habit = adapter.getItem(position)
if (habit == null) return
val habit = adapter.getItem(position) ?: return
behavior.onClickHabit(habit)
}
@ -129,9 +128,9 @@ class HabitCardListController @Inject constructor(
startSelection(position)
}
protected fun startSelection(position: Int) {
private fun startSelection(position: Int) {
toggleSelection(position)
activeMode = SELECTION_MODE
activeMode = selectionMode
selectionMenu.get().onSelectionStart()
}
}
@ -157,8 +156,8 @@ class HabitCardListController @Inject constructor(
notifyListener()
}
protected fun notifyListener() {
if (activeMode === SELECTION_MODE)
private fun notifyListener() {
if (activeMode === selectionMode)
selectionMenu.get().onSelectionChange()
else
selectionMenu.get().onSelectionFinish()

@ -151,18 +151,18 @@ class HabitCardListView(
inner class TouchHelperCallback : ItemTouchHelper.Callback() {
override fun getMovementFlags(recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder): Int {
viewHolder: ViewHolder): Int {
return makeMovementFlags(UP or DOWN, START or END)
}
override fun onMove(recyclerView: RecyclerView,
from: RecyclerView.ViewHolder,
to: RecyclerView.ViewHolder): Boolean {
from: ViewHolder,
to: ViewHolder): Boolean {
controller.get().drop(from.adapterPosition, to.adapterPosition)
return true
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder,
override fun onSwiped(viewHolder: ViewHolder,
direction: Int) {
}

@ -154,7 +154,7 @@ class HabitCardView(
}
clipToPadding = false
layoutParams = FrameLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT)
layoutParams = LayoutParams(MATCH_PARENT, WRAP_CONTENT)
val margin = dp(3f).toInt()
setPadding(margin, 0, margin, margin)
addView(innerFrame)
@ -171,7 +171,7 @@ class HabitCardView(
updateBackground(isSelected)
}
fun triggerRipple(timestamp: Timestamp) {
private fun triggerRipple(timestamp: Timestamp) {
val today = DateUtils.getToday()
val offset = timestamp.daysUntil(today) - dataOffset
val button = checkmarkPanel.buttons[offset]

@ -36,7 +36,7 @@ import java.util.*
class HeaderView(
context: Context,
val prefs: Preferences,
val midnightTimer: MidnightTimer
private val midnightTimer: MidnightTimer
) : ScrollableChart(context),
Preferences.Listener,
MidnightTimer.MidnightListener {

@ -35,7 +35,7 @@ class HintView(
private val hintList: HintList
) : LinearLayout(context) {
val hintContent: TextView
private val hintContent: TextView
init {
isClickable = true
@ -84,7 +84,7 @@ class HintView(
}
private inner class DismissAnimator : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: android.animation.Animator) {
override fun onAnimationEnd(animation: Animator) {
visibility = View.GONE
}
}

@ -98,9 +98,7 @@ public class ShowHabitRootView extends BaseRootView
@Override
public void onModelChange()
{
new Handler(Looper.getMainLooper()).post(() -> {
toolbar.setTitle(habit.getName());
});
new Handler(Looper.getMainLooper()).post(() -> toolbar.setTitle(habit.getName()));
controller.onToolbarChanged();
}

@ -70,7 +70,7 @@ public abstract class HabitCard extends LinearLayout
@Override
public void onModelChange()
{
post(() -> refreshData());
post(this::refreshData);
}
@Override

@ -25,7 +25,6 @@ import android.util.*;
import android.widget.*;
import org.isoron.androidbase.utils.*;
import org.isoron.uhabits.*;
import org.isoron.uhabits.R;
import org.isoron.uhabits.activities.common.views.*;
import org.isoron.uhabits.core.models.*;

@ -20,11 +20,9 @@
package org.isoron.uhabits.activities.habits.show.views;
import android.content.*;
import android.support.annotation.*;
import android.util.*;
import android.widget.*;
import org.isoron.uhabits.*;
import org.isoron.uhabits.R;
import org.isoron.uhabits.activities.common.views.*;
import org.isoron.uhabits.core.models.*;

@ -23,7 +23,6 @@ import android.app.*
import android.content.*
import android.os.*
import org.isoron.uhabits.*
import org.isoron.uhabits.automation.FireSettingReceiver.*
import org.isoron.uhabits.core.models.*
class EditSettingController(private val activity: Activity) {
@ -45,11 +44,11 @@ class EditSettingController(private val activity: Activity) {
}
private fun getActionName(action: Int): String {
when (action) {
ACTION_CHECK -> return activity.getString(R.string.check)
ACTION_UNCHECK -> return activity.getString(R.string.uncheck)
ACTION_TOGGLE -> return activity.getString(R.string.toggle)
else -> return "???"
return when (action) {
ACTION_CHECK -> activity.getString(R.string.check)
ACTION_UNCHECK -> activity.getString(R.string.uncheck)
ACTION_TOGGLE -> activity.getString(R.string.toggle)
else -> "???"
}
}
}

@ -79,7 +79,7 @@ class EditSettingRootView(
}
private fun populateHabitSpinner() {
val names = habitList.mapTo(LinkedList<String>()) { it.name }
val names = habitList.mapTo(LinkedList()) { it.name }
val adapter = ArrayAdapter(context, simple_spinner_item, names)
adapter.setDropDownViewResource(simple_spinner_dropdown_item)
habitSpinner.adapter = adapter

@ -56,7 +56,7 @@ class FireSettingReceiver : BroadcastReceiver() {
}
@ReceiverScope
@Component(dependencies = arrayOf(HabitsApplicationComponent::class))
@Component(dependencies = [HabitsApplicationComponent::class])
internal interface ReceiverComponent {
val widgetController: WidgetBehavior
}

@ -27,22 +27,22 @@ class AndroidCursor(private val cursor: android.database.Cursor) : Cursor {
override fun moveToNext() = cursor.moveToNext()
override fun getInt(index: Int): Int? {
if (cursor.isNull(index)) return null
else return cursor.getInt(index)
return if (cursor.isNull(index)) null
else cursor.getInt(index)
}
override fun getLong(index: Int): Long? {
if (cursor.isNull(index)) return null
else return cursor.getLong(index)
return if (cursor.isNull(index)) null
else cursor.getLong(index)
}
override fun getDouble(index: Int): Double? {
if (cursor.isNull(index)) return null
else return cursor.getDouble(index)
return if (cursor.isNull(index)) null
else cursor.getDouble(index)
}
override fun getString(index: Int): String? {
if (cursor.isNull(index)) return null
else return cursor.getString(index)
return if (cursor.isNull(index)) null
else cursor.getString(index)
}
}

@ -66,7 +66,7 @@ class AndroidDatabase(private val db: SQLiteDatabase) : Database {
is Double -> values.put(key, value)
is String -> values.put(key, value)
else -> throw IllegalStateException(
"unsupported type: " + value)
"unsupported type: $value")
}
}
return values

@ -37,9 +37,8 @@ class IntentParser
}
private fun parseHabit(uri: Uri): Habit {
val habit = habits.getById(parseId(uri)) ?:
return habits.getById(parseId(uri)) ?:
throw IllegalArgumentException("habit not found")
return habit
}
private fun parseTimestamp(intent: Intent): Timestamp {

@ -27,7 +27,6 @@ import android.os.Build.VERSION.*
import android.os.Build.VERSION_CODES.*
import android.util.*
import org.isoron.androidbase.*
import org.isoron.uhabits.*
import org.isoron.uhabits.core.*
import org.isoron.uhabits.core.models.*
import org.isoron.uhabits.core.reminders.*
@ -45,13 +44,13 @@ class IntentScheduler
private val manager =
context.getSystemService(ALARM_SERVICE) as AlarmManager
fun schedule(timestamp: Long, intent: PendingIntent) {
private fun schedule(timestamp: Long, intent: PendingIntent) {
Log.d("IntentScheduler",
"timestamp=" + timestamp + " current=" + System.currentTimeMillis())
if (timestamp < System.currentTimeMillis()) {
Log.e("IntentScheduler",
"Ignoring attempt to schedule intent in the past.")
return;
return
}
if (SDK_INT >= M)
manager.setExactAndAllowWhileIdle(RTC_WAKEUP, timestamp, intent)
@ -72,7 +71,7 @@ class IntentScheduler
}
private fun logReminderScheduled(habit: Habit, reminderTime: Long) {
val min = Math.min(5, habit.name.length)
val min = 5.coerceAtMost(habit.name.length)
val name = habit.name.substring(0, min)
val df = DateFormats.getBackupDateFormat()
val time = df.format(Date(reminderTime))

@ -36,7 +36,7 @@ class PendingIntentFactory
private val intentFactory: IntentFactory) {
fun addCheckmark(habit: Habit, timestamp: Timestamp?): PendingIntent =
PendingIntent.getBroadcast(
getBroadcast(
context, 1,
Intent(context, WidgetReceiver::class.java).apply {
data = Uri.parse(habit.uriString)
@ -46,7 +46,7 @@ class PendingIntentFactory
FLAG_UPDATE_CURRENT)
fun dismissNotification(habit: Habit): PendingIntent =
PendingIntent.getBroadcast(
getBroadcast(
context, 0,
Intent(context, ReminderReceiver::class.java).apply {
action = WidgetReceiver.ACTION_DISMISS_REMINDER
@ -55,7 +55,7 @@ class PendingIntentFactory
FLAG_UPDATE_CURRENT)
fun removeRepetition(habit: Habit): PendingIntent =
PendingIntent.getBroadcast(
getBroadcast(
context, 3,
Intent(context, WidgetReceiver::class.java).apply {
action = WidgetReceiver.ACTION_REMOVE_REPETITION
@ -74,7 +74,7 @@ class PendingIntentFactory
fun showReminder(habit: Habit,
reminderTime: Long?,
timestamp: Long): PendingIntent =
PendingIntent.getBroadcast(
getBroadcast(
context,
(habit.getId()!! % Integer.MAX_VALUE).toInt() + 1,
Intent(context, ReminderReceiver::class.java).apply {
@ -86,7 +86,7 @@ class PendingIntentFactory
FLAG_UPDATE_CURRENT)
fun snoozeNotification(habit: Habit): PendingIntent =
PendingIntent.getBroadcast(
getBroadcast(
context, 0,
Intent(context, ReminderReceiver::class.java).apply {
data = Uri.parse(habit.uriString)
@ -95,7 +95,7 @@ class PendingIntentFactory
FLAG_UPDATE_CURRENT)
fun toggleCheckmark(habit: Habit, timestamp: Long?): PendingIntent =
PendingIntent.getBroadcast(
getBroadcast(
context, 2,
Intent(context, WidgetReceiver::class.java).apply {
data = Uri.parse(habit.uriString)

@ -86,10 +86,10 @@ class AndroidNotificationTray
active.add(notificationId)
}
fun buildNotification(habit: Habit,
reminderTime: Long,
timestamp: Timestamp,
disableSound: Boolean = false): Notification {
private fun buildNotification(habit: Habit,
reminderTime: Long,
timestamp: Timestamp,
disableSound: Boolean = false): Notification {
val addRepetitionAction = Action(
R.drawable.ic_action_check,
@ -112,7 +112,7 @@ class AndroidNotificationTray
.addAction(removeRepetitionAction)
val defaultText = context.getString(R.string.default_reminder_question)
val builder = NotificationCompat.Builder(context, REMINDERS_CHANNEL_ID)
val builder = Builder(context, REMINDERS_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(habit.name)
.setContentText(if(habit.description.isBlank()) defaultText else habit.description)
@ -144,7 +144,7 @@ class AndroidNotificationTray
private fun buildSummary(habit: Habit,
reminderTime: Long): Notification {
return NotificationCompat.Builder(context, REMINDERS_CHANNEL_ID)
return Builder(context, REMINDERS_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(context.getString(R.string.app_name))
.setWhen(reminderTime)

@ -37,17 +37,17 @@ class RingtoneManager
PreferenceManager.getDefaultSharedPreferences(context)
fun getName(): String? {
try {
return try {
var ringtoneName = context.resources.getString(R.string.none)
val ringtoneUri = getURI()
if (ringtoneUri != null) {
val ringtone = getRingtone(context, ringtoneUri)
if (ringtone != null) ringtoneName = ringtone.getTitle(context)
}
return ringtoneName
ringtoneName
} catch (e: RuntimeException) {
e.printStackTrace()
return null
null
}
}

@ -27,8 +27,6 @@ import org.isoron.uhabits.*;
import org.isoron.uhabits.core.models.*;
import org.isoron.uhabits.core.utils.*;
import java.util.*;
import static android.content.ContentUris.*;
/**

@ -134,7 +134,7 @@ public class SyncManager implements CommandRunner.Listener
if (command.isRemote()) return;
JSONObject msg = toJSONObject(command.toJson());
Long now = new Date().getTime();
long now = new Date().getTime();
Event e = new Event(command.getId(), now, msg.toString());
repository.save(e);
@ -309,7 +309,7 @@ public class SyncManager implements CommandRunner.Listener
public void call(Object... args)
{
readyToEmit = false;
for (Event e : pendingConfirmation) pendingEmit.add(e);
pendingEmit.addAll(pendingConfirmation);
pendingConfirmation.clear();
}
}

@ -89,7 +89,7 @@ public class AndroidTaskRunner implements TaskRunner
private final Task task;
private boolean isCancelled = false;
public CustomAsyncTask(Task task)
CustomAsyncTask(Task task)
{
this.task = task;
}
@ -99,7 +99,7 @@ public class AndroidTaskRunner implements TaskRunner
return task;
}
public void publish(int progress)
void publish(int progress)
{
publishProgress(progress);
}

@ -39,10 +39,10 @@ public class AndroidDateUtils
return df.format(date);
}
public static String formatWeekdayList(Context context, boolean weekday[])
public static String formatWeekdayList(Context context, boolean[] weekday)
{
String shortDayNames[] = org.isoron.uhabits.core.utils.DateUtils.getShortWeekdayNames(Calendar.SATURDAY);
String longDayNames[] = org.isoron.uhabits.core.utils.DateUtils.getLongWeekdayNames(Calendar.SATURDAY);
String[] shortDayNames = org.isoron.uhabits.core.utils.DateUtils.getShortWeekdayNames(Calendar.SATURDAY);
String[] longDayNames = org.isoron.uhabits.core.utils.DateUtils.getLongWeekdayNames(Calendar.SATURDAY);
StringBuilder buffer = new StringBuilder();
int count = 0;

@ -28,7 +28,7 @@ import org.jetbrains.annotations.*;
public class AttributeSetUtils
{
public static final String ISORON_NAMESPACE = "http://isoron.org/android";
private static final String ISORON_NAMESPACE = "http://isoron.org/android";
@Nullable
public static String getAttribute(@NonNull Context context,

@ -73,21 +73,19 @@ public abstract class DatabaseUtils
}
@NonNull
public static String getDatabaseFilename()
private static String getDatabaseFilename()
{
String databaseFilename = Config.DATABASE_FILENAME;
if (HabitsApplication.Companion.isTestMode()) databaseFilename = "test.db";
return databaseFilename;
}
@SuppressWarnings("unchecked")
public static void initializeDatabase(Context context)
{
opener = new HabitsDatabaseOpener(context, getDatabaseFilename(),
DATABASE_VERSION);
}
@SuppressWarnings("ResultOfMethodCallIgnored")
public static String saveDatabaseCopy(Context context, File dir)
throws IOException
{

@ -34,9 +34,9 @@ fun RelativeLayout.addBelow(view: View,
subject: View,
width: Int = MATCH_PARENT,
height: Int = WRAP_CONTENT,
applyCustomRules: (params: RelativeLayout.LayoutParams) -> Unit = {}) {
applyCustomRules: (params: LayoutParams) -> Unit = {}) {
view.layoutParams = RelativeLayout.LayoutParams(width, height).apply {
view.layoutParams = LayoutParams(width, height).apply {
addRule(BELOW, subject.id)
applyCustomRules(this)
}
@ -48,7 +48,7 @@ fun RelativeLayout.addAtBottom(view: View,
width: Int = MATCH_PARENT,
height: Int = WRAP_CONTENT) {
view.layoutParams = RelativeLayout.LayoutParams(width, height).apply {
view.layoutParams = LayoutParams(width, height).apply {
addRule(ALIGN_PARENT_BOTTOM)
}
view.id = View.generateViewId()
@ -59,7 +59,7 @@ fun RelativeLayout.addAtTop(view: View,
width: Int = MATCH_PARENT,
height: Int = WRAP_CONTENT) {
view.layoutParams = RelativeLayout.LayoutParams(width, height).apply {
view.layoutParams = LayoutParams(width, height).apply {
addRule(ALIGN_PARENT_TOP)
}
view.id = View.generateViewId()

@ -23,7 +23,6 @@ import android.app.*;
import android.content.*;
import android.graphics.*;
import android.support.annotation.*;
import android.util.*;
import android.view.*;
import android.widget.*;
@ -38,7 +37,7 @@ public abstract class BaseWidget
private final int id;
@NonNull
protected final WidgetPreferences widgetPrefs;
private final WidgetPreferences widgetPrefs;
@NonNull
protected final Preferences prefs;
@ -119,7 +118,7 @@ public abstract class BaseWidget
{
int imageWidth = view.getMeasuredWidth();
int imageHeight = view.getMeasuredHeight();
int p[] = calculatePadding(width, height, imageWidth, imageHeight);
int[] p = calculatePadding(width, height, imageWidth, imageHeight);
remoteViews.setViewPadding(R.id.buttonOverlay, p[0], p[1], p[2], p[3]);
}

@ -23,7 +23,6 @@ import android.appwidget.*;
import android.content.*;
import android.os.*;
import android.support.annotation.*;
import android.util.*;
import android.widget.*;
import org.isoron.uhabits.*;
@ -137,7 +136,7 @@ public abstract class BaseWidgetProvider extends AppWidgetProvider
protected List<Habit> getHabitsFromWidgetId(int widgetId)
{
long selectedIds[] = widgetPrefs.getHabitIdsFromWidgetId(widgetId);
long[] selectedIds = widgetPrefs.getHabitIdsFromWidgetId(widgetId);
ArrayList<Habit> selectedHabits = new ArrayList<>(selectedIds.length);
for (long id : selectedIds)
{

@ -23,7 +23,7 @@ import android.content.*
class CheckmarkWidgetProvider : BaseWidgetProvider() {
override fun getWidgetFromId(context: Context, id: Int): BaseWidget {
val habits = getHabitsFromWidgetId(id)
if (habits.size == 1) return CheckmarkWidget(context, id, habits[0])
else return StackWidget(context, id, StackWidgetType.CHECKMARK, habits)
return if (habits.size == 1) CheckmarkWidget(context, id, habits[0])
else StackWidget(context, id, StackWidgetType.CHECKMARK, habits)
}
}

@ -24,10 +24,10 @@ import android.content.*
class FrequencyWidgetProvider : BaseWidgetProvider() {
override fun getWidgetFromId(context: Context, id: Int): BaseWidget {
val habits = getHabitsFromWidgetId(id)
if (habits.size == 1) return FrequencyWidget(context,
id,
habits[0],
preferences.firstWeekday)
else return StackWidget(context, id, StackWidgetType.FREQUENCY, habits)
return if (habits.size == 1) FrequencyWidget(context,
id,
habits[0],
preferences.firstWeekday)
else StackWidget(context, id, StackWidgetType.FREQUENCY, habits)
}
}

@ -88,7 +88,7 @@ class HabitPickerDialog : Activity() {
}
}
fun confirm(selectedIds: List<Long>) {
private fun confirm(selectedIds: List<Long>) {
widgetPreferences.addWidget(widgetId, selectedIds.toLongArray())
widgetUpdater.updateWidgets()
setResult(RESULT_OK, Intent().apply {

@ -23,10 +23,10 @@ import android.content.*
class HistoryWidgetProvider : BaseWidgetProvider() {
override fun getWidgetFromId(context: Context, id: Int): BaseWidget {
val habits = getHabitsFromWidgetId(id)
if (habits.size == 1) return HistoryWidget(context,
id,
habits[0],
preferences.firstWeekday)
else return StackWidget(context, id, StackWidgetType.HISTORY, habits)
return if (habits.size == 1) HistoryWidget(context,
id,
habits[0],
preferences.firstWeekday)
else StackWidget(context, id, StackWidgetType.HISTORY, habits)
}
}

@ -23,7 +23,7 @@ import android.content.*
class ScoreWidgetProvider : BaseWidgetProvider() {
override fun getWidgetFromId(context: Context, id: Int): BaseWidget {
val habits = getHabitsFromWidgetId(id)
if (habits.size == 1) return ScoreWidget(context, id, habits[0])
else return StackWidget(context, id, StackWidgetType.SCORE, habits)
return if (habits.size == 1) ScoreWidget(context, id, habits[0])
else StackWidget(context, id, StackWidgetType.SCORE, habits)
}
}

@ -23,7 +23,7 @@ import android.content.*
class StreakWidgetProvider : BaseWidgetProvider() {
override fun getWidgetFromId(context: Context, id: Int): BaseWidget {
val habits = getHabitsFromWidgetId(id)
if (habits.size == 1) return StreakWidget(context, id, habits[0])
else return StackWidget(context, id, StackWidgetType.STREAKS, habits)
return if (habits.size == 1) StreakWidget(context, id, habits[0])
else StackWidget(context, id, StackWidgetType.STREAKS, habits)
}
}

@ -60,7 +60,7 @@ class WidgetUpdater
commandRunner.removeListener(this)
}
fun updateWidgets(modifiedHabitId: Long?) {
private fun updateWidgets(modifiedHabitId: Long?) {
taskRunner.execute {
updateWidgets(modifiedHabitId, CheckmarkWidgetProvider::class.java)
updateWidgets(modifiedHabitId, HistoryWidgetProvider::class.java)

@ -171,8 +171,8 @@ public class CheckmarkWidgetView extends HabitWidgetView
private void init()
{
ring = (RingView) findViewById(R.id.scoreRing);
label = (TextView) findViewById(R.id.label);
ring = findViewById(R.id.scoreRing);
label = findViewById(R.id.label);
if (ring != null) ring.setIsTransparencyEnabled(true);

@ -50,7 +50,7 @@ public class EmptyWidgetView extends HabitWidgetView
private void init()
{
title = (TextView) findViewById(R.id.title);
title = findViewById(R.id.title);
title.setVisibility(VISIBLE);
}
}

@ -64,10 +64,10 @@ public class GraphWidgetView extends HabitWidgetView
ViewGroup.LayoutParams.MATCH_PARENT);
dataView.setLayoutParams(params);
ViewGroup innerFrame = (ViewGroup) findViewById(R.id.innerFrame);
ViewGroup innerFrame = findViewById(R.id.innerFrame);
innerFrame.addView(dataView);
title = (TextView) findViewById(R.id.title);
title = findViewById(R.id.title);
title.setVisibility(VISIBLE);
}
}

@ -106,7 +106,7 @@ public abstract class HabitWidgetView extends FrameLayout
backgroundPaint.setColor(res.getColor(R.attr.cardBgColor));
backgroundPaint.setAlpha(backgroundAlpha);
frame = (ViewGroup) findViewById(R.id.frame);
frame = findViewById(R.id.frame);
if (frame != null) frame.setBackgroundDrawable(background);
}

@ -22,6 +22,6 @@
<files-path name="files" path="." />
<cache-path name="cache" path="." />
<external-path name="external" path="." />
<extendal-cache-path name="external-cache" path="." />
<external-cache-path name="external-cache" path="." />
<external-files-path name="external-files" path="." />
</paths>

@ -37,7 +37,7 @@ public class ChangeHabitColorCommand extends Command
final List<Habit> selected;
@NonNull
final List<Integer> originalColors;
private final List<Integer> originalColors;
@NonNull
final Integer newColor;

@ -31,7 +31,7 @@ import org.isoron.uhabits.core.models.*;
@AutoFactory
public class CreateHabitCommand extends Command
{
ModelFactory modelFactory;
private ModelFactory modelFactory;
HabitList habitList;

@ -136,8 +136,8 @@ public class Repository<T>
{
try
{
Field fields[] = getFields();
String columns[] = getColumnNames();
Field[] fields = getFields();
String[] columns = getColumnNames();
Map<String, Object> values = new HashMap<>();
for (int i = 0; i < fields.length; i++)
@ -322,7 +322,7 @@ public class Repository<T>
{
if (cacheIdField == null)
{
Field fields[] = getFields();
Field[] fields = getFields();
String idName = getIdName();
for (Field f : fields)
if (f.getName().equals(idName))

@ -86,11 +86,9 @@ public class SQLParser {
public static List<String> parse(final InputStream stream) throws IOException {
final BufferedInputStream buffer = new BufferedInputStream(stream);
final List<String> commands = new ArrayList<String>();
final StringBuffer sb = new StringBuffer();
try {
try (BufferedInputStream buffer = new BufferedInputStream(stream)) {
final List<String> commands = new ArrayList<>();
final StringBuilder sb = new StringBuilder();
final Tokenizer tokenizer = new Tokenizer(buffer);
int state = STATE_NONE;
@ -141,16 +139,14 @@ public class SQLParser {
}
}
}
if (sb.length() > 0) {
commands.add(sb.toString().trim());
}
} finally {
buffer.close();
return commands;
}
if (sb.length() > 0) {
commands.add(sb.toString().trim());
}
return commands;
}
private static boolean isNewLine(final char c) {

@ -62,13 +62,13 @@ public class HabitBullCSVImporter extends AbstractImporter
CSVReader reader = new CSVReader(new FileReader(file));
HashMap<String, Habit> map = new HashMap<>();
for (String line[] : reader)
for (String[] line : reader)
{
String name = line[0];
if (name.equals("HabitName")) continue;
String description = line[1];
String dateString[] = line[3].split("-");
String[] dateString = line[3].split("-");
int year = Integer.parseInt(dateString[0]);
int month = Integer.parseInt(dateString[1]);
int day = Integer.parseInt(dateString[2]);

@ -81,7 +81,7 @@ public class HabitsCSVExporter
zos.putNextEntry(ze);
int length;
byte bytes[] = new byte[1024];
byte[] bytes = new byte[1024];
while ((length = fis.read(bytes)) >= 0) zos.write(bytes, 0, length);
zos.closeEntry();
@ -102,7 +102,7 @@ public class HabitsCSVExporter
@NonNull
private String sanitizeFilename(String name)
{
String s = name.replaceAll("[^ a-zA-Z0-9\\._-]+", "");
String s = name.replaceAll("[^ a-zA-Z0-9._-]+", "");
return s.substring(0, Math.min(s.length(), 100));
}

@ -84,9 +84,7 @@ public class LoopDBImporter extends AbstractImporter
}
@Override
public synchronized void importHabitsFromFile(@NonNull File file)
throws IOException
{
public synchronized void importHabitsFromFile(@NonNull File file) {
Database db = opener.open(file);
MigrationHelper helper = new MigrationHelper(db);
helper.migrateTo(DATABASE_VERSION);

@ -67,8 +67,7 @@ public class RewireDBImporter extends AbstractImporter
}
@Override
public void importHabitsFromFile(@NonNull File file) throws IOException
{
public void importHabitsFromFile(@NonNull File file) {
Database db = opener.open(file);
db.beginTransaction();
createHabits(db);
@ -79,17 +78,13 @@ public class RewireDBImporter extends AbstractImporter
private void createHabits(Database db)
{
Cursor c = null;
try
{
c = db.query("select _id, name, description, schedule, " +
"active_days, repeating_count, days, period " +
"from habits");
try (Cursor c = db.query("select _id, name, description, schedule, " +
"active_days, repeating_count, days, period " +
"from habits")) {
if (!c.moveToNext()) return;
do
{
do {
int id = c.getInt(0);
String name = c.getString(1);
String description = c.getString(2);
@ -103,11 +98,10 @@ public class RewireDBImporter extends AbstractImporter
habit.setName(name);
habit.setDescription(description);
int periods[] = { 7, 31, 365 };
int[] periods = {7, 31, 365};
int numerator, denominator;
switch (schedule)
{
switch (schedule) {
case 0:
numerator = activeDays.split(",").length;
denominator = 7;
@ -135,10 +129,6 @@ public class RewireDBImporter extends AbstractImporter
} while (c.moveToNext());
}
finally
{
if (c != null) c.close();
}
}
private void createCheckmarks(@NonNull Database db,
@ -177,23 +167,19 @@ public class RewireDBImporter extends AbstractImporter
private void createReminder(Database db, Habit habit, int rewireHabitId)
{
String[] params = { Integer.toString(rewireHabitId) };
Cursor c = null;
try
{
c = db.query(
try (Cursor c = db.query(
"select time, active_days from reminders where habit_id=? limit 1",
params);
params)) {
if (!c.moveToNext()) return;
int rewireReminder = Integer.parseInt(c.getString(0));
if (rewireReminder <= 0 || rewireReminder >= 1440) return;
boolean reminderDays[] = new boolean[7];
boolean[] reminderDays = new boolean[7];
String activeDays[] = c.getString(1).split(",");
for (String d : activeDays)
{
String[] activeDays = c.getString(1).split(",");
for (String d : activeDays) {
int idx = (Integer.parseInt(d) + 1) % 7;
reminderDays[idx] = true;
}
@ -206,9 +192,5 @@ public class RewireDBImporter extends AbstractImporter
habit.setReminder(reminder);
habitList.update(habit);
}
finally
{
if (c != null) c.close();
}
}
}

@ -67,8 +67,7 @@ public class TickmateDBImporter extends AbstractImporter
}
@Override
public void importHabitsFromFile(@NonNull File file) throws IOException
{
public void importHabitsFromFile(@NonNull File file) {
final Database db = opener.open(file);
db.beginTransaction();
createHabits(db);
@ -111,16 +110,12 @@ public class TickmateDBImporter extends AbstractImporter
private void createHabits(Database db)
{
Cursor c = null;
try
{
c = db.query("select _id, name, description from tracks",
new String[0]);
try (Cursor c = db.query("select _id, name, description from tracks"
)) {
if (!c.moveToNext()) return;
do
{
do {
int id = c.getInt(0);
String name = c.getString(1);
String description = c.getString(2);
@ -135,9 +130,5 @@ public class TickmateDBImporter extends AbstractImporter
} while (c.moveToNext());
}
finally
{
if (c != null) c.close();
}
}
}

@ -234,7 +234,7 @@ public abstract class CheckmarkList
if (from.isNewerThan(to)) return new int[0];
List<Checkmark> checkmarks = getByInterval(from, to);
int values[] = new int[checkmarks.size()];
int[] values = new int[checkmarks.size()];
int i = 0;
for (Checkmark c : checkmarks)
@ -260,7 +260,7 @@ public abstract class CheckmarkList
*/
public final void writeCSV(Writer out) throws IOException
{
int values[];
int[] values;
synchronized (this)
{
@ -295,10 +295,10 @@ public abstract class CheckmarkList
if (oldestRep == null) return;
final Timestamp from = oldestRep.getTimestamp();
Repetition reps[] = habit
.getRepetitions()
.getByInterval(from, today)
.toArray(new Repetition[0]);
Repetition[] reps = habit
.getRepetitions()
.getByInterval(from, today)
.toArray(new Repetition[0]);
if (habit.isNumerical()) computeNumerical(reps);
else computeYesNo(reps);
@ -417,8 +417,8 @@ public abstract class CheckmarkList
List<Checkmark> checks = getAll();
int count = 0;
Timestamp truncatedTimestamps[] = new Timestamp[checks.size()];
int values[] = new int[checks.size()];
Timestamp[] truncatedTimestamps = new Timestamp[checks.size()];
int[] values = new int[checks.size()];
for (Checkmark rep : checks)
{

@ -209,13 +209,13 @@ public abstract class HabitList implements Iterable<Habit>
*/
public void writeCSV(@NonNull Writer out) throws IOException
{
String header[] = {
"Position",
"Name",
"Description",
"NumRepetitions",
"Interval",
"Color"
String[] header = {
"Position",
"Name",
"Description",
"NumRepetitions",
"Interval",
"Color"
};
CSVWriter csv = new CSVWriter(out);

@ -60,7 +60,6 @@ public class HabitMatcher
{
if (!isArchivedAllowed() && habit.isArchived()) return false;
if (isReminderRequired() && !habit.hasReminder()) return false;
if (!isCompletedAllowed() && habit.isCompletedToday()) return false;
return true;
return isCompletedAllowed() || !habit.isCompletedToday();
}
}

@ -20,12 +20,6 @@
package org.isoron.uhabits.core.models;
import org.apache.commons.lang3.builder.*;
import org.isoron.uhabits.core.utils.DateFormats;
import org.isoron.uhabits.core.utils.DateUtils;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import static org.isoron.uhabits.core.utils.StringUtils.defaultToStringStyle;

@ -268,7 +268,7 @@ public abstract class ScoreList implements Iterable<Score>
if (from.isNewerThan(to)) return;
final double freq = habit.getFrequency().toDouble();
final int checkmarkValues[] = habit.getCheckmarks().getValues(from, to);
final int[] checkmarkValues = habit.getCheckmarks().getValues(from, to);
List<Score> scores = new LinkedList<>();

@ -71,7 +71,7 @@ public abstract class StreakList
Timestamp beginning = findBeginning();
if (beginning == null || beginning.isNewerThan(today)) return;
int checks[] = habit.getCheckmarks().getValues(beginning, today);
int[] checks = habit.getCheckmarks().getValues(beginning, today);
List<Streak> streaks = checkmarksToStreaks(beginning, checks);
removeNewestComputed();

@ -26,7 +26,6 @@ import org.isoron.uhabits.core.utils.DateUtils;
import java.util.*;
import static java.util.Calendar.*;
import static org.isoron.uhabits.core.utils.StringUtils.*;
public final class Timestamp
{

@ -43,7 +43,7 @@ public final class WeekdayList
}
}
public WeekdayList(boolean weekdays[])
public WeekdayList(boolean[] weekdays)
{
this.weekdays = Arrays.copyOf(weekdays, 7);
}

@ -163,7 +163,7 @@ public class SQLiteHabitList extends HabitList
if (record == null) throw new RuntimeException("habit not in database");
repository.executeAsTransaction(() ->
{
((SQLiteRepetitionList) habit.getRepetitions()).removeAll();
habit.getRepetitions().removeAll();
repository.remove(record);
});

@ -33,7 +33,7 @@ public class WidgetPreferences {
this.storage = storage;
}
public void addWidget(int widgetId, long habitIds[]) {
public void addWidget(int widgetId, long[] habitIds) {
storage.putLongArray(getHabitIdKey(widgetId), habitIds);
}

@ -25,7 +25,7 @@ import org.isoron.uhabits.core.utils.*;
public class HabitFixtures
{
public boolean NON_DAILY_HABIT_CHECKS[] = {
public boolean[] NON_DAILY_HABIT_CHECKS = {
true, false, false, true, true, true, false, false, true, true
};
@ -58,7 +58,7 @@ public class HabitFixtures
habit.setColor(4);
Timestamp today = DateUtils.getToday();
int marks[] = {0, 1, 3, 5, 7, 8, 9, 10, 12, 14, 15, 17, 19, 20, 26, 27,
int[] marks = {0, 1, 3, 5, 7, 8, 9, 10, 12, 14, 15, 17, 19, 20, 26, 27,
28, 50, 51, 52, 53, 54, 58, 60, 63, 65, 70, 71, 72, 73, 74, 75, 80,
81, 83, 89, 90, 91, 95, 102, 103, 108, 109, 120};
@ -81,8 +81,8 @@ public class HabitFixtures
saveIfSQLite(habit);
Timestamp today = DateUtils.getToday();
int times[] = {0, 1, 3, 5, 7, 8, 9, 10};
int values[] = {100, 200, 300, 400, 500, 600, 700, 800};
int[] times = {0, 1, 3, 5, 7, 8, 9, 10};
int[] values = {100, 200, 300, 400, 500, 600, 700, 800};
for (int i = 0; i < times.length; i++)
{
@ -105,14 +105,14 @@ public class HabitFixtures
habit.setColor(1);
saveIfSQLite(habit);
int times[] = {0, 5, 9, 15, 17, 21, 23, 27, 28, 35, 41, 45, 47, 53, 56, 62, 70, 73, 78,
int[] times = {0, 5, 9, 15, 17, 21, 23, 27, 28, 35, 41, 45, 47, 53, 56, 62, 70, 73, 78,
83, 86, 94, 101, 106, 113, 114, 120, 126, 130, 133, 141, 143, 148, 151, 157, 164,
166, 171, 173, 176, 179, 183, 191, 259, 264, 268, 270, 275, 282, 284, 289, 295,
302, 306, 310, 315, 323, 325, 328, 335, 343, 349, 351, 353, 357, 359, 360, 367,
372, 376, 380, 385, 393, 400, 404, 412, 415, 418, 422, 425, 433, 437, 444, 449,
455, 460, 462, 465, 470, 471, 479, 481, 485, 489, 494, 495, 500, 501, 503, 507};
int values[] = {230, 306, 148, 281, 134, 285, 104, 158, 325, 236, 303, 210, 118, 124,
int[] values = {230, 306, 148, 281, 134, 285, 104, 158, 325, 236, 303, 210, 118, 124,
301, 201, 156, 376, 347, 367, 396, 134, 160, 381, 155, 354, 231, 134, 164, 354,
236, 398, 199, 221, 208, 397, 253, 276, 214, 341, 299, 221, 353, 250, 341, 168,
374, 205, 182, 217, 297, 321, 104, 237, 294, 110, 136, 229, 102, 271, 250, 294,

@ -155,9 +155,9 @@ public class NotificationTray
{
public final Timestamp timestamp;
public final long reminderTime;
final long reminderTime;
public NotificationData(Timestamp timestamp, long reminderTime)
NotificationData(Timestamp timestamp, long reminderTime)
{
this.timestamp = timestamp;
this.reminderTime = reminderTime;
@ -174,7 +174,7 @@ public class NotificationTray
private final long reminderTime;
public ShowNotificationTask(Habit habit, NotificationData data)
ShowNotificationTask(Habit habit, NotificationData data)
{
this.habit = habit;
this.timestamp = data.timestamp;
@ -225,7 +225,7 @@ public class NotificationTray
if (!habit.hasReminder()) return false;
Reminder reminder = habit.getReminder();
boolean reminderDays[] = reminder.getDays().toArray();
boolean[] reminderDays = reminder.getDays().toArray();
int weekday = timestamp.getWeekday();
return reminderDays[weekday];

@ -234,7 +234,7 @@ public class HabitCardListCache implements CommandRunner.Listener
private class CacheData
{
@NonNull
public final HashMap<Long, Habit> id_to_habit;
final HashMap<Long, Habit> id_to_habit;
@NonNull
public final List<Habit> habits;
@ -248,7 +248,7 @@ public class HabitCardListCache implements CommandRunner.Listener
/**
* Creates a new CacheData without any content.
*/
public CacheData()
CacheData()
{
id_to_habit = new HashMap<>();
habits = new LinkedList<>();
@ -256,7 +256,7 @@ public class HabitCardListCache implements CommandRunner.Listener
scores = new HashMap<>();
}
public synchronized void copyCheckmarksFrom(@NonNull CacheData oldData)
synchronized void copyCheckmarksFrom(@NonNull CacheData oldData)
{
if (oldData == null) throw new NullPointerException();
@ -270,7 +270,7 @@ public class HabitCardListCache implements CommandRunner.Listener
}
}
public synchronized void copyScoresFrom(@NonNull CacheData oldData)
synchronized void copyScoresFrom(@NonNull CacheData oldData)
{
if (oldData == null) throw new NullPointerException();
@ -282,7 +282,7 @@ public class HabitCardListCache implements CommandRunner.Listener
}
}
public synchronized void fetchHabits()
synchronized void fetchHabits()
{
for (Habit h : filteredHabits)
{
@ -306,14 +306,14 @@ public class HabitCardListCache implements CommandRunner.Listener
@Nullable
private TaskRunner runner;
public RefreshTask()
RefreshTask()
{
newData = new CacheData();
targetId = null;
isCancelled = false;
}
public RefreshTask(long targetId)
RefreshTask(long targetId)
{
newData = new CacheData();
this.targetId = targetId;

@ -45,7 +45,7 @@ public class HintList
* @param hints initial list of hints
*/
public HintList(@Provided @NonNull Preferences prefs,
@NonNull String hints[])
@NonNull String[] hints)
{
this.prefs = prefs;
this.hints = hints;

@ -2,26 +2,26 @@ package org.isoron.uhabits.core.utils;
public class ColorConstants
{
public static String CSV_PALETTE[] = {
"#D32F2F", // 0 red
"#E64A19", // 1 deep orange
"#F57C00", // 2 orange
"#FF8F00", // 3 amber
"#F9A825", // 4 yellow
"#AFB42B", // 5 lime
"#7CB342", // 6 light green
"#388E3C", // 7 green
"#00897B", // 8 teal
"#00ACC1", // 9 cyan
"#039BE5", // 10 light blue
"#1976D2", // 11 blue
"#303F9F", // 12 indigo
"#5E35B1", // 13 deep purple
"#8E24AA", // 14 purple
"#D81B60", // 15 pink
"#5D4037", // 16 brown
"#303030", // 17 dark grey
"#757575", // 18 grey
"#aaaaaa" // 19 light grey
public static String[] CSV_PALETTE = {
"#D32F2F", // 0 red
"#E64A19", // 1 deep orange
"#F57C00", // 2 orange
"#FF8F00", // 3 amber
"#F9A825", // 4 yellow
"#AFB42B", // 5 lime
"#7CB342", // 6 light green
"#388E3C", // 7 green
"#00897B", // 8 teal
"#00ACC1", // 9 cyan
"#039BE5", // 10 light blue
"#1976D2", // 11 blue
"#303F9F", // 12 indigo
"#5E35B1", // 13 deep purple
"#8E24AA", // 14 purple
"#D81B60", // 15 pink
"#5D4037", // 16 brown
"#303030", // 17 dark grey
"#757575", // 18 grey
"#aaaaaa" // 19 light grey
};
}

@ -55,7 +55,7 @@ public class MidnightTimer
public synchronized void onResume()
{
executor = Executors.newSingleThreadScheduledExecutor();
executor.scheduleAtFixedRate(() -> notifyListeners(),
executor.scheduleAtFixedRate(this::notifyListeners,
DateUtils.millisecondsUntilTomorrow() + 1000,
DateUtils.DAY_LENGTH, TimeUnit.MILLISECONDS);
}

@ -51,16 +51,16 @@ public class StringUtils
return toStringStyle;
}
public static String joinLongs(long values[])
public static String joinLongs(long[] values)
{
return org.apache.commons.lang3.StringUtils.join(values, ',');
}
public static long[] splitLongs(String str)
{
String parts[] = org.apache.commons.lang3.StringUtils.split(str, ',');
String[] parts = org.apache.commons.lang3.StringUtils.split(str, ',');
long numbers[] = new long[parts.length];
long[] numbers = new long[parts.length];
for (int i = 0; i < parts.length; i++) numbers[i] = Long.valueOf(parts[i]);
return numbers;
}

Loading…
Cancel
Save