Miscellaneous code cleanup

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

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

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

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

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

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

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

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

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

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

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

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

@ -50,8 +50,7 @@ abstract class HabitsActivity : BaseActivity() {
private fun getHabitFromIntent(habitList: HabitList): Habit? { private fun getHabitFromIntent(habitList: HabitList): Habit? {
val data = intent.data ?: return null val data = intent.data ?: return null
val habit = habitList.getById(ContentUris.parseId(data)) return habitList.getById(ContentUris.parseId(data))
?: throw RuntimeException("habit not found") ?: 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.*
import org.isoron.uhabits.activities.habits.list.views.* import org.isoron.uhabits.activities.habits.list.views.*
import org.isoron.uhabits.activities.habits.show.* import org.isoron.uhabits.activities.habits.show.*
import org.isoron.uhabits.core.ui.*
import org.isoron.uhabits.core.ui.screens.habits.list.* import org.isoron.uhabits.core.ui.screens.habits.list.*
@ActivityScope @ActivityScope
@Component(modules = arrayOf( @Component(modules = [
ActivityContextModule::class, ActivityContextModule::class,
BaseActivityModule::class, BaseActivityModule::class,
AboutModule::class, AboutModule::class,
HabitsActivityModule::class, HabitsActivityModule::class,
ListHabitsModule::class, ListHabitsModule::class,
ShowHabitModule::class, ShowHabitModule::class,
HabitModule::class HabitModule::class
), dependencies = arrayOf(HabitsApplicationComponent::class)) ], dependencies = [HabitsApplicationComponent::class])
interface HabitsActivityComponent { interface HabitsActivityComponent {
val aboutRootView: AboutRootView val aboutRootView: AboutRootView
val aboutScreen: AboutScreen val aboutScreen: AboutScreen

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

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

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

@ -21,8 +21,9 @@ package org.isoron.uhabits.activities.common.views;
import android.os.*; import android.os.*;
import android.support.v4.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 = public static final Parcelable.Creator<BundleSavedState> CREATOR =
ParcelableCompat.newCreator( ParcelableCompat.newCreator(

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

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

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

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

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

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

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

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

@ -29,12 +29,12 @@ import org.isoron.uhabits.core.utils.*
class ListHabitsActivity : HabitsActivity() { class ListHabitsActivity : HabitsActivity() {
var pureBlack: Boolean = false private var pureBlack: Boolean = false
lateinit var adapter: HabitCardListAdapter lateinit var adapter: HabitCardListAdapter
lateinit var rootView: ListHabitsRootView private lateinit var rootView: ListHabitsRootView
lateinit var screen: ListHabitsScreen lateinit var screen: ListHabitsScreen
lateinit var prefs: Preferences lateinit var prefs: Preferences
lateinit var midnightTimer: MidnightTimer private lateinit var midnightTimer: MidnightTimer
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) 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.models.*
import org.isoron.uhabits.core.preferences.* import org.isoron.uhabits.core.preferences.*
import org.isoron.uhabits.core.tasks.* 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.core.utils.*
import org.isoron.uhabits.utils.* import org.isoron.uhabits.utils.*
import java.lang.Math.*
import javax.inject.* import javax.inject.*
const val MAX_CHECKMARK_COUNT = 60 const val MAX_CHECKMARK_COUNT = 60
@ -52,11 +50,11 @@ class ListHabitsRootView @Inject constructor(
) : BaseRootView(context), ModelObservable.Listener { ) : BaseRootView(context), ModelObservable.Listener {
val listView: HabitCardListView = habitCardListViewFactory.create() val listView: HabitCardListView = habitCardListViewFactory.create()
val llEmpty = EmptyListView(context) private val llEmpty = EmptyListView(context)
val tbar = buildToolbar() private val tbar = buildToolbar()
val progressBar = TaskProgressBar(context, runner) private val progressBar = TaskProgressBar(context, runner)
val hintView: HintView private val hintView: HintView
val header = HeaderView(context, preferences, midnightTimer) private val header = HeaderView(context, preferences, midnightTimer)
init { init {
val hints = resources.getStringArray(R.array.hints) 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) { override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
val count = getCheckmarkCount() val count = getCheckmarkCount()
header.buttonCount = count header.buttonCount = count
header.setMaxDataOffset(max(MAX_CHECKMARK_COUNT - count, 0)) header.setMaxDataOffset((MAX_CHECKMARK_COUNT - count).coerceAtLeast(0))
listView.checkmarkCount = count listView.checkmarkCount = count
super.onSizeChanged(w, h, oldw, oldh) super.onSizeChanged(w, h, oldw, oldh)
} }
@ -121,9 +119,9 @@ class ListHabitsRootView @Inject constructor(
private fun getCheckmarkCount(): Int { private fun getCheckmarkCount(): Int {
val nameWidth = dim(R.dimen.habitNameWidth) val nameWidth = dim(R.dimen.habitNameWidth)
val buttonWidth = dim(R.dimen.checkmarkWidth) 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() 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() { private fun updateEmptyView() {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

@ -79,7 +79,7 @@ class EditSettingRootView(
} }
private fun populateHabitSpinner() { 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) val adapter = ArrayAdapter(context, simple_spinner_item, names)
adapter.setDropDownViewResource(simple_spinner_dropdown_item) adapter.setDropDownViewResource(simple_spinner_dropdown_item)
habitSpinner.adapter = adapter habitSpinner.adapter = adapter

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

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

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

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

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

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

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

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

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

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

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

@ -39,10 +39,10 @@ public class AndroidDateUtils
return df.format(date); 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[] shortDayNames = org.isoron.uhabits.core.utils.DateUtils.getShortWeekdayNames(Calendar.SATURDAY);
String longDayNames[] = org.isoron.uhabits.core.utils.DateUtils.getLongWeekdayNames(Calendar.SATURDAY); String[] longDayNames = org.isoron.uhabits.core.utils.DateUtils.getLongWeekdayNames(Calendar.SATURDAY);
StringBuilder buffer = new StringBuilder(); StringBuilder buffer = new StringBuilder();
int count = 0; int count = 0;

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

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

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

@ -23,7 +23,6 @@ import android.app.*;
import android.content.*; import android.content.*;
import android.graphics.*; import android.graphics.*;
import android.support.annotation.*; import android.support.annotation.*;
import android.util.*;
import android.view.*; import android.view.*;
import android.widget.*; import android.widget.*;
@ -38,7 +37,7 @@ public abstract class BaseWidget
private final int id; private final int id;
@NonNull @NonNull
protected final WidgetPreferences widgetPrefs; private final WidgetPreferences widgetPrefs;
@NonNull @NonNull
protected final Preferences prefs; protected final Preferences prefs;
@ -119,7 +118,7 @@ public abstract class BaseWidget
{ {
int imageWidth = view.getMeasuredWidth(); int imageWidth = view.getMeasuredWidth();
int imageHeight = view.getMeasuredHeight(); 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]); 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.content.*;
import android.os.*; import android.os.*;
import android.support.annotation.*; import android.support.annotation.*;
import android.util.*;
import android.widget.*; import android.widget.*;
import org.isoron.uhabits.*; import org.isoron.uhabits.*;
@ -137,7 +136,7 @@ public abstract class BaseWidgetProvider extends AppWidgetProvider
protected List<Habit> getHabitsFromWidgetId(int widgetId) protected List<Habit> getHabitsFromWidgetId(int widgetId)
{ {
long selectedIds[] = widgetPrefs.getHabitIdsFromWidgetId(widgetId); long[] selectedIds = widgetPrefs.getHabitIdsFromWidgetId(widgetId);
ArrayList<Habit> selectedHabits = new ArrayList<>(selectedIds.length); ArrayList<Habit> selectedHabits = new ArrayList<>(selectedIds.length);
for (long id : selectedIds) for (long id : selectedIds)
{ {

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

@ -24,10 +24,10 @@ import android.content.*
class FrequencyWidgetProvider : BaseWidgetProvider() { class FrequencyWidgetProvider : BaseWidgetProvider() {
override fun getWidgetFromId(context: Context, id: Int): BaseWidget { override fun getWidgetFromId(context: Context, id: Int): BaseWidget {
val habits = getHabitsFromWidgetId(id) val habits = getHabitsFromWidgetId(id)
if (habits.size == 1) return FrequencyWidget(context, return if (habits.size == 1) FrequencyWidget(context,
id, id,
habits[0], habits[0],
preferences.firstWeekday) preferences.firstWeekday)
else return StackWidget(context, id, StackWidgetType.FREQUENCY, habits) 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()) widgetPreferences.addWidget(widgetId, selectedIds.toLongArray())
widgetUpdater.updateWidgets() widgetUpdater.updateWidgets()
setResult(RESULT_OK, Intent().apply { setResult(RESULT_OK, Intent().apply {

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

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

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

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

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

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

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

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

@ -22,6 +22,6 @@
<files-path name="files" path="." /> <files-path name="files" path="." />
<cache-path name="cache" path="." /> <cache-path name="cache" path="." />
<external-path name="external" 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="." /> <external-files-path name="external-files" path="." />
</paths> </paths>

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

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

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

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

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

@ -81,7 +81,7 @@ public class HabitsCSVExporter
zos.putNextEntry(ze); zos.putNextEntry(ze);
int length; int length;
byte bytes[] = new byte[1024]; byte[] bytes = new byte[1024];
while ((length = fis.read(bytes)) >= 0) zos.write(bytes, 0, length); while ((length = fis.read(bytes)) >= 0) zos.write(bytes, 0, length);
zos.closeEntry(); zos.closeEntry();
@ -102,7 +102,7 @@ public class HabitsCSVExporter
@NonNull @NonNull
private String sanitizeFilename(String name) 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)); return s.substring(0, Math.min(s.length(), 100));
} }

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

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

@ -67,8 +67,7 @@ public class TickmateDBImporter extends AbstractImporter
} }
@Override @Override
public void importHabitsFromFile(@NonNull File file) throws IOException public void importHabitsFromFile(@NonNull File file) {
{
final Database db = opener.open(file); final Database db = opener.open(file);
db.beginTransaction(); db.beginTransaction();
createHabits(db); createHabits(db);
@ -111,16 +110,12 @@ public class TickmateDBImporter extends AbstractImporter
private void createHabits(Database db) private void createHabits(Database db)
{ {
Cursor c = null;
try try (Cursor c = db.query("select _id, name, description from tracks"
{ )) {
c = db.query("select _id, name, description from tracks",
new String[0]);
if (!c.moveToNext()) return; if (!c.moveToNext()) return;
do do {
{
int id = c.getInt(0); int id = c.getInt(0);
String name = c.getString(1); String name = c.getString(1);
String description = c.getString(2); String description = c.getString(2);
@ -135,9 +130,5 @@ public class TickmateDBImporter extends AbstractImporter
} while (c.moveToNext()); } 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]; if (from.isNewerThan(to)) return new int[0];
List<Checkmark> checkmarks = getByInterval(from, to); List<Checkmark> checkmarks = getByInterval(from, to);
int values[] = new int[checkmarks.size()]; int[] values = new int[checkmarks.size()];
int i = 0; int i = 0;
for (Checkmark c : checkmarks) for (Checkmark c : checkmarks)
@ -260,7 +260,7 @@ public abstract class CheckmarkList
*/ */
public final void writeCSV(Writer out) throws IOException public final void writeCSV(Writer out) throws IOException
{ {
int values[]; int[] values;
synchronized (this) synchronized (this)
{ {
@ -295,10 +295,10 @@ public abstract class CheckmarkList
if (oldestRep == null) return; if (oldestRep == null) return;
final Timestamp from = oldestRep.getTimestamp(); final Timestamp from = oldestRep.getTimestamp();
Repetition reps[] = habit Repetition[] reps = habit
.getRepetitions() .getRepetitions()
.getByInterval(from, today) .getByInterval(from, today)
.toArray(new Repetition[0]); .toArray(new Repetition[0]);
if (habit.isNumerical()) computeNumerical(reps); if (habit.isNumerical()) computeNumerical(reps);
else computeYesNo(reps); else computeYesNo(reps);
@ -417,8 +417,8 @@ public abstract class CheckmarkList
List<Checkmark> checks = getAll(); List<Checkmark> checks = getAll();
int count = 0; int count = 0;
Timestamp truncatedTimestamps[] = new Timestamp[checks.size()]; Timestamp[] truncatedTimestamps = new Timestamp[checks.size()];
int values[] = new int[checks.size()]; int[] values = new int[checks.size()];
for (Checkmark rep : checks) for (Checkmark rep : checks)
{ {

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

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

@ -20,12 +20,6 @@
package org.isoron.uhabits.core.models; package org.isoron.uhabits.core.models;
import org.apache.commons.lang3.builder.*; 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; 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; if (from.isNewerThan(to)) return;
final double freq = habit.getFrequency().toDouble(); 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<>(); List<Score> scores = new LinkedList<>();

@ -71,7 +71,7 @@ public abstract class StreakList
Timestamp beginning = findBeginning(); Timestamp beginning = findBeginning();
if (beginning == null || beginning.isNewerThan(today)) return; 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); List<Streak> streaks = checkmarksToStreaks(beginning, checks);
removeNewestComputed(); removeNewestComputed();

@ -26,7 +26,6 @@ import org.isoron.uhabits.core.utils.DateUtils;
import java.util.*; import java.util.*;
import static java.util.Calendar.*; import static java.util.Calendar.*;
import static org.isoron.uhabits.core.utils.StringUtils.*;
public final class Timestamp 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); 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"); if (record == null) throw new RuntimeException("habit not in database");
repository.executeAsTransaction(() -> repository.executeAsTransaction(() ->
{ {
((SQLiteRepetitionList) habit.getRepetitions()).removeAll(); habit.getRepetitions().removeAll();
repository.remove(record); repository.remove(record);
}); });

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

@ -25,7 +25,7 @@ import org.isoron.uhabits.core.utils.*;
public class HabitFixtures 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 true, false, false, true, true, true, false, false, true, true
}; };
@ -58,7 +58,7 @@ public class HabitFixtures
habit.setColor(4); habit.setColor(4);
Timestamp today = DateUtils.getToday(); 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, 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, 83, 89, 90, 91, 95, 102, 103, 108, 109, 120};
@ -81,8 +81,8 @@ public class HabitFixtures
saveIfSQLite(habit); saveIfSQLite(habit);
Timestamp today = DateUtils.getToday(); Timestamp today = DateUtils.getToday();
int times[] = {0, 1, 3, 5, 7, 8, 9, 10}; int[] times = {0, 1, 3, 5, 7, 8, 9, 10};
int values[] = {100, 200, 300, 400, 500, 600, 700, 800}; int[] values = {100, 200, 300, 400, 500, 600, 700, 800};
for (int i = 0; i < times.length; i++) for (int i = 0; i < times.length; i++)
{ {
@ -105,14 +105,14 @@ public class HabitFixtures
habit.setColor(1); habit.setColor(1);
saveIfSQLite(habit); 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, 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, 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, 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, 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}; 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, 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, 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, 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 Timestamp timestamp;
public final long reminderTime; final long reminderTime;
public NotificationData(Timestamp timestamp, long reminderTime) NotificationData(Timestamp timestamp, long reminderTime)
{ {
this.timestamp = timestamp; this.timestamp = timestamp;
this.reminderTime = reminderTime; this.reminderTime = reminderTime;
@ -174,7 +174,7 @@ public class NotificationTray
private final long reminderTime; private final long reminderTime;
public ShowNotificationTask(Habit habit, NotificationData data) ShowNotificationTask(Habit habit, NotificationData data)
{ {
this.habit = habit; this.habit = habit;
this.timestamp = data.timestamp; this.timestamp = data.timestamp;
@ -225,7 +225,7 @@ public class NotificationTray
if (!habit.hasReminder()) return false; if (!habit.hasReminder()) return false;
Reminder reminder = habit.getReminder(); Reminder reminder = habit.getReminder();
boolean reminderDays[] = reminder.getDays().toArray(); boolean[] reminderDays = reminder.getDays().toArray();
int weekday = timestamp.getWeekday(); int weekday = timestamp.getWeekday();
return reminderDays[weekday]; return reminderDays[weekday];

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

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

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

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

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

Loading…
Cancel
Save