Revert "Make use of Java 10 var keyword"

This reverts commit 085bb7a94c.
This commit is contained in:
Stefan Niedermann 2021-07-29 18:44:06 +02:00
parent 085bb7a94c
commit 91055e57f3
116 changed files with 724 additions and 720 deletions

View file

@ -37,7 +37,7 @@ public class AppendToNoteActivity extends MainActivity {
@Override
public void onNoteClick(int position, View v) {
if (!TextUtils.isEmpty(receivedText)) {
final var fullNote$ = mainViewModel.getFullNote$(((Note) adapter.getItem(position)).getId());
final LiveData<Note> fullNote$ = mainViewModel.getFullNote$(((Note) adapter.getItem(position)).getId());
fullNote$.observe(this, (fullNote) -> {
fullNote$.removeObservers(this);
final String oldContent = fullNote.getContent();
@ -47,7 +47,7 @@ public class AppendToNoteActivity extends MainActivity {
} else {
newContent = receivedText;
}
final var updateLiveData = mainViewModel.updateNoteAndSync(fullNote, newContent, null);
LiveData<Void> updateLiveData = mainViewModel.updateNoteAndSync(fullNote, newContent, null);
updateLiveData.observe(this, (next) -> {
Toast.makeText(this, getString(R.string.added_content, receivedText), Toast.LENGTH_SHORT).show();
updateLiveData.removeObservers(this);

View file

@ -35,7 +35,7 @@ public class FormattingHelpActivity extends BrandedActivity {
binding.content.setMovementMethod(LinkMovementMethod.getInstance());
binding.content.setMarkdownString(buildFormattingHelp());
final var sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
binding.content.setTextSize(TypedValue.COMPLEX_UNIT_PX, getFontSizeFromPreferences(this, sp));
if (sp.getBoolean(getString(R.string.pref_key_font), false)) {
binding.content.setTypeface(Typeface.MONOSPACE);

View file

@ -99,11 +99,11 @@ public abstract class LockedActivity extends BrandedActivity {
private void askToUnlock() {
if (NotesApplication.isLocked()) {
final var keyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
if (keyguardManager != null) {
final var intent = keyguardManager.createConfirmDeviceCredentialIntent(getString(R.string.unlock_notes), null);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivityForResult(intent, REQUEST_CODE_UNLOCK);
Intent i = keyguardManager.createConfirmDeviceCredentialIntent(getString(R.string.unlock_notes), null);
i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivityForResult(i, REQUEST_CODE_UNLOCK);
} else {
Log.e(TAG, "Keyguard manager is null");
}

View file

@ -27,7 +27,7 @@ public class NotesApplication extends Application {
public void onCreate() {
PREF_KEY_THEME = getString(R.string.pref_key_theme);
setAppTheme(getAppTheme(getApplicationContext()));
final var prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
lockedPreference = prefs.getBoolean(getString(R.string.pref_key_lock), false);
isGridViewEnabled = getDefaultSharedPreferences(this).getBoolean(getString(R.string.pref_key_gridview), false);
super.onCreate();
@ -46,12 +46,12 @@ public class NotesApplication extends Application {
}
public static DarkModeSetting getAppTheme(Context context) {
final var prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
String mode;
try {
mode = prefs.getString(PREF_KEY_THEME, DarkModeSetting.SYSTEM_DEFAULT.name());
} catch (ClassCastException e) {
final boolean darkModeEnabled = prefs.getBoolean(PREF_KEY_THEME, false);
boolean darkModeEnabled = prefs.getBoolean(PREF_KEY_THEME, false);
mode = darkModeEnabled ? DarkModeSetting.DARK.name() : DarkModeSetting.LIGHT.name();
}
return DarkModeSetting.valueOf(mode);

View file

@ -19,7 +19,7 @@ public class SplashscreenActivity extends AppCompatActivity {
super.onCreate(savedInstanceState);
Thread.currentThread().setUncaughtExceptionHandler(new ExceptionHandler(this));
final var intent = new Intent(this, MainActivity.class);
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
}

View file

@ -16,10 +16,10 @@ public class AboutFragmentContributingTab extends Fragment {
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final var binding = FragmentAboutContributionTabBinding.inflate(inflater, container, false);
SupportUtil.setHtml(binding.aboutSource, R.string.about_source, getString(R.string.url_source));
SupportUtil.setHtml(binding.aboutIssues, R.string.about_issues, getString(R.string.url_issues));
SupportUtil.setHtml(binding.aboutTranslate, R.string.about_translate, getString(R.string.url_translations));
return binding.getRoot();
FragmentAboutContributionTabBinding b = FragmentAboutContributionTabBinding.inflate(inflater, container, false);
SupportUtil.setHtml(b.aboutSource, R.string.about_source, getString(R.string.url_source));
SupportUtil.setHtml(b.aboutIssues, R.string.about_issues, getString(R.string.url_issues));
SupportUtil.setHtml(b.aboutTranslate, R.string.about_translate, getString(R.string.url_translations));
return b.getRoot();
}
}

View file

@ -17,7 +17,7 @@ public class AboutFragmentCreditsTab extends Fragment {
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final var binding = FragmentAboutCreditsTabBinding.inflate(inflater, container, false);
FragmentAboutCreditsTabBinding binding = FragmentAboutCreditsTabBinding.inflate(inflater, container, false);
SupportUtil.setHtml(binding.aboutVersion, R.string.about_version, "v" + BuildConfig.VERSION_NAME);
SupportUtil.setHtml(binding.aboutMaintainer, R.string.about_maintainer);
SupportUtil.setHtml(binding.aboutTranslators, R.string.about_translators_transifex, getString(R.string.url_translations));

View file

@ -56,15 +56,16 @@ public class AccountPickerDialogFragment extends BrandedDialogFragment {
} else {
throw new ClassCastException("Caller must implement " + AccountPickerListener.class.getSimpleName());
}
final var args = requireArguments();
final Bundle args = requireArguments();
final Collection<?> accounts;
if (!args.containsKey(PARAM_TARGET_ACCOUNTS)) {
throw new IllegalArgumentException(PARAM_TARGET_ACCOUNTS + " is required.");
}
final var accounts = (Collection<?>) args.getSerializable(PARAM_TARGET_ACCOUNTS);
accounts = (Collection<?>) args.getSerializable(PARAM_TARGET_ACCOUNTS);
if (accounts == null) {
throw new IllegalArgumentException(PARAM_TARGET_ACCOUNTS + " is required.");
}
final long currentAccountId = requireArguments().getLong(PARAM_CURRENT_ACCOUNT_ID, -1L);
long currentAccountId = requireArguments().getLong(PARAM_CURRENT_ACCOUNT_ID, -1L);
targetAccounts = accounts
.stream()
.map(a -> (Account) a)
@ -75,13 +76,13 @@ public class AccountPickerDialogFragment extends BrandedDialogFragment {
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final var dialogBuilder = new BrandedAlertDialogBuilder(requireActivity())
final AlertDialog.Builder dialogBuilder = new BrandedAlertDialogBuilder(requireActivity())
.setTitle(R.string.simple_move)
.setNegativeButton(android.R.string.cancel, null);
if (targetAccounts.size() > 0) {
final var binding = DialogChooseAccountBinding.inflate(LayoutInflater.from(requireContext()));
final var adapter = new AccountChooserAdapter(targetAccounts, (account -> {
final DialogChooseAccountBinding binding = DialogChooseAccountBinding.inflate(LayoutInflater.from(requireContext()));
RecyclerView.Adapter<AccountChooserViewHolder> adapter = new AccountChooserAdapter(targetAccounts, (account -> {
accountPickerListener.onAccountPicked(account);
dismiss();
}));
@ -102,8 +103,8 @@ public class AccountPickerDialogFragment extends BrandedDialogFragment {
}
public static DialogFragment newInstance(@NonNull ArrayList<Account> targetAccounts, long currentAccountId) {
final var fragment = new AccountPickerDialogFragment();
final var args = new Bundle();
final DialogFragment fragment = new AccountPickerDialogFragment();
final Bundle args = new Bundle();
args.putSerializable(PARAM_TARGET_ACCOUNTS, targetAccounts);
args.putLong(PARAM_CURRENT_ACCOUNT_ID, currentAccountId);
fragment.setArguments(args);

View file

@ -47,7 +47,7 @@ public class AccountSwitcherDialog extends BrandedDialogFragment {
throw new ClassCastException("Caller must implement " + AccountSwitcherListener.class.getSimpleName());
}
final var args = getArguments();
final Bundle args = getArguments();
if (args == null || !args.containsKey(KEY_CURRENT_ACCOUNT_ID)) {
throw new IllegalArgumentException("Please provide at least " + KEY_CURRENT_ACCOUNT_ID);
@ -63,7 +63,7 @@ public class AccountSwitcherDialog extends BrandedDialogFragment {
public Dialog onCreateDialog(Bundle savedInstanceState) {
binding = DialogAccountSwitcherBinding.inflate(requireActivity().getLayoutInflater());
final var account$ = repo.getAccountById$(currentAccountId);
final LiveData<Account> account$ = repo.getAccountById$(currentAccountId);
account$.observe(requireActivity(), (currentLocalAccount) -> {
account$.removeObservers(requireActivity());
@ -76,15 +76,15 @@ public class AccountSwitcherDialog extends BrandedDialogFragment {
.into(binding.currentAccountItemAvatar);
binding.accountLayout.setOnClickListener((v) -> dismiss());
final var adapter = new AccountSwitcherAdapter((localAccount -> {
final AccountSwitcherAdapter adapter = new AccountSwitcherAdapter((localAccount -> {
accountSwitcherListener.onAccountChosen(localAccount);
dismiss();
}));
binding.accountsList.setAdapter(adapter);
final var localAccounts$ = repo.getAccounts$();
final LiveData<List<Account>> localAccounts$ = repo.getAccounts$();
localAccounts$.observe(requireActivity(), (localAccounts) -> {
localAccounts$.removeObservers(requireActivity());
for (final var localAccount : localAccounts) {
for (Account localAccount : localAccounts) {
if (localAccount.getId() == currentLocalAccount.getId()) {
localAccounts.remove(localAccount);
break;
@ -110,9 +110,9 @@ public class AccountSwitcherDialog extends BrandedDialogFragment {
}
public static DialogFragment newInstance(long currentAccountId) {
final var dialog = new AccountSwitcherDialog();
DialogFragment dialog = new AccountSwitcherDialog();
final var args = new Bundle();
Bundle args = new Bundle();
args.putLong(KEY_CURRENT_ACCOUNT_ID, currentAccountId);
dialog.setArguments(args);

View file

@ -34,7 +34,7 @@ public abstract class BrandedActivity extends AppCompatActivity implements Brand
protected void onStart() {
super.onStart();
final var typedValue = new TypedValue();
final TypedValue typedValue = new TypedValue();
getTheme().resolveAttribute(R.attr.colorAccent, typedValue, true);
colorAccent = typedValue.data;
@ -53,13 +53,13 @@ public abstract class BrandedActivity extends AppCompatActivity implements Brand
// FIXME Workaround for https://github.com/stefan-niedermann/nextcloud-notes/issues/889
appBarLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.primary));
final var overflowDrawable = toolbar.getOverflowIcon();
final Drawable overflowDrawable = toolbar.getOverflowIcon();
if (overflowDrawable != null) {
overflowDrawable.setColorFilter(colorAccent, PorterDuff.Mode.SRC_ATOP);
toolbar.setOverflowIcon(overflowDrawable);
}
final var navigationDrawable = toolbar.getNavigationIcon();
final Drawable navigationDrawable = toolbar.getNavigationIcon();
if (navigationDrawable != null) {
navigationDrawable.setColorFilter(colorAccent, PorterDuff.Mode.SRC_ATOP);
toolbar.setNavigationIcon(navigationDrawable);

View file

@ -24,7 +24,7 @@ public class BrandedAlertDialogBuilder extends AlertDialog.Builder implements Br
public AlertDialog create() {
this.dialog = super.create();
@NonNull final var context = getContext();
@NonNull Context context = getContext();
@ColorInt final int mainColor = BrandingUtil.readBrandMainColor(context);
@ColorInt final int textColor = BrandingUtil.readBrandTextColor(context);
applyBrand(mainColor, textColor);
@ -35,11 +35,11 @@ public class BrandedAlertDialogBuilder extends AlertDialog.Builder implements Br
@CallSuper
@Override
public void applyBrand(int mainColor, int textColor) {
final var buttons = new Button[3];
final Button[] buttons = new Button[3];
buttons[0] = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
buttons[1] = dialog.getButton(DialogInterface.BUTTON_NEGATIVE);
buttons[2] = dialog.getButton(DialogInterface.BUTTON_NEUTRAL);
for (final var button : buttons) {
for (Button button : buttons) {
if (button != null) {
button.setTextColor(getSecondaryForegroundColorDependingOnTheme(button.getContext(), mainColor));
}

View file

@ -18,7 +18,7 @@ public class BrandedDeleteAlertDialogBuilder extends BrandedAlertDialogBuilder {
@Override
public void applyBrand(int mainColor, int textColor) {
super.applyBrand(mainColor, textColor);
final var positiveButton = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
final Button positiveButton = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
if (positiveButton != null) {
positiveButton.setTextColor(getContext().getResources().getColor(R.color.bg_attention));
}

View file

@ -12,9 +12,11 @@ public abstract class BrandedDialogFragment extends DialogFragment implements Br
public void onStart() {
super.onStart();
@Nullable final var context = requireContext();
@ColorInt final int mainColor = BrandingUtil.readBrandMainColor(context);
@ColorInt final int textColor = BrandingUtil.readBrandTextColor(context);
applyBrand(mainColor, textColor);
@Nullable Context context = getContext();
if (context != null) {
@ColorInt final int mainColor = BrandingUtil.readBrandMainColor(context);
@ColorInt final int textColor = BrandingUtil.readBrandTextColor(context);
applyBrand(mainColor, textColor);
}
}
}

View file

@ -25,16 +25,18 @@ public abstract class BrandedFragment extends Fragment implements Branded {
public void onStart() {
super.onStart();
final var context = requireContext();
final var typedValue = new TypedValue();
context.getTheme().resolveAttribute(R.attr.colorAccent, typedValue, true);
final TypedValue typedValue = new TypedValue();
requireActivity().getTheme().resolveAttribute(R.attr.colorAccent, typedValue, true);
colorAccent = typedValue.data;
context.getTheme().resolveAttribute(R.attr.colorPrimary, typedValue, true);
requireActivity().getTheme().resolveAttribute(R.attr.colorPrimary, typedValue, true);
colorPrimary = typedValue.data;
@ColorInt final int mainColor = BrandingUtil.readBrandMainColor(context);
@ColorInt final int textColor = BrandingUtil.readBrandTextColor(context);
applyBrand(mainColor, textColor);
@Nullable Context context = getContext();
if (context != null) {
@ColorInt final int mainColor = BrandingUtil.readBrandMainColor(context);
@ColorInt final int textColor = BrandingUtil.readBrandTextColor(context);
applyBrand(mainColor, textColor);
}
}
@Override

View file

@ -34,11 +34,11 @@ public class BrandedPreferenceCategory extends PreferenceCategory {
public void onBindViewHolder(PreferenceViewHolder holder) {
super.onBindViewHolder(holder);
final var view = holder.itemView.findViewById(android.R.id.title);
@Nullable final var context = getContext();
if (context != null && view instanceof TextView) {
final View v = holder.itemView.findViewById(android.R.id.title);
@Nullable final Context context = getContext();
if (context != null && v instanceof TextView) {
@ColorInt final int mainColor = getSecondaryForegroundColorDependingOnTheme(context, BrandingUtil.readBrandMainColor(context));
((TextView) view).setTextColor(mainColor);
((TextView) v).setTextColor(mainColor);
}
}
}

View file

@ -14,7 +14,7 @@ public class BrandedSnackbar {
@NonNull
public static Snackbar make(@NonNull View view, @NonNull CharSequence text, @Snackbar.Duration int duration) {
final var snackbar = Snackbar.make(view, text, duration);
final Snackbar snackbar = Snackbar.make(view, text, duration);
final int color = BrandingUtil.readBrandMainColor(view.getContext());
snackbar.setActionTextColor(ColorUtil.INSTANCE.isColorDark(color) ? Color.WHITE : color);
return snackbar;

View file

@ -1,6 +1,5 @@
package it.niedermann.owncloud.notes.branding;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.Color;
@ -27,7 +26,6 @@ public class BrandedSwitchPreference extends SwitchPreference implements Branded
@ColorInt
private Integer textColor = null;
@SuppressLint("UseSwitchCompatOrMaterialCode")
@Nullable
private Switch switchView;
@ -94,11 +92,11 @@ public class BrandedSwitchPreference extends SwitchPreference implements Branded
return (Switch) view;
}
if (view instanceof ViewGroup) {
final var viewGroup = (ViewGroup) view;
ViewGroup viewGroup = (ViewGroup) view;
for (int i = 0; i < viewGroup.getChildCount(); i++) {
final var child = viewGroup.getChildAt(i);
View child = viewGroup.getChildAt(i);
if (child instanceof ViewGroup) {
@SuppressLint("UseSwitchCompatOrMaterialCode") final var result = findSwitchWidget(child);
Switch result = findSwitchWidget(child);
if (result != null) return result;
}
if (child instanceof Switch) {

View file

@ -64,27 +64,27 @@ public class BrandingUtil {
}
public static LiveData<Integer> readBrandMainColorLiveData(@NonNull Context context) {
final var sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
Log.v(TAG, "--- Read: shared_preference_theme_main");
return new SharedPreferenceIntLiveData(sharedPreferences, pref_key_branding_main, context.getApplicationContext().getResources().getColor(R.color.defaultBrand));
}
public static LiveData<Integer> readBrandTextColorLiveData(@NonNull Context context) {
final var sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
Log.v(TAG, "--- Read: shared_preference_theme_text");
return new SharedPreferenceIntLiveData(sharedPreferences, pref_key_branding_text, Color.WHITE);
}
@ColorInt
public static int readBrandMainColor(@NonNull Context context) {
final var sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
Log.v(TAG, "--- Read: shared_preference_theme_main");
return sharedPreferences.getInt(pref_key_branding_main, context.getApplicationContext().getResources().getColor(R.color.defaultBrand));
}
@ColorInt
public static int readBrandTextColor(@NonNull Context context) {
final var sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
Log.v(TAG, "--- Read: shared_preference_theme_text");
return sharedPreferences.getInt(pref_key_branding_text, Color.WHITE);
}
@ -92,7 +92,7 @@ public class BrandingUtil {
public static void saveBrandColors(@NonNull Context context, @ColorInt int mainColor, @ColorInt int textColor) {
final int previousMainColor = readBrandMainColor(context);
final int previousTextColor = readBrandTextColor(context);
final var editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
final SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
Log.v(TAG, "--- Write: shared_preference_theme_main" + " | " + mainColor);
Log.v(TAG, "--- Write: shared_preference_theme_text" + " | " + textColor);
editor.putInt(pref_key_branding_main, mainColor);
@ -100,7 +100,7 @@ public class BrandingUtil {
editor.apply();
if (context instanceof BrandedActivity) {
if (mainColor != previousMainColor || textColor != previousTextColor) {
final var activity = (BrandedActivity) context;
final BrandedActivity activity = (BrandedActivity) context;
activity.runOnUiThread(() -> ActivityCompat.recreate(activity));
}
}
@ -145,7 +145,7 @@ public class BrandingUtil {
}
public static void tintMenuIcon(@NonNull MenuItem menuItem, @ColorInt int color) {
var drawable = menuItem.getIcon();
Drawable drawable = menuItem.getIcon();
if (drawable != null) {
drawable = DrawableCompat.wrap(drawable);
DrawableCompat.setTint(drawable, color);
@ -154,7 +154,7 @@ public class BrandingUtil {
}
public static void applyBrandToLayerDrawable(@NonNull LayerDrawable check, @IdRes int areaToColor, @ColorInt int mainColor) {
final var drawable = check.findDrawableByLayerId(areaToColor);
final Drawable drawable = check.findDrawableByLayerId(areaToColor);
if (drawable == null) {
Log.e(TAG, "Could not find areaToColor (" + areaToColor + "). Cannot apply brand.");
} else {

View file

@ -103,13 +103,13 @@ public abstract class BaseNoteFragment extends BrandedFragment implements Catego
super.onViewCreated(view, savedInstanceState);
executor.submit(() -> {
try {
final var ssoAccount = SingleAccountHelper.getCurrentSingleSignOnAccount(requireContext().getApplicationContext());
SingleSignOnAccount ssoAccount = SingleAccountHelper.getCurrentSingleSignOnAccount(requireContext().getApplicationContext());
this.localAccount = repo.getAccountByName(ssoAccount.name);
if (savedInstanceState == null) {
final long id = requireArguments().getLong(PARAM_NOTE_ID);
long id = requireArguments().getLong(PARAM_NOTE_ID);
if (id > 0) {
final long accountId = requireArguments().getLong(PARAM_ACCOUNT_ID);
long accountId = requireArguments().getLong(PARAM_ACCOUNT_ID);
if (accountId > 0) {
/* Switch account if account id has been provided */
this.localAccount = repo.getAccountById(accountId);
@ -120,8 +120,8 @@ public abstract class BaseNoteFragment extends BrandedFragment implements Catego
requireActivity().runOnUiThread(() -> onNoteLoaded(note));
requireActivity().invalidateOptionsMenu();
} else {
final var cloudNote = (Note) requireArguments().getSerializable(PARAM_NEWNOTE);
final var content = requireArguments().getString(PARAM_CONTENT);
Note cloudNote = (Note) requireArguments().getSerializable(PARAM_NEWNOTE);
String content = requireArguments().getString(PARAM_CONTENT);
if (cloudNote == null) {
if (content == null) {
throw new IllegalArgumentException(PARAM_NOTE_ID + " is not given, argument " + PARAM_NEWNOTE + " is missing and " + PARAM_CONTENT + " is missing.");
@ -198,7 +198,7 @@ public abstract class BaseNoteFragment extends BrandedFragment implements Catego
if (note != null) {
prepareFavoriteOption(menu.findItem(R.id.menu_favorite));
final var preferredApiVersion = ApiVersionUtil.getPreferredApiVersion(localAccount.getApiVersion());
final ApiVersion preferredApiVersion = ApiVersionUtil.getPreferredApiVersion(localAccount.getApiVersion());
menu.findItem(R.id.menu_title).setVisible(preferredApiVersion != null && preferredApiVersion.compareTo(ApiVersion.API_VERSION_1_0) >= 0);
menu.findItem(R.id.menu_delete).setVisible(!isNew);
}
@ -215,7 +215,7 @@ public abstract class BaseNoteFragment extends BrandedFragment implements Catego
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
final int itemId = item.getItemId();
int itemId = item.getItemId();
if (itemId == R.id.menu_cancel) {
executor.submit(() -> {
if (originalNote == null) {
@ -251,10 +251,10 @@ public abstract class BaseNoteFragment extends BrandedFragment implements Catego
return false;
} else if (itemId == MENU_ID_PIN) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
final var shortcutManager = requireActivity().getSystemService(ShortcutManager.class);
final ShortcutManager shortcutManager = requireActivity().getSystemService(ShortcutManager.class);
if (shortcutManager != null) {
if (shortcutManager.isRequestPinShortcutSupported()) {
final var pinShortcutInfo = new ShortcutInfo.Builder(getActivity(), note.getId() + "")
final ShortcutInfo pinShortcutInfo = new ShortcutInfo.Builder(getActivity(), note.getId() + "")
.setShortLabel(note.getTitle())
.setIcon(Icon.createWithResource(requireActivity().getApplicationContext(), TRUE.equals(note.getFavorite()) ? R.drawable.ic_star_yellow_24dp : R.drawable.ic_star_grey_ccc_24dp))
.setIntent(new Intent(getActivity(), EditNoteActivity.class).putExtra(EditNoteActivity.PARAM_NOTE_ID, note.getId()).setAction(ACTION_SHORTCUT))
@ -278,7 +278,7 @@ public abstract class BaseNoteFragment extends BrandedFragment implements Catego
protected void onNoteLoaded(Note note) {
this.originalScrollY = note.getScrollY();
scrollToY(originalScrollY);
final var scrollView = getScrollView();
final ScrollView scrollView = getScrollView();
if (scrollView != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
scrollView.setOnScrollChangeListener((View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) -> {
@ -304,7 +304,7 @@ public abstract class BaseNoteFragment extends BrandedFragment implements Catego
protected void saveNote(@Nullable ISyncCallback callback) {
Log.d(TAG, "saveData()");
if (note != null) {
final var newContent = getContent();
final String newContent = getContent();
if (note.getContent().equals(newContent)) {
if (note.getScrollY() != originalScrollY) {
Log.v(TAG, "... only saving new scroll state, since content did not change");
@ -329,13 +329,13 @@ public abstract class BaseNoteFragment extends BrandedFragment implements Catego
* Opens a dialog in order to chose a category
*/
private void showCategorySelector() {
final var fragmentId = "fragment_category";
final var manager = requireActivity().getSupportFragmentManager();
final var frag = manager.findFragmentByTag(fragmentId);
final String fragmentId = "fragment_category";
FragmentManager manager = requireActivity().getSupportFragmentManager();
Fragment frag = manager.findFragmentByTag(fragmentId);
if (frag != null) {
manager.beginTransaction().remove(frag).commit();
}
final var categoryFragment = CategoryDialogFragment.newInstance(note.getAccountId(), note.getCategory());
final DialogFragment categoryFragment = CategoryDialogFragment.newInstance(note.getAccountId(), note.getCategory());
categoryFragment.setTargetFragment(this, 0);
categoryFragment.show(manager, fragmentId);
}
@ -345,13 +345,13 @@ public abstract class BaseNoteFragment extends BrandedFragment implements Catego
*/
public void showEditTitleDialog() {
saveNote(null);
final var fragmentId = "fragment_edit_title";
final var manager = requireActivity().getSupportFragmentManager();
final var frag = manager.findFragmentByTag(fragmentId);
final String fragmentId = "fragment_edit_title";
FragmentManager manager = requireActivity().getSupportFragmentManager();
Fragment frag = manager.findFragmentByTag(fragmentId);
if (frag != null) {
manager.beginTransaction().remove(frag).commit();
}
final var editTitleFragment = EditTitleDialogFragment.newInstance(note.getTitle());
DialogFragment editTitleFragment = EditTitleDialogFragment.newInstance(note.getTitle());
editTitleFragment.setTargetFragment(this, 0);
editTitleFragment.show(manager, fragmentId);
}
@ -374,7 +374,7 @@ public abstract class BaseNoteFragment extends BrandedFragment implements Catego
}
public void moveNote(Account account) {
final var moveLiveData = repo.moveNoteToAnotherAccount(account, note);
final LiveData<Note> moveLiveData = repo.moveNoteToAnotherAccount(account, note);
moveLiveData.observe(this, (v) -> moveLiveData.removeObservers(this));
listener.close();
}

View file

@ -131,15 +131,15 @@ public class EditNoteActivity extends LockedActivity implements BaseNoteFragment
* @param noteId ID of the existing note.
*/
private void launchExistingNote(long accountId, long noteId) {
final var prefKeyNoteMode = getString(R.string.pref_key_note_mode);
final var prefKeyLastMode = getString(R.string.pref_key_last_note_mode);
final var prefValueEdit = getString(R.string.pref_value_mode_edit);
final var prefValuePreview = getString(R.string.pref_value_mode_preview);
final var prefValueLast = getString(R.string.pref_value_mode_last);
final String prefKeyNoteMode = getString(R.string.pref_key_note_mode);
final String prefKeyLastMode = getString(R.string.pref_key_last_note_mode);
final String prefValueEdit = getString(R.string.pref_value_mode_edit);
final String prefValuePreview = getString(R.string.pref_value_mode_preview);
final String prefValueLast = getString(R.string.pref_value_mode_last);
final var preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
final String mode = preferences.getString(prefKeyNoteMode, prefValueEdit);
final String lastMode = preferences.getString(prefKeyLastMode, prefValueEdit);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String mode = preferences.getString(prefKeyNoteMode, prefValueEdit);
String lastMode = preferences.getString(prefKeyLastMode, prefValueEdit);
boolean editMode = true;
if (prefValuePreview.equals(mode) || (prefValueLast.equals(mode) && prefValuePreview.equals(lastMode))) {
editMode = false;
@ -176,7 +176,7 @@ public class EditNoteActivity extends LockedActivity implements BaseNoteFragment
* Content ("share" functionality), category and favorite attribute can be preset.
*/
private void launchNewNote() {
final var intent = getIntent();
Intent intent = getIntent();
String categoryTitle = "";
boolean favorite = false;
@ -204,19 +204,19 @@ public class EditNoteActivity extends LockedActivity implements BaseNoteFragment
if (content == null) {
content = "";
}
final var newNote = new Note(null, Calendar.getInstance(), NoteUtil.generateNonEmptyNoteTitle(content, this), content, categoryTitle, favorite, null);
Note newNote = new Note(null, Calendar.getInstance(), NoteUtil.generateNonEmptyNoteTitle(content, this), content, categoryTitle, favorite, null);
fragment = NoteEditFragment.newInstanceWithNewNote(newNote);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_view, fragment).commit();
}
private void launchReadonlyNote() {
final var intent = getIntent();
final var content = new StringBuilder();
Intent intent = getIntent();
StringBuilder content = new StringBuilder();
try {
final var inputStream = getContentResolver().openInputStream(Objects.requireNonNull(intent.getData()));
final var bufferedReader = new BufferedReader(new InputStreamReader(Objects.requireNonNull(inputStream)));
InputStream inputStream = getContentResolver().openInputStream(Objects.requireNonNull(intent.getData()));
BufferedReader r = new BufferedReader(new InputStreamReader(Objects.requireNonNull(inputStream)));
String line;
while ((line = bufferedReader.readLine()) != null) {
while ((line = r.readLine()) != null) {
content.append(line).append('\n');
}
} catch (IOException e) {
@ -241,7 +241,7 @@ public class EditNoteActivity extends LockedActivity implements BaseNoteFragment
@Override
public boolean onOptionsItemSelected(MenuItem item) {
final int itemId = item.getItemId();
int itemId = item.getItemId();
if (itemId == android.R.id.home) {
close();
return true;
@ -263,7 +263,7 @@ public class EditNoteActivity extends LockedActivity implements BaseNoteFragment
/* TODO enhancement: store last mode in note
* for cross device functionality per note mode should be stored on the server.
*/
final var preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
final String prefKeyLastMode = getString(R.string.pref_key_last_note_mode);
if (fragment instanceof NoteEditFragment) {
preferences.edit().putString(prefKeyLastMode, getString(R.string.pref_value_mode_edit)).apply();

View file

@ -156,7 +156,7 @@ public class NoteEditFragment extends SearchableBaseNoteFragment {
binding.editContent.setMarkdownString(note.getContent());
binding.editContent.setEnabled(true);
final var sp = PreferenceManager.getDefaultSharedPreferences(requireContext().getApplicationContext());
final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(requireContext().getApplicationContext());
binding.editContent.setTextSize(TypedValue.COMPLEX_UNIT_PX, getFontSizeFromPreferences(requireContext(), sp));
if (sp.getBoolean(getString(R.string.pref_key_font), false)) {
binding.editContent.setTypeface(Typeface.MONOSPACE);
@ -167,7 +167,7 @@ public class NoteEditFragment extends SearchableBaseNoteFragment {
binding.editContent.postDelayed(() -> {
binding.editContent.requestFocus();
final var imm = (InputMethodManager) requireContext().getSystemService(Context.INPUT_METHOD_SERVICE);
final InputMethodManager imm = (InputMethodManager) requireContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.showSoftInput(binding.editContent, InputMethodManager.SHOW_IMPLICIT);
} else {
@ -202,7 +202,7 @@ public class NoteEditFragment extends SearchableBaseNoteFragment {
*/
@Override
protected String getContent() {
final var editable = binding.editContent.getText();
final Editable editable = binding.editContent.getText();
return editable == null ? "" : editable.toString();
}
@ -257,8 +257,8 @@ public class NoteEditFragment extends SearchableBaseNoteFragment {
}
public static BaseNoteFragment newInstance(long accountId, long noteId) {
final var fragment = new NoteEditFragment();
final var args = new Bundle();
final BaseNoteFragment fragment = new NoteEditFragment();
final Bundle args = new Bundle();
args.putLong(PARAM_NOTE_ID, noteId);
args.putLong(PARAM_ACCOUNT_ID, accountId);
fragment.setArguments(args);
@ -266,8 +266,8 @@ public class NoteEditFragment extends SearchableBaseNoteFragment {
}
public static BaseNoteFragment newInstanceWithNewNote(Note newNote) {
final var fragment = new NoteEditFragment();
final var args = new Bundle();
final BaseNoteFragment fragment = new NoteEditFragment();
final Bundle args = new Bundle();
args.putSerializable(PARAM_NEWNOTE, newNote);
fragment.setArguments(args);
return fragment;

View file

@ -102,7 +102,7 @@ public class NotePreviewFragment extends SearchableBaseNoteFragment implements O
registerInternalNoteLinkHandler();
binding.singleNoteContent.setMovementMethod(LinkMovementMethod.getInstance());
final var sp = PreferenceManager.getDefaultSharedPreferences(requireActivity().getApplicationContext());
final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(requireActivity().getApplicationContext());
binding.singleNoteContent.setTextSize(TypedValue.COMPLEX_UNIT_PX, getFontSizeFromPreferences(requireContext(), sp));
if (sp.getBoolean(getString(R.string.pref_key_font), false)) {
binding.singleNoteContent.setTypeface(Typeface.MONOSPACE);
@ -157,7 +157,7 @@ public class NotePreviewFragment extends SearchableBaseNoteFragment implements O
binding.swiperefreshlayout.setRefreshing(true);
executor.submit(() -> {
try {
final var account = repo.getAccountByName(SingleAccountHelper.getCurrentSingleSignOnAccount(requireContext()).name);
final Account account = repo.getAccountByName(SingleAccountHelper.getCurrentSingleSignOnAccount(requireContext()).name);
repo.addCallbackPull(account, () -> executor.submit(() -> {
note = repo.getNoteById(note.getId());
changedText = note.getContent();
@ -185,8 +185,8 @@ public class NotePreviewFragment extends SearchableBaseNoteFragment implements O
}
public static BaseNoteFragment newInstance(long accountId, long noteId) {
final var fragment = new NotePreviewFragment();
final var args = new Bundle();
final BaseNoteFragment fragment = new NotePreviewFragment();
final Bundle args = new Bundle();
args.putLong(PARAM_NOTE_ID, noteId);
args.putLong(PARAM_ACCOUNT_ID, accountId);
fragment.setArguments(args);

View file

@ -60,8 +60,8 @@ public class NoteReadonlyFragment extends NotePreviewFragment {
}
public static BaseNoteFragment newInstance(String content) {
final var fragment = new NoteReadonlyFragment();
final var args = new Bundle();
final BaseNoteFragment fragment = new NoteReadonlyFragment();
final Bundle args = new Bundle();
args.putString(PARAM_CONTENT, content);
fragment.setArguments(args);
return fragment;

View file

@ -65,7 +65,7 @@ public abstract class SearchableBaseNoteFragment extends BaseNoteFragment {
public void onPrepareOptionsMenu(@NonNull Menu menu) {
super.onPrepareOptionsMenu(menu);
final var searchMenuItem = menu.findItem(R.id.search);
MenuItem searchMenuItem = menu.findItem(R.id.search);
searchView = (SearchView) searchMenuItem.getActionView();
if (!TextUtils.isEmpty(searchQuery) && isNew) {
@ -77,7 +77,7 @@ public abstract class SearchableBaseNoteFragment extends BaseNoteFragment {
}
final var searchEditFrame = searchView.findViewById(R.id
final LinearLayout searchEditFrame = searchView.findViewById(R.id
.search_edit_frame);
searchEditFrame.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@ -85,7 +85,7 @@ public abstract class SearchableBaseNoteFragment extends BaseNoteFragment {
@Override
public void onGlobalLayout() {
final int currentVisibility = searchEditFrame.getVisibility();
int currentVisibility = searchEditFrame.getVisibility();
if (currentVisibility != oldVisibility) {
if (currentVisibility != View.VISIBLE) {
@ -105,8 +105,8 @@ public abstract class SearchableBaseNoteFragment extends BaseNoteFragment {
});
final var next = getSearchNextButton();
final var prev = getSearchPrevButton();
FloatingActionButton next = getSearchNextButton();
FloatingActionButton prev = getSearchPrevButton();
if (next != null) {
next.setOnClickListener(v -> {
@ -208,8 +208,8 @@ public abstract class SearchableBaseNoteFragment extends BaseNoteFragment {
protected abstract FloatingActionButton getSearchPrevButton();
private void showSearchFabs() {
final var next = getSearchNextButton();
final var prev = getSearchPrevButton();
FloatingActionButton next = getSearchNextButton();
FloatingActionButton prev = getSearchPrevButton();
if (prev != null) {
prev.show();
}
@ -219,8 +219,8 @@ public abstract class SearchableBaseNoteFragment extends BaseNoteFragment {
}
private void hideSearchFabs() {
final var next = getSearchNextButton();
final var prev = getSearchPrevButton();
FloatingActionButton next = getSearchNextButton();
FloatingActionButton prev = getSearchPrevButton();
if (prev != null) {
prev.hide();
}
@ -230,7 +230,7 @@ public abstract class SearchableBaseNoteFragment extends BaseNoteFragment {
}
private void jumpToOccurrence() {
final var layout = getLayout();
Layout layout = getLayout();
if (layout == null) {
Log.w(TAG, "getLayout() is null");
} else if (getContent() == null || getContent().isEmpty()) {
@ -240,8 +240,8 @@ public abstract class SearchableBaseNoteFragment extends BaseNoteFragment {
currentOccurrence = occurrenceCount;
jumpToOccurrence();
} else if (searchQuery != null && !searchQuery.isEmpty()) {
final String currentContent = getContent().toLowerCase();
final int indexOfNewText = indexOfNth(currentContent, searchQuery.toLowerCase(), 0, currentOccurrence);
String currentContent = getContent().toLowerCase();
int indexOfNewText = indexOfNth(currentContent, searchQuery.toLowerCase(), 0, currentOccurrence);
if (indexOfNewText <= 0) {
// Search term is not n times in text
// Go back to first search result
@ -251,11 +251,11 @@ public abstract class SearchableBaseNoteFragment extends BaseNoteFragment {
}
return;
}
final String textUntilFirstOccurrence = currentContent.substring(0, indexOfNewText);
final int numberLine = layout.getLineForOffset(textUntilFirstOccurrence.length());
String textUntilFirstOccurrence = currentContent.substring(0, indexOfNewText);
int numberLine = layout.getLineForOffset(textUntilFirstOccurrence.length());
if (numberLine >= 0) {
final var scrollView = getScrollView();
ScrollView scrollView = getScrollView();
if (scrollView != null) {
scrollView.post(() -> scrollView.smoothScrollTo(0, layout.getLineTop(numberLine)));
}
@ -268,7 +268,7 @@ public abstract class SearchableBaseNoteFragment extends BaseNoteFragment {
throw new IllegalArgumentException("Param 'nth' must be greater than 0!");
if (nth == 1)
return input.indexOf(value, startIndex);
final int idx = input.indexOf(value, startIndex);
int idx = input.indexOf(value, startIndex);
if (idx == -1)
return -1;
return indexOfNth(input, value, idx + 1, nth - 1);
@ -281,11 +281,11 @@ public abstract class SearchableBaseNoteFragment extends BaseNoteFragment {
// Use regrex which is faster before.
// Such that the main thread will not stop for a long tilme
// And so there will not an ANR problem
final var matcher = Pattern.compile(needle, Pattern.CASE_INSENSITIVE | Pattern.LITERAL)
Matcher m = Pattern.compile(needle, Pattern.CASE_INSENSITIVE | Pattern.LITERAL)
.matcher(haystack);
int count = 0;
while (matcher.find()) {
while (m.find()) {
count++;
}
return count;

View file

@ -27,7 +27,7 @@ public class CategoryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolde
private static final String clearItemId = "clear_item";
private static final String addItemId = "add_item";
@NonNull
private final List<NavigationItem> categories = new ArrayList<>();
private List<NavigationItem> categories = new ArrayList<>();
@NonNull
private final CategoryListener listener;
private final Context context;
@ -40,18 +40,18 @@ public class CategoryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolde
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
final var view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_category, parent, false);
return new CategoryViewHolder(view);
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_category, parent, false);
return new CategoryViewHolder(v);
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
final var category = categories.get(position);
final var categoryViewHolder = (CategoryViewHolder) holder;
NavigationItem category = categories.get(position);
CategoryViewHolder categoryViewHolder = (CategoryViewHolder) holder;
switch (category.id) {
case addItemId:
final var wrapDrawable = DrawableCompat.wrap(ContextCompat.getDrawable(context, category.icon));
Drawable wrapDrawable = DrawableCompat.wrap(ContextCompat.getDrawable(context, category.icon));
DrawableCompat.setTint(wrapDrawable, ContextCompat.getColor(context, R.color.icon_color_default));
categoryViewHolder.getIcon().setImageDrawable(wrapDrawable);
categoryViewHolder.getCategoryWrapper().setOnClickListener((v) -> listener.onCategoryAdded());
@ -110,14 +110,14 @@ public class CategoryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolde
this.categories.add(0, clearItem);
if (currentSearchString != null && currentSearchString.trim().length() > 0) {
boolean currentSearchStringIsInCategories = false;
for (final var category : categories) {
for (NavigationItem category : categories) {
if (currentSearchString.equals(category.label)) {
currentSearchStringIsInCategories = true;
break;
}
}
if (!currentSearchStringIsInCategories) {
final var addItem = new NavigationItem(addItemId, context.getString(R.string.add_category, currentSearchString.trim()), 0, R.drawable.ic_add_blue_24dp);
NavigationItem addItem = new NavigationItem(addItemId, context.getString(R.string.add_category, currentSearchString.trim()), 0, R.drawable.ic_add_blue_24dp);
this.categories.add(addItem);
}
}

View file

@ -77,7 +77,7 @@ public class CategoryDialogFragment extends BrandedDialogFragment {
} else {
throw new IllegalArgumentException("Provide at least \"" + PARAM_ACCOUNT_ID + "\"");
}
final var target = getTargetFragment();
Fragment target = getTargetFragment();
if (target instanceof CategoryDialogListener) {
listener = (CategoryDialogListener) target;
} else if (getActivity() instanceof CategoryDialogListener) {
@ -96,7 +96,7 @@ public class CategoryDialogFragment extends BrandedDialogFragment {
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final var dialogView = View.inflate(getContext(), R.layout.dialog_change_category, null);
View dialogView = View.inflate(getContext(), R.layout.dialog_change_category, null);
binding = DialogChangeCategoryBinding.bind(dialogView);
this.editCategory = binding.search;
@ -187,11 +187,11 @@ public class CategoryDialogFragment extends BrandedDialogFragment {
}
public static DialogFragment newInstance(long accountId, String category) {
final var categoryFragment = new CategoryDialogFragment();
final var args = new Bundle();
args.putString(CategoryDialogFragment.PARAM_CATEGORY, category);
args.putLong(CategoryDialogFragment.PARAM_ACCOUNT_ID, accountId);
categoryFragment.setArguments(args);
final DialogFragment categoryFragment = new CategoryDialogFragment();
final Bundle arguments = new Bundle();
arguments.putString(CategoryDialogFragment.PARAM_CATEGORY, category);
arguments.putLong(CategoryDialogFragment.PARAM_ACCOUNT_ID, accountId);
categoryFragment.setArguments(arguments);
return categoryFragment;
}
}

View file

@ -28,7 +28,7 @@ public class EditTitleDialogFragment extends DialogFragment {
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
final var args = getArguments();
final Bundle args = getArguments();
if (args == null) {
throw new IllegalArgumentException("Provide at least " + PARAM_OLD_TITLE);
}
@ -46,7 +46,7 @@ public class EditTitleDialogFragment extends DialogFragment {
@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
final var dialogView = View.inflate(getContext(), R.layout.dialog_edit_title, null);
View dialogView = View.inflate(getContext(), R.layout.dialog_edit_title, null);
binding = DialogEditTitleBinding.bind(dialogView);
if (savedInstanceState == null) {
@ -66,7 +66,7 @@ public class EditTitleDialogFragment extends DialogFragment {
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
binding.title.requestFocus();
final var window = requireDialog().getWindow();
Window window = requireDialog().getWindow();
if (window != null) {
window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
} else {
@ -75,8 +75,8 @@ public class EditTitleDialogFragment extends DialogFragment {
}
public static DialogFragment newInstance(String title) {
final var fragment = new EditTitleDialogFragment();
final var args = new Bundle();
final DialogFragment fragment = new EditTitleDialogFragment();
final Bundle args = new Bundle();
args.putString(PARAM_OLD_TITLE, title);
fragment.setArguments(args);
return fragment;

View file

@ -26,18 +26,18 @@ public class ExceptionActivity extends AppCompatActivity {
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final var binding = ActivityExceptionBinding.inflate(getLayoutInflater());
final ActivityExceptionBinding binding = ActivityExceptionBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
setSupportActionBar(binding.toolbar);
var throwable = ((Throwable) getIntent().getSerializableExtra(KEY_THROWABLE));
Throwable throwable = ((Throwable) getIntent().getSerializableExtra(KEY_THROWABLE));
if (throwable == null) {
throwable = new Exception("Could not get exception");
}
final var adapter = new TipsAdapter(this::startActivity);
final TipsAdapter adapter = new TipsAdapter(this::startActivity);
final String debugInfos = ExceptionUtil.INSTANCE.getDebugInfos(this, throwable, BuildConfig.FLAVOR);
binding.tips.setAdapter(adapter);
@ -53,7 +53,7 @@ public class ExceptionActivity extends AppCompatActivity {
@NonNull
public static Intent createIntent(@NonNull Context context, Throwable throwable) {
final var args = new Bundle();
final Bundle args = new Bundle();
args.putSerializable(KEY_THROWABLE, throwable);
return new Intent(context, ExceptionActivity.class)
.putExtras(args)

View file

@ -30,11 +30,11 @@ public class ExceptionDialogFragment extends AppCompatDialogFragment {
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
final var args = getArguments();
final Bundle args = getArguments();
if (args != null) {
final var throwablesArgument = args.getSerializable(KEY_THROWABLES);
final Object throwablesArgument = args.getSerializable(KEY_THROWABLES);
if (throwablesArgument instanceof Iterable<?>) {
for (final var arg : (Iterable<?>) throwablesArgument) {
for (Object arg : (Iterable<?>) throwablesArgument) {
if (arg instanceof Throwable) {
throwables.add((Throwable) arg);
} else {
@ -50,10 +50,10 @@ public class ExceptionDialogFragment extends AppCompatDialogFragment {
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final var view = View.inflate(getContext(), R.layout.dialog_exception, null);
final var binding = DialogExceptionBinding.bind(view);
final View view = View.inflate(getContext(), R.layout.dialog_exception, null);
final DialogExceptionBinding binding = DialogExceptionBinding.bind(view);
final var adapter = new TipsAdapter((actionIntent) -> requireActivity().startActivity(actionIntent));
final TipsAdapter adapter = new TipsAdapter((actionIntent) -> requireActivity().startActivity(actionIntent));
final String debugInfos = ExceptionUtil.INSTANCE.getDebugInfos(requireContext(), throwables, BuildConfig.FLAVOR);
@ -72,19 +72,19 @@ public class ExceptionDialogFragment extends AppCompatDialogFragment {
}
public static DialogFragment newInstance(ArrayList<Throwable> exceptions) {
final var args = new Bundle();
final Bundle args = new Bundle();
args.putSerializable(KEY_THROWABLES, exceptions);
final var fragment = new ExceptionDialogFragment();
final DialogFragment fragment = new ExceptionDialogFragment();
fragment.setArguments(args);
return fragment;
}
public static DialogFragment newInstance(Throwable exception) {
final var args = new Bundle();
final var list = new ArrayList<Throwable>(1);
final Bundle args = new Bundle();
final ArrayList<Throwable> list = new ArrayList<>(1);
list.add(exception);
args.putSerializable(KEY_THROWABLES, list);
final var fragment = new ExceptionDialogFragment();
final DialogFragment fragment = new ExceptionDialogFragment();
fragment.setArguments(args);
return fragment;
}

View file

@ -48,8 +48,8 @@ public class TipsAdapter extends RecyclerView.Adapter<TipsViewHolder> {
@NonNull
@Override
public TipsViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
final var view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_tip, parent, false);
return new TipsViewHolder(view);
final View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_tip, parent, false);
return new TipsViewHolder(v);
}
@Override
@ -63,17 +63,17 @@ public class TipsAdapter extends RecyclerView.Adapter<TipsViewHolder> {
}
public void setThrowables(@NonNull List<Throwable> throwables) {
for (final var throwable : throwables) {
if (throwable instanceof TokenMismatchException) {
for (Throwable t : throwables) {
if (t instanceof TokenMismatchException) {
add(R.string.error_dialog_tip_token_mismatch_retry);
add(R.string.error_dialog_tip_token_mismatch_clear_storage);
final var intent = new Intent(ACTION_APPLICATION_DETAILS_SETTINGS)
Intent intent = new Intent(ACTION_APPLICATION_DETAILS_SETTINGS)
.setData(Uri.parse("package:" + BuildConfig.APPLICATION_ID))
.putExtra(INTENT_EXTRA_BUTTON_TEXT, R.string.error_action_open_deck_info);
add(R.string.error_dialog_tip_clear_storage, intent);
} else if (throwable instanceof NextcloudFilesAppNotSupportedException) {
} else if (t instanceof NextcloudFilesAppNotSupportedException) {
add(R.string.error_dialog_tip_files_outdated);
} else if (throwable instanceof NextcloudApiNotRespondingException) {
} else if (t instanceof NextcloudApiNotRespondingException) {
if (VERSION.SDK_INT >= VERSION_CODES.M) {
add(R.string.error_dialog_tip_disable_battery_optimizations, new Intent().setAction(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS).putExtra(INTENT_EXTRA_BUTTON_TEXT, R.string.error_action_open_battery_settings));
} else {
@ -81,17 +81,17 @@ public class TipsAdapter extends RecyclerView.Adapter<TipsViewHolder> {
}
add(R.string.error_dialog_tip_files_force_stop);
add(R.string.error_dialog_tip_files_delete_storage);
final var intent = new Intent(ACTION_APPLICATION_DETAILS_SETTINGS)
Intent intent = new Intent(ACTION_APPLICATION_DETAILS_SETTINGS)
.setData(Uri.parse("package:" + BuildConfig.APPLICATION_ID))
.putExtra(INTENT_EXTRA_BUTTON_TEXT, R.string.error_action_open_deck_info);
add(R.string.error_dialog_tip_clear_storage, intent);
} else if (throwable instanceof SocketTimeoutException || throwable instanceof ConnectException) {
} else if (t instanceof SocketTimeoutException || t instanceof ConnectException) {
add(R.string.error_dialog_timeout_instance);
add(R.string.error_dialog_timeout_toggle, new Intent(Settings.ACTION_WIFI_SETTINGS).putExtra(INTENT_EXTRA_BUTTON_TEXT, R.string.error_action_open_network));
} else if (throwable instanceof JSONException || throwable instanceof NullPointerException) {
} else if (t instanceof JSONException || t instanceof NullPointerException) {
add(R.string.error_dialog_check_server);
} else if (throwable instanceof NextcloudHttpRequestFailedException) {
final int statusCode = ((NextcloudHttpRequestFailedException) throwable).getStatusCode();
} else if (t instanceof NextcloudHttpRequestFailedException) {
int statusCode = ((NextcloudHttpRequestFailedException) t).getStatusCode();
switch (statusCode) {
case 302:
add(R.string.error_dialog_server_app_enabled);

View file

@ -8,9 +8,10 @@ import androidx.annotation.StringRes;
@SuppressWarnings("WeakerAccess")
public class TipsModel {
@StringRes
private final int text;
private int text;
@Nullable
private final Intent actionIntent;
private
Intent actionIntent;
TipsModel(@StringRes int text, @Nullable Intent actionIntent) {
this.text = text;

View file

@ -23,11 +23,11 @@ public class TipsViewHolder extends RecyclerView.ViewHolder {
public void bind(TipsModel tip, Consumer<Intent> actionButtonClickedListener) {
binding.tip.setText(tip.getText());
final var intent = tip.getActionIntent();
if (intent != null && intent.hasExtra(INTENT_EXTRA_BUTTON_TEXT)) {
final Intent actionIntent = tip.getActionIntent();
if (actionIntent != null && actionIntent.hasExtra(INTENT_EXTRA_BUTTON_TEXT)) {
binding.actionButton.setVisibility(View.VISIBLE);
binding.actionButton.setText(intent.getIntExtra(INTENT_EXTRA_BUTTON_TEXT, 0));
binding.actionButton.setOnClickListener((v) -> actionButtonClickedListener.accept(intent));
binding.actionButton.setText(actionIntent.getIntExtra(INTENT_EXTRA_BUTTON_TEXT, 0));
binding.actionButton.setOnClickListener((v) -> actionButtonClickedListener.accept(actionIntent));
} else {
binding.actionButton.setVisibility(View.GONE);
}

View file

@ -94,7 +94,7 @@ public class ImportAccountActivity extends AppCompatActivity {
Log.i(TAG, "Added account: " + "name:" + ssoAccount.name + ", " + ssoAccount.url + ", userId" + ssoAccount.userId);
try {
Log.i(TAG, "Loading capabilities for " + ssoAccount.name);
final var capabilities = CapabilitiesClient.getCapabilities(getApplicationContext(), ssoAccount, null, ApiProvider.getInstance());
final Capabilities capabilities = CapabilitiesClient.getCapabilities(getApplicationContext(), ssoAccount, null, ApiProvider.getInstance());
final String displayName = CapabilitiesClient.getDisplayName(getApplicationContext(), ssoAccount, ApiProvider.getInstance());
importAccountViewModel.addAccount(ssoAccount.url, ssoAccount.userId, ssoAccount.name, capabilities, displayName, new IResponseCallback<Account>() {

View file

@ -173,7 +173,7 @@ public class MainActivity extends LockedActivity implements NoteClickListener, A
} else {
executor.submit(() -> {
try {
final var account = mainViewModel.getLocalAccountByAccountName(SingleAccountHelper.getCurrentSingleSignOnAccount(getApplicationContext()).name);
final Account account = mainViewModel.getLocalAccountByAccountName(SingleAccountHelper.getCurrentSingleSignOnAccount(getApplicationContext()).name);
runOnUiThread(() -> mainViewModel.postCurrentAccount(account));
} catch (NextcloudFilesAppAccountNotFoundException e) {
// Verbose log output for https://github.com/stefan-niedermann/nextcloud-notes/issues/1256
@ -181,12 +181,12 @@ public class MainActivity extends LockedActivity implements NoteClickListener, A
.setTitle(NextcloudFilesAppAccountNotFoundException.class.getSimpleName())
.setMessage(R.string.backup)
.setPositiveButton(R.string.simple_backup, (a, b) -> executor.submit(() -> {
final var modifiedNotes = new LinkedList<Note>();
for (final var account : mainViewModel.getAccounts()) {
final List<Note> modifiedNotes = new LinkedList<>();
for (Account account : mainViewModel.getAccounts()) {
modifiedNotes.addAll(mainViewModel.getLocalModifiedNotes(account.getId()));
}
if (modifiedNotes.size() == 1) {
final var note = modifiedNotes.get(0);
final Note note = modifiedNotes.get(0);
ShareUtil.openShareDialog(this, note.getTitle(), note.getContent());
} else {
ShareUtil.openShareDialog(this,
@ -195,12 +195,12 @@ public class MainActivity extends LockedActivity implements NoteClickListener, A
}
}))
.setNegativeButton(R.string.simple_error, (a, b) -> {
final var ssoPreferences = AccountImporter.getSharedPreferences(getApplicationContext());
final var ssoPreferencesString = new StringBuilder()
final SharedPreferences ssoPreferences = AccountImporter.getSharedPreferences(getApplicationContext());
final StringBuilder ssoPreferencesString = new StringBuilder()
.append("Current SSO account: ").append(ssoPreferences.getString("PREF_CURRENT_ACCOUNT_STRING", null)).append("\n")
.append("\n")
.append("SSO SharedPreferences: ").append("\n");
for (final var entry : ssoPreferences.getAll().entrySet()) {
for (Map.Entry<String, ?> entry : ssoPreferences.getAll().entrySet()) {
ssoPreferencesString.append(entry.getKey()).append(": ").append(entry.getValue()).append("\n");
}
ssoPreferencesString.append("\n")
@ -251,7 +251,7 @@ public class MainActivity extends LockedActivity implements NoteClickListener, A
}
fabCreate.setOnClickListener((View view) -> {
final var createIntent = new Intent(getApplicationContext(), EditNoteActivity.class);
final Intent createIntent = new Intent(getApplicationContext(), EditNoteActivity.class);
createIntent.putExtra(EditNoteActivity.PARAM_CATEGORY, selectedCategory);
if (activityBinding.searchView.getQuery().length() > 0) {
createIntent.putExtra(EditNoteActivity.PARAM_CONTENT, activityBinding.searchView.getQuery().toString());
@ -269,8 +269,8 @@ public class MainActivity extends LockedActivity implements NoteClickListener, A
binding.activityNotesListView.emptyContentView.getRoot().setVisibility(notes.size() > 0 ? GONE : VISIBLE);
// Remove deleted notes from the selection
if (tracker.hasSelection()) {
final var deletedNotes = new LinkedList<Long>();
for (final var id : tracker.getSelection()) {
final Collection<Long> deletedNotes = new LinkedList<>();
for (Long id : tracker.getSelection()) {
if (notes
.stream()
.filter(item -> !item.isSection())
@ -279,7 +279,7 @@ public class MainActivity extends LockedActivity implements NoteClickListener, A
deletedNotes.add(id);
}
}
for (final var id : deletedNotes) {
for (Long id : deletedNotes) {
tracker.deselect(id);
}
}
@ -289,13 +289,13 @@ public class MainActivity extends LockedActivity implements NoteClickListener, A
updateSortMethodIcon(methodOfCategory.second);
activityBinding.sortingMethod.setOnClickListener((v) -> {
if (methodOfCategory.first != null) {
var newMethod = methodOfCategory.second;
CategorySortingMethod newMethod = methodOfCategory.second;
if (newMethod == CategorySortingMethod.SORT_LEXICOGRAPHICAL_ASC) {
newMethod = CategorySortingMethod.SORT_MODIFIED_DESC;
} else {
newMethod = CategorySortingMethod.SORT_LEXICOGRAPHICAL_ASC;
}
final var modifyLiveData = mainViewModel.modifyCategoryOrder(methodOfCategory.first, newMethod);
final LiveData<Void> modifyLiveData = mainViewModel.modifyCategoryOrder(methodOfCategory.first, newMethod);
modifyLiveData.observe(this, (next) -> modifyLiveData.removeObservers(this));
}
});
@ -355,7 +355,7 @@ public class MainActivity extends LockedActivity implements NoteClickListener, A
@Override
protected void onResume() {
final var accountLiveData = mainViewModel.getCurrentAccount();
final LiveData<Account> accountLiveData = mainViewModel.getCurrentAccount();
accountLiveData.observe(this, (currentAccount) -> {
accountLiveData.removeObservers(this);
try {
@ -423,8 +423,8 @@ public class MainActivity extends LockedActivity implements NoteClickListener, A
listView.setAdapter(adapter);
listView.setItemAnimator(null);
if (gridView) {
final int spanCount = getResources().getInteger(R.integer.grid_view_span_count);
final var gridLayoutManager = new StaggeredGridLayoutManager(spanCount, StaggeredGridLayoutManager.VERTICAL);
int spanCount = getResources().getInteger(R.integer.grid_view_span_count);
StaggeredGridLayoutManager gridLayoutManager = new StaggeredGridLayoutManager(spanCount, StaggeredGridLayoutManager.VERTICAL);
listView.setLayoutManager(gridLayoutManager);
listView.addItemDecoration(new GridItemDecoration(adapter, spanCount,
getResources().getDimensionPixelSize(R.dimen.spacer_3x),
@ -434,7 +434,7 @@ public class MainActivity extends LockedActivity implements NoteClickListener, A
getResources().getDimensionPixelSize(R.dimen.spacer_activity_sides) + getResources().getDimensionPixelSize(R.dimen.spacer_1x)
));
} else {
final var layoutManager = new LinearLayoutManager(this);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
listView.setLayoutManager(layoutManager);
listView.addItemDecoration(new SectionItemDecoration(adapter,
getResources().getDimensionPixelSize(R.dimen.spacer_activity_sides) + getResources().getDimensionPixelSize(R.dimen.spacer_1x) + getResources().getDimensionPixelSize(R.dimen.spacer_3x) + getResources().getDimensionPixelSize(R.dimen.spacer_2x),
@ -456,10 +456,10 @@ public class MainActivity extends LockedActivity implements NoteClickListener, A
swipeRefreshLayout.setOnRefreshListener(() -> {
CustomAppGlideModule.clearCache(this);
final var syncLiveData = mainViewModel.getCurrentAccount();
final LiveData<Account> syncLiveData = mainViewModel.getCurrentAccount();
final Observer<Account> syncObserver = currentAccount -> {
syncLiveData.removeObservers(this);
mainViewModel.synchronizeCapabilitiesAndNotes(currentAccount, new IResponseCallback<>() {
mainViewModel.synchronizeCapabilitiesAndNotes(currentAccount, new IResponseCallback<Void>() {
@Override
public void onSuccess(Void v) {
Log.d(TAG, "Successfully synchronized capabilities and notes for " + currentAccount.getAccountName());
@ -558,7 +558,7 @@ public class MainActivity extends LockedActivity implements NoteClickListener, A
@Override
public void onIconClick(NavigationItem item) {
final var expandedCategoryLiveData = mainViewModel.getExpandedCategory();
final LiveData<String> expandedCategoryLiveData = mainViewModel.getExpandedCategory();
expandedCategoryLiveData.observe(MainActivity.this, expandedCategory -> {
if (item.icon == NavigationAdapter.ICON_MULTIPLE && !item.label.equals(expandedCategory)) {
mainViewModel.postExpandedCategory(item.label);
@ -671,14 +671,14 @@ public class MainActivity extends LockedActivity implements NoteClickListener, A
Log.i(TAG, "Added account: " + "name:" + ssoAccount.name + ", " + ssoAccount.url + ", userId" + ssoAccount.userId);
try {
Log.i(TAG, "Refreshing capabilities for " + ssoAccount.name);
final var capabilities = CapabilitiesClient.getCapabilities(getApplicationContext(), ssoAccount, null, ApiProvider.getInstance());
final Capabilities capabilities = CapabilitiesClient.getCapabilities(getApplicationContext(), ssoAccount, null, ApiProvider.getInstance());
final String displayName = CapabilitiesClient.getDisplayName(getApplicationContext(), ssoAccount, ApiProvider.getInstance());
mainViewModel.addAccount(ssoAccount.url, ssoAccount.userId, ssoAccount.name, capabilities, displayName, new IResponseCallback<Account>() {
@Override
public void onSuccess(Account result) {
executor.submit(() -> {
Log.i(TAG, capabilities.toString());
final var a = mainViewModel.getLocalAccountByAccountName(ssoAccount.name);
final Account a = mainViewModel.getLocalAccountByAccountName(ssoAccount.name);
runOnUiThread(() -> mainViewModel.postCurrentAccount(a));
});
}
@ -720,9 +720,9 @@ public class MainActivity extends LockedActivity implements NoteClickListener, A
@Override
public void onNoteClick(int position, View v) {
final boolean hasCheckedItems = tracker.getSelection().size() > 0;
boolean hasCheckedItems = tracker.getSelection().size() > 0;
if (!hasCheckedItems) {
final var note = (Note) adapter.getItem(position);
final Note note = (Note) adapter.getItem(position);
startActivity(new Intent(getApplicationContext(), EditNoteActivity.class)
.putExtra(EditNoteActivity.PARAM_NOTE_ID, note.getId()));
}
@ -730,7 +730,7 @@ public class MainActivity extends LockedActivity implements NoteClickListener, A
@Override
public void onNoteFavoriteClick(int position, View view) {
final var toggleLiveData = mainViewModel.toggleFavoriteAndSync(((Note) adapter.getItem(position)).getId());
LiveData<Void> toggleLiveData = mainViewModel.toggleFavoriteAndSync(((Note) adapter.getItem(position)).getId());
toggleLiveData.observe(this, (next) -> toggleLiveData.removeObservers(this));
}
@ -772,8 +772,8 @@ public class MainActivity extends LockedActivity implements NoteClickListener, A
@Override
public void onAccountPicked(@NonNull Account account) {
for (final var noteId : tracker.getSelection()) {
final var moveLiveData = mainViewModel.moveNoteToAnotherAccount(account, noteId);
for (Long noteId : tracker.getSelection()) {
final LiveData<Note> moveLiveData = mainViewModel.moveNoteToAnotherAccount(account, noteId);
moveLiveData.observe(this, (v) -> {
tracker.deselect(noteId);
moveLiveData.removeObservers(this);
@ -783,7 +783,7 @@ public class MainActivity extends LockedActivity implements NoteClickListener, A
@Override
public void onCategoryChosen(String category) {
final var categoryLiveData = mainViewModel.setCategory(tracker.getSelection(), category);
final LiveData<Void> categoryLiveData = mainViewModel.setCategory(tracker.getSelection(), category);
categoryLiveData.observe(this, (next) -> categoryLiveData.removeObservers(this));
tracker.clearSelection();
}

View file

@ -121,7 +121,7 @@ public class MainViewModel extends AndroidViewModel {
BrandingUtil.saveBrandColors(getApplication(), account.getColor(), account.getTextColor());
SingleAccountHelper.setCurrentAccount(getApplication(), account.getAccountName());
final var currentAccount = this.currentAccount.getValue();
final Account currentAccount = this.currentAccount.getValue();
// If only ETag or colors change, we must not reset the navigation
// TODO in the long term we should store the last NavigationCategory for each Account
if (currentAccount == null || currentAccount.getId() != account.getId()) {
@ -161,14 +161,14 @@ public class MainViewModel extends AndroidViewModel {
}
case DEFAULT_CATEGORY:
default: {
final String category = selectedCategory.getCategory();
String category = selectedCategory.getCategory();
if (category == null) {
postExpandedCategory(null);
Log.e(TAG, "navigation selection is a " + DEFAULT_CATEGORY + ", but the contained category is null.");
} else {
int slashIndex = category.indexOf('/');
final String rootCategory = slashIndex < 0 ? category : category.substring(0, slashIndex);
final String expandedCategory = getExpandedCategory().getValue();
String rootCategory = slashIndex < 0 ? category : category.substring(0, slashIndex);
String expandedCategory = getExpandedCategory().getValue();
if (expandedCategory != null && !expandedCategory.equals(rootCategory)) {
postExpandedCategory(null);
}
@ -209,7 +209,7 @@ public class MainViewModel extends AndroidViewModel {
@NonNull
@MainThread
public LiveData<List<Item>> getNotesListLiveData() {
final var insufficientInformation = new MutableLiveData<List<Item>>();
final MutableLiveData<List<Item>> insufficientInformation = new MutableLiveData<>();
return distinctUntilChanged(switchMap(getCurrentAccount(), currentAccount -> {
Log.v(TAG, "[getNotesListLiveData] - currentAccount: " + currentAccount);
if (currentAccount == null) {
@ -292,7 +292,7 @@ public class MainViewModel extends AndroidViewModel {
@NonNull
@MainThread
public LiveData<List<NavigationItem>> getNavigationCategories() {
final var insufficientInformation = new MutableLiveData<List<NavigationItem>>();
final MutableLiveData<List<NavigationItem>> insufficientInformation = new MutableLiveData<>();
return switchMap(getCurrentAccount(), currentAccount -> {
if (currentAccount == null) {
return insufficientInformation;
@ -315,29 +315,29 @@ public class MainViewModel extends AndroidViewModel {
}
private static List<NavigationItem> fromCategoriesWithNotesCount(@NonNull Context context, @Nullable String expandedCategory, @NonNull List<CategoryWithNotesCount> fromDatabase, int count, int favoritesCount) {
final var categories = convertToCategoryNavigationItem(context, fromDatabase);
final var itemRecent = new NavigationItem(ADAPTER_KEY_RECENT, context.getString(R.string.label_all_notes), count, R.drawable.ic_access_time_grey600_24dp, RECENT);
final var itemFavorites = new NavigationItem(ADAPTER_KEY_STARRED, context.getString(R.string.label_favorites), favoritesCount, R.drawable.ic_star_yellow_24dp, FAVORITES);
final List<NavigationItem.CategoryNavigationItem> categories = convertToCategoryNavigationItem(context, fromDatabase);
final NavigationItem itemRecent = new NavigationItem(ADAPTER_KEY_RECENT, context.getString(R.string.label_all_notes), count, R.drawable.ic_access_time_grey600_24dp, RECENT);
final NavigationItem itemFavorites = new NavigationItem(ADAPTER_KEY_STARRED, context.getString(R.string.label_favorites), favoritesCount, R.drawable.ic_star_yellow_24dp, FAVORITES);
final var items = new ArrayList<NavigationItem>(fromDatabase.size() + 3);
final ArrayList<NavigationItem> items = new ArrayList<>(fromDatabase.size() + 3);
items.add(itemRecent);
items.add(itemFavorites);
NavigationItem lastPrimaryCategory = null;
NavigationItem lastSecondaryCategory = null;
for (final var item : categories) {
final int slashIndex = item.label.indexOf('/');
final String currentPrimaryCategory = slashIndex < 0 ? item.label : item.label.substring(0, slashIndex);
final boolean isCategoryOpen = currentPrimaryCategory.equals(expandedCategory);
for (NavigationItem item : categories) {
int slashIndex = item.label.indexOf('/');
String currentPrimaryCategory = slashIndex < 0 ? item.label : item.label.substring(0, slashIndex);
String currentSecondaryCategory = null;
boolean isCategoryOpen = currentPrimaryCategory.equals(expandedCategory);
if (isCategoryOpen && !currentPrimaryCategory.equals(item.label)) {
final String currentCategorySuffix = item.label.substring(expandedCategory.length() + 1);
final int subSlashIndex = currentCategorySuffix.indexOf('/');
String currentCategorySuffix = item.label.substring(expandedCategory.length() + 1);
int subSlashIndex = currentCategorySuffix.indexOf('/');
currentSecondaryCategory = subSlashIndex < 0 ? currentCategorySuffix : currentCategorySuffix.substring(0, subSlashIndex);
}
boolean belongsToLastPrimaryCategory = lastPrimaryCategory != null && currentPrimaryCategory.equals(lastPrimaryCategory.label);
final boolean belongsToLastSecondaryCategory = belongsToLastPrimaryCategory && lastSecondaryCategory != null && lastSecondaryCategory.label.equals(currentPrimaryCategory + "/" + currentSecondaryCategory);
boolean belongsToLastSecondaryCategory = belongsToLastPrimaryCategory && lastSecondaryCategory != null && lastSecondaryCategory.label.equals(currentPrimaryCategory + "/" + currentSecondaryCategory);
if (isCategoryOpen && !belongsToLastPrimaryCategory && currentSecondaryCategory != null) {
lastPrimaryCategory = new NavigationItem("category:" + currentPrimaryCategory, currentPrimaryCategory, 0, NavigationAdapter.ICON_MULTIPLE_OPEN);
@ -401,9 +401,9 @@ public class MainViewModel extends AndroidViewModel {
}
if (repo.isSyncPossible()) {
try {
final var ssoAccount = AccountImporter.getSingleSignOnAccount(getApplication(), localAccount.getAccountName());
final SingleSignOnAccount ssoAccount = AccountImporter.getSingleSignOnAccount(getApplication(), localAccount.getAccountName());
try {
final var capabilities = CapabilitiesClient.getCapabilities(getApplication(), ssoAccount, localAccount.getCapabilitiesETag(), ApiProvider.getInstance());
final Capabilities capabilities = CapabilitiesClient.getCapabilities(getApplication(), ssoAccount, localAccount.getCapabilitiesETag(), ApiProvider.getInstance());
repo.updateCapabilitiesETag(localAccount.getId(), capabilities.getETag());
repo.updateBrand(localAccount.getId(), capabilities.getColor(), capabilities.getTextColor());
localAccount.setColor(capabilities.getColor());
@ -530,7 +530,7 @@ public class MainViewModel extends AndroidViewModel {
return new MutableLiveData<>(null);
} else {
Log.v(TAG, "[deleteNotesAndSync] - currentAccount: " + currentAccount.getAccountName());
for (final var id : ids) {
for (Long id : ids) {
repo.deleteNoteAndSync(currentAccount, id);
}
return new MutableLiveData<>(null);
@ -557,7 +557,7 @@ public class MainViewModel extends AndroidViewModel {
return new MutableLiveData<>();
} else {
Log.v(TAG, "[getNote] - currentAccount: " + currentAccount.getAccountName());
final var notes = new MutableLiveData<List<Note>>();
final MutableLiveData<List<Note>> notes = new MutableLiveData<>();
executor.submit(() -> notes.postValue(
ids
.stream()
@ -604,9 +604,9 @@ public class MainViewModel extends AndroidViewModel {
@WorkerThread
public String collectNoteContents(@NonNull List<Long> noteIds) {
final var noteContents = new StringBuilder();
for (final var noteId : noteIds) {
final var fullNote = repo.getNoteById(noteId);
final StringBuilder noteContents = new StringBuilder();
for (Long noteId : noteIds) {
final Note fullNote = repo.getNoteById(noteId);
final String tempFullNote = fullNote.getContent();
if (!TextUtils.isEmpty(tempFullNote)) {
if (noteContents.length() > 0) {

View file

@ -72,7 +72,7 @@ public class MultiSelectedActionModeCallback implements Callback {
mode.getMenuInflater().inflate(R.menu.menu_list_context_multiple, menu);
menu.findItem(R.id.menu_move).setVisible(canMoveNoteToAnotherAccounts);
for (int i = 0; i < menu.size(); i++) {
var drawable = menu.getItem(i).getIcon();
Drawable drawable = menu.getItem(i).getIcon();
if (drawable != null) {
drawable = DrawableCompat.wrap(drawable);
DrawableCompat.setTint(drawable, colorAccent);
@ -96,23 +96,23 @@ public class MultiSelectedActionModeCallback implements Callback {
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
int itemId = item.getItemId();
if (itemId == R.id.menu_delete) {
final var selection = new ArrayList<Long>(tracker.getSelection().size());
for (final var sel : tracker.getSelection()) {
final List<Long> selection = new ArrayList<>(tracker.getSelection().size());
for (Long sel : tracker.getSelection()) {
selection.add(sel);
}
final var fullNotes$ = mainViewModel.getFullNotesWithCategory(selection);
final LiveData<List<Note>> fullNotes$ = mainViewModel.getFullNotesWithCategory(selection);
fullNotes$.observe(lifecycleOwner, (fullNotes) -> {
fullNotes$.removeObservers(lifecycleOwner);
tracker.clearSelection();
final var deleteLiveData = mainViewModel.deleteNotesAndSync(selection);
final LiveData<Void> deleteLiveData = mainViewModel.deleteNotesAndSync(selection);
deleteLiveData.observe(lifecycleOwner, (next) -> deleteLiveData.removeObservers(lifecycleOwner));
final String deletedSnackbarTitle = fullNotes.size() == 1
String deletedSnackbarTitle = fullNotes.size() == 1
? context.getString(R.string.action_note_deleted, fullNotes.get(0).getTitle())
: context.getResources().getQuantityString(R.plurals.bulk_notes_deleted, fullNotes.size(), fullNotes.size());
BrandedSnackbar.make(view, deletedSnackbarTitle, Snackbar.LENGTH_LONG)
.setAction(R.string.action_undo, (View v) -> {
for (final var deletedNote : fullNotes) {
final var undoLiveData = mainViewModel.addNoteAndSync(deletedNote);
for (Note deletedNote : fullNotes) {
final LiveData<Note> undoLiveData = mainViewModel.addNoteAndSync(deletedNote);
undoLiveData.observe(lifecycleOwner, (o) -> undoLiveData.removeObservers(lifecycleOwner));
}
String restoreSnackbarTitle = fullNotes.size() == 1
@ -125,7 +125,7 @@ public class MultiSelectedActionModeCallback implements Callback {
});
return true;
} else if (itemId == R.id.menu_move) {
final var currentAccount$ = mainViewModel.getCurrentAccount();
final LiveData<Account> currentAccount$ = mainViewModel.getCurrentAccount();
currentAccount$.observe(lifecycleOwner, account -> {
currentAccount$.removeObservers(lifecycleOwner);
executor.submit(() -> AccountPickerDialogFragment
@ -134,15 +134,15 @@ public class MultiSelectedActionModeCallback implements Callback {
});
return true;
} else if (itemId == R.id.menu_share) {
final var selection = new ArrayList<Long>(tracker.getSelection().size());
for (final var sel : tracker.getSelection()) {
final List<Long> selection = new ArrayList<>(tracker.getSelection().size());
for (Long sel : tracker.getSelection()) {
selection.add(sel);
}
tracker.clearSelection();
executor.submit(() -> {
if (selection.size() == 1) {
final var note = mainViewModel.getFullNote(selection.get(0));
final Note note = mainViewModel.getFullNote(selection.get(0));
ShareUtil.openShareDialog(context, note.getTitle(), note.getContent());
} else {
ShareUtil.openShareDialog(context,
@ -152,7 +152,7 @@ public class MultiSelectedActionModeCallback implements Callback {
});
return true;
} else if (itemId == R.id.menu_category) {// TODO detect whether all selected notes do have the same category - in this case preselect it
final var accountLiveData = mainViewModel.getCurrentAccount();
final LiveData<Account> accountLiveData = mainViewModel.getCurrentAccount();
accountLiveData.observe(lifecycleOwner, account -> {
accountLiveData.removeObservers(lifecycleOwner);
CategoryDialogFragment

View file

@ -70,7 +70,7 @@ public class ItemAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> i
this.gridView = gridView;
this.mainColor = ContextCompat.getColor(context, R.color.defaultBrand);
this.textColor = Color.WHITE;
final var sp = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
this.fontSize = getFontSizeFromPreferences(context, sp);
this.monospace = sp.getBoolean(context.getString(R.string.pref_key_font), false);
setHasStableIds(true);
@ -140,7 +140,7 @@ public class ItemAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> i
public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder holder, int position) {
boolean isSelected = false;
if (tracker != null) {
final Long itemId = getItemId(position);
Long itemId = getItemId(position);
if (tracker.isSelected(itemId)) {
tracker.select(itemId);
isSelected = true;
@ -187,12 +187,12 @@ public class ItemAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> i
@IntRange(from = 0, to = 3)
@Override
public int getItemViewType(int position) {
final var item = getItem(position);
Item item = getItem(position);
if (item == null) {
throw new IllegalArgumentException("Item at position " + position + " must not be null");
}
if (getItem(position).isSection()) return TYPE_SECTION;
final var note = (Note) getItem(position);
Note note = (Note) getItem(position);
if (TextUtils.isEmpty(note.getExcerpt())) {
if (TextUtils.isEmpty(note.getCategory())) {
return TYPE_NOTE_ONLY_TITLE;

View file

@ -117,7 +117,6 @@ public abstract class NoteViewHolder extends RecyclerView.ViewHolder {
// The Pattern.quote method will add \Q to the very beginning of the string and \E to the end of the string
// It implies that the string between \Q and \E is a literal string and thus the reserved keyword in such string will be ignored.
// See https://stackoverflow.com/questions/15409296/what-is-the-use-of-pattern-quote-method
//noinspection ConstantConditions
final Pattern pattern = Pattern.compile("(" + Pattern.quote(searchQuery.toString()) + ")", Pattern.CASE_INSENSITIVE);
SpannableString spannableString = new SpannableString(content);
Matcher matcher = pattern.matcher(spannableString);

View file

@ -33,7 +33,7 @@ public class GridItemDecoration extends SectionItemDecoration {
super.getItemOffsets(outRect, view, parent, state);
final int position = parent.getChildAdapterPosition(view);
if (position >= 0) {
final var lp = (StaggeredGridLayoutManager.LayoutParams) view.getLayoutParams();
final StaggeredGridLayoutManager.LayoutParams lp = (StaggeredGridLayoutManager.LayoutParams) view.getLayoutParams();
if (adapter.getItemViewType(position) == ItemAdapter.TYPE_SECTION) {
lp.setFullSpan(true);

View file

@ -30,7 +30,7 @@ public class NoteViewHolderWithExcerpt extends NoteViewHolder {
public void bind(boolean isSelected, @NonNull Note note, boolean showCategory, int mainColor, int textColor, @Nullable CharSequence searchQuery) {
super.bind(isSelected, note, showCategory, mainColor, textColor, searchQuery);
@NonNull final var context = itemView.getContext();
@NonNull final Context context = itemView.getContext();
binding.noteSwipeable.setAlpha(DBStatus.LOCAL_DELETED.equals(note.getStatus()) ? 0.5f : 1.0f);
bindCategory(context, binding.noteCategory, showCategory, note.getCategory(), mainColor);
bindStatus(binding.noteStatus, note.getStatus(), mainColor);

View file

@ -72,17 +72,17 @@ public class NotesListViewItemTouchHelper extends ItemTouchHelper {
switch (direction) {
case ItemTouchHelper.LEFT:
viewHolder.setIsRecyclable(false);
final var dbNoteWithoutContent = (Note) adapter.getItem(viewHolder.getLayoutPosition());
final var dbNoteLiveData = mainViewModel.getFullNote$(dbNoteWithoutContent.getId());
final Note dbNoteWithoutContent = (Note) adapter.getItem(viewHolder.getLayoutPosition());
final LiveData<Note> dbNoteLiveData = mainViewModel.getFullNote$(dbNoteWithoutContent.getId());
dbNoteLiveData.observe(lifecycleOwner, (dbNote) -> {
dbNoteLiveData.removeObservers(lifecycleOwner);
tracker.deselect(dbNote.getId());
final var deleteLiveData = mainViewModel.deleteNoteAndSync(dbNote.getId());
final LiveData<Void> deleteLiveData = mainViewModel.deleteNoteAndSync(dbNote.getId());
deleteLiveData.observe(lifecycleOwner, (next) -> deleteLiveData.removeObservers(lifecycleOwner));
Log.v(TAG, "Item deleted through swipe ----------------------------------------------");
BrandedSnackbar.make(view, context.getString(R.string.action_note_deleted, dbNote.getTitle()), UNDO_DURATION)
.setAction(R.string.action_undo, (View v) -> {
final var undoLiveData = mainViewModel.addNoteAndSync(dbNote);
final LiveData<Note> undoLiveData = mainViewModel.addNoteAndSync(dbNote);
undoLiveData.observe(lifecycleOwner, (o) -> undoLiveData.removeObservers(lifecycleOwner));
BrandedSnackbar.make(view, context.getString(R.string.action_note_restored, dbNote.getTitle()), Snackbar.LENGTH_SHORT)
.show();
@ -92,8 +92,8 @@ public class NotesListViewItemTouchHelper extends ItemTouchHelper {
break;
case ItemTouchHelper.RIGHT:
viewHolder.setIsRecyclable(false);
final var adapterNote = (Note) adapter.getItem(viewHolder.getLayoutPosition());
final var toggleLiveData = mainViewModel.toggleFavoriteAndSync(adapterNote.getId());
final Note adapterNote = (Note) adapter.getItem(viewHolder.getLayoutPosition());
final LiveData<Void> toggleLiveData = mainViewModel.toggleFavoriteAndSync(adapterNote.getId());
toggleLiveData.observe(lifecycleOwner, (next) -> toggleLiveData.removeObservers(lifecycleOwner));
break;
default:
@ -103,7 +103,7 @@ public class NotesListViewItemTouchHelper extends ItemTouchHelper {
@Override
public void onChildDraw(@NonNull Canvas c, @NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
final var noteViewHolder = (NoteViewHolder) viewHolder;
final NoteViewHolder noteViewHolder = (NoteViewHolder) viewHolder;
// show swipe icon on the side
noteViewHolder.showSwipe(dX > 0);
// move only swipeable part of item (not leave-behind)

View file

@ -18,7 +18,7 @@ public class ItemIdKeyProvider extends ItemKeyProvider<Long> {
@Nullable
@Override
public Long getKey(int position) {
final var adapter = recyclerView.getAdapter();
final RecyclerView.Adapter<?> adapter = recyclerView.getAdapter();
if (adapter == null) {
throw new IllegalStateException("RecyclerView adapter is not set!");
}
@ -27,7 +27,7 @@ public class ItemIdKeyProvider extends ItemKeyProvider<Long> {
@Override
public int getPosition(@NonNull Long key) {
final var viewHolder = recyclerView.findViewHolderForItemId(key);
final RecyclerView.ViewHolder viewHolder = recyclerView.findViewHolderForItemId(key);
return viewHolder == null ? NO_POSITION : viewHolder.getLayoutPosition();
}
}

View file

@ -22,7 +22,7 @@ public class ItemLookup extends ItemDetailsLookup<Long> {
@Nullable
@Override
public ItemDetails<Long> getItemDetails(@NonNull MotionEvent e) {
final var view = recyclerView.findChildViewUnder(e.getX(), e.getY());
final View view = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (view != null) {
final RecyclerView.ViewHolder viewHolder = recyclerView.getChildViewHolder(view);
if (viewHolder instanceof NoteViewHolder) {

View file

@ -22,7 +22,7 @@ public class ItemSelectionTracker {
new ItemLookup(recyclerView),
StorageStrategy.createLongStorage()
).withSelectionPredicate(
new SelectionTracker.SelectionPredicate<>() {
new SelectionTracker.SelectionPredicate<Long>() {
@Override
public boolean canSetStateForKey(@NonNull Long key, boolean nextState) {
return true;

View file

@ -84,9 +84,9 @@ public class MenuAdapter extends RecyclerView.Adapter<MenuViewHolder> {
}
private static Intent generateTrashbinAppIntent(@NonNull Context context, @NonNull Account account, boolean prod) throws PackageManager.NameNotFoundException {
final var packageManager = context.getPackageManager();
final PackageManager packageManager = context.getPackageManager();
final String packageName = prod ? Constants.PACKAGE_NAME_PROD : Constants.PACKAGE_NAME_DEV;
final var intent = new Intent();
final Intent intent = new Intent();
intent.setClassName(packageName, "com.owncloud.android.ui.trashbin.TrashbinActivity");
if (packageManager.resolveActivity(intent, 0) != null) {
return intent

View file

@ -74,7 +74,7 @@ public class NavigationAdapter extends RecyclerView.Adapter<NavigationViewHolder
}
public void setItems(@NonNull List<NavigationItem> items) {
for (final var item : items) {
for (NavigationItem item : items) {
if (TextUtils.isEmpty(item.label)) {
item.id = MainActivity.ADAPTER_KEY_UNCATEGORIZED;
item.label = context.getString(R.string.action_uncategorized);

View file

@ -75,7 +75,7 @@ public class NavigationItem {
if (this == o) return true;
if (!(o instanceof NavigationItem)) return false;
final var that = (NavigationItem) o;
NavigationItem that = (NavigationItem) o;
if (icon != that.icon) return false;
if (!id.equals(that.id)) return false;

View file

@ -32,7 +32,7 @@ class NavigationViewHolder extends RecyclerView.ViewHolder {
NavigationViewHolder(@NonNull View itemView, @NonNull final NavigationClickListener navigationClickListener) {
super(itemView);
view = itemView;
final var binding = ItemNavigationBinding.bind(view);
ItemNavigationBinding binding = ItemNavigationBinding.bind(view);
this.name = binding.navigationItemLabel;
this.count = binding.navigationItemCount;
this.icon = binding.navigationItemIcon;
@ -42,7 +42,7 @@ class NavigationViewHolder extends RecyclerView.ViewHolder {
public void bind(@NonNull NavigationItem item, @ColorInt int mainColor, String selectedItem) {
currentItem = item;
final boolean isSelected = item.id.equals(selectedItem);
boolean isSelected = item.id.equals(selectedItem);
name.setText(NoteUtil.extendCategory(item.label));
count.setVisibility(item.count == null ? View.GONE : View.VISIBLE);
count.setText(String.valueOf(item.count));
@ -52,7 +52,7 @@ class NavigationViewHolder extends RecyclerView.ViewHolder {
} else {
icon.setVisibility(View.GONE);
}
final int textColor = isSelected ? mainColor : view.getResources().getColor(R.color.fg_default);
int textColor = isSelected ? mainColor : view.getResources().getColor(R.color.fg_default);
name.setTextColor(textColor);
count.setTextColor(textColor);

View file

@ -22,8 +22,8 @@ public class SlotterUtil {
@NonNull
public static List<Item> fillListByCategory(@NonNull List<Note> noteList, @Nullable String currentCategory) {
final var itemList = new ArrayList<Item>();
for (final var note : noteList) {
List<Item> itemList = new ArrayList<>();
for (Note note : noteList) {
if (currentCategory != null && !currentCategory.equals(note.getCategory())) {
itemList.add(new SectionItem(NoteUtil.extendCategory(note.getCategory())));
}
@ -36,11 +36,11 @@ public class SlotterUtil {
@NonNull
public static List<Item> fillListByTime(@NonNull Context context, @NonNull List<Note> noteList) {
final var itemList = new ArrayList<Item>();
final var timeslotter = new Timeslotter(context);
List<Item> itemList = new ArrayList<>();
Timeslotter timeslotter = new Timeslotter(context);
String lastTimeslot = null;
for (int i = 0; i < noteList.size(); i++) {
final var currentNote = noteList.get(i);
Note currentNote = noteList.get(i);
String timeslot = timeslotter.getTimeslot(currentNote);
if (i > 0 && !timeslot.equals(lastTimeslot)) {
itemList.add(new SectionItem(timeslot));
@ -54,10 +54,10 @@ public class SlotterUtil {
@NonNull
public static List<Item> fillListByInitials(@NonNull Context context, @NonNull List<Note> noteList) {
final var itemList = new ArrayList<Item>();
List<Item> itemList = new ArrayList<>();
String lastInitials = null;
for (int i = 0; i < noteList.size(); i++) {
final var currentNote = noteList.get(i);
Note currentNote = noteList.get(i);
String initials = currentNote.getTitle().substring(0, 1).toUpperCase();
if (!initials.matches("[A-Z\\u00C0-\\u00DF]")) {
initials = initials.matches("[\\u0250-\\uFFFF]") ? context.getString(R.string.simple_other) : "#";

View file

@ -37,8 +37,8 @@ public class Timeslotter {
if (note.getFavorite()) {
return "";
}
final var modified = note.getModified();
for (final var timeslot : timeslots) {
Calendar modified = note.getModified();
for (Timeslot timeslot : timeslots) {
if (!modified.before(timeslot.getTime())) {
return timeslot.getLabel();
}

View file

@ -53,7 +53,7 @@ public class ManageAccountAdapter extends RecyclerView.Adapter<ManageAccountView
@Override
public void onBindViewHolder(@NonNull ManageAccountViewHolder holder, int position) {
final var localAccount = localAccounts.get(position);
final Account localAccount = localAccounts.get(position);
holder.bind(localAccount, (localAccountClicked) -> {
setCurrentLocalAccount(localAccountClicked);
onAccountClick.accept(localAccountClicked);

View file

@ -53,11 +53,11 @@ public class ManageAccountViewHolder extends RecyclerView.ViewHolder {
itemView.setOnClickListener((v) -> onAccountClick.accept(localAccount));
binding.accountContextMenu.setVisibility(VISIBLE);
binding.accountContextMenu.setOnClickListener((v) -> {
final var popup = new PopupMenu(itemView.getContext(), v);
final PopupMenu popup = new PopupMenu(itemView.getContext(), v);
popup.inflate(R.menu.menu_account);
final var preferredApiVersion = getPreferredApiVersion(localAccount.getApiVersion());
final ApiVersion preferredApiVersion = getPreferredApiVersion(localAccount.getApiVersion());
if (preferredApiVersion != null && !preferredApiVersion.supportsSettings()) {
final var menu = popup.getMenu();
final Menu menu = popup.getMenu();
Stream.of(
R.id.notes_path,
R.id.file_suffix

View file

@ -114,21 +114,21 @@ public class ManageAccountsActivity extends LockedActivity {
}
private void onChangeNotesPath(@NonNull Account localAccount) {
final var repository = NotesRepository.getInstance(getApplicationContext());
final var editText = new EditText(this);
final var wrapper = createDialogViewWrapper();
final var dialog = new BrandedAlertDialogBuilder(this)
final NotesRepository repository = NotesRepository.getInstance(getApplicationContext());
final EditText editText = new EditText(this);
final ViewGroup wrapper = createDialogViewWrapper();
final AlertDialog dialog = new BrandedAlertDialogBuilder(this)
.setTitle(R.string.settings_notes_path)
.setMessage(R.string.settings_notes_path_description)
.setView(wrapper)
.setNeutralButton(android.R.string.cancel, null)
.setPositiveButton(R.string.action_edit_save, (v, d) -> new Thread(() -> {
try {
final var putSettingsCall = repository.putServerSettings(AccountImporter.getSingleSignOnAccount(this, localAccount.getAccountName()), new NotesSettings(editText.getText().toString(), null), getPreferredApiVersion(localAccount.getApiVersion()));
putSettingsCall.enqueue(new Callback<>() {
final Call<NotesSettings> putSettingsCall = repository.putServerSettings(AccountImporter.getSingleSignOnAccount(this, localAccount.getAccountName()), new NotesSettings(editText.getText().toString(), null), getPreferredApiVersion(localAccount.getApiVersion()));
putSettingsCall.enqueue(new Callback<NotesSettings>() {
@Override
public void onResponse(@NonNull Call<NotesSettings> call, @NonNull Response<NotesSettings> response) {
final var body = response.body();
final NotesSettings body = response.body();
if (response.isSuccessful() && body != null) {
runOnUiThread(() -> Toast.makeText(ManageAccountsActivity.this, getString(R.string.settings_notes_path_success, body.getNotesPath()), Toast.LENGTH_LONG).show());
} else {
@ -148,14 +148,14 @@ public class ManageAccountsActivity extends LockedActivity {
.show();
try {
repository.getServerSettings(AccountImporter.getSingleSignOnAccount(this, localAccount.getAccountName()), getPreferredApiVersion(localAccount.getApiVersion()))
.enqueue(new Callback<>() {
.enqueue(new Callback<NotesSettings>() {
@Override
public void onResponse(@NonNull Call<NotesSettings> call, @NonNull Response<NotesSettings> response) {
runOnUiThread(() -> {
final var body = response.body();
final NotesSettings body = response.body();
if (response.isSuccessful() && body != null) {
wrapper.removeAllViews();
final var editText = new EditText(ManageAccountsActivity.this);
final EditText editText = new EditText(ManageAccountsActivity.this);
editText.setText(body.getNotesPath());
wrapper.addView(editText);
} else {
@ -180,13 +180,13 @@ public class ManageAccountsActivity extends LockedActivity {
}
private void onChangeFileSuffix(@NonNull Account localAccount) {
final var repository = NotesRepository.getInstance(getApplicationContext());
final var spinner = new Spinner(this);
final var wrapper = createDialogViewWrapper();
final var adapter = ArrayAdapter.createFromResource(this, R.array.settings_file_suffixes, android.R.layout.simple_spinner_item);
final NotesRepository repository = NotesRepository.getInstance(getApplicationContext());
final Spinner spinner = new Spinner(this);
final ViewGroup wrapper = createDialogViewWrapper();
final ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.settings_file_suffixes, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
final var dialog = new BrandedAlertDialogBuilder(this)
final AlertDialog dialog = new BrandedAlertDialogBuilder(this)
.setTitle(R.string.settings_file_suffix)
.setMessage(R.string.settings_file_suffix_description)
.setView(wrapper)
@ -194,10 +194,10 @@ public class ManageAccountsActivity extends LockedActivity {
.setPositiveButton(R.string.action_edit_save, (v, d) -> new Thread(() -> {
try {
final Call<NotesSettings> putSettingsCall = repository.putServerSettings(AccountImporter.getSingleSignOnAccount(this, localAccount.getAccountName()), new NotesSettings(null, spinner.getSelectedItem().toString()), getPreferredApiVersion(localAccount.getApiVersion()));
putSettingsCall.enqueue(new Callback<>() {
putSettingsCall.enqueue(new Callback<NotesSettings>() {
@Override
public void onResponse(@NonNull Call<NotesSettings> call, @NonNull Response<NotesSettings> response) {
final var body = response.body();
final NotesSettings body = response.body();
if (response.isSuccessful() && body != null) {
runOnUiThread(() -> Toast.makeText(ManageAccountsActivity.this, getString(R.string.settings_file_suffix_success, body.getNotesPath()), Toast.LENGTH_LONG).show());
} else {
@ -217,7 +217,7 @@ public class ManageAccountsActivity extends LockedActivity {
.show();
try {
repository.getServerSettings(AccountImporter.getSingleSignOnAccount(this, localAccount.getAccountName()), getPreferredApiVersion(localAccount.getApiVersion()))
.enqueue(new Callback<>() {
.enqueue(new Callback<NotesSettings>() {
@Override
public void onResponse(@NonNull Call<NotesSettings> call, @NonNull Response<NotesSettings> response) {
final NotesSettings body = response.body();
@ -254,9 +254,9 @@ public class ManageAccountsActivity extends LockedActivity {
@NonNull
private ViewGroup createDialogViewWrapper() {
final var progressBar = new ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal);
final ProgressBar progressBar = new ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal);
progressBar.setIndeterminate(true);
final var wrapper = new FrameLayout(this);
final FrameLayout wrapper = new FrameLayout(this);
final int paddingVertical = getResources().getDimensionPixelSize(R.dimen.spacer_1x);
final int paddingHorizontal = SDK_INT >= LOLLIPOP_MR1
? getDimensionFromAttribute(android.R.attr.dialogPreferredPadding)
@ -268,7 +268,7 @@ public class ManageAccountsActivity extends LockedActivity {
@Px
private int getDimensionFromAttribute(@SuppressWarnings("SameParameterValue") @AttrRes int attr) {
final var typedValue = new TypedValue();
final TypedValue typedValue = new TypedValue();
if (getTheme().resolveAttribute(attr, typedValue, true))
return TypedValue.complexToDimensionPixelSize(typedValue.data, getResources().getDisplayMetrics());
else {

View file

@ -48,7 +48,7 @@ public class ManageAccountsViewModel extends AndroidViewModel {
public void deleteAccount(@NonNull Account account, @NonNull Context context) {
executor.submit(() -> {
final var accounts = repo.getAccounts();
final List<Account> accounts = repo.getAccounts();
for (int i = 0; i < accounts.size(); i++) {
if (accounts.get(i).getId() == account.getId()) {
if (i > 0) {

View file

@ -60,7 +60,7 @@ public class ApiProvider {
if (API_CACHE_OCS.containsKey(ssoAccount.name)) {
return API_CACHE_OCS.get(ssoAccount.name);
}
final var ocsAPI = new NextcloudRetrofitApiBuilder(getNextcloudAPI(context, ssoAccount), API_ENDPOINT_OCS).create(OcsAPI.class);
final OcsAPI ocsAPI = new NextcloudRetrofitApiBuilder(getNextcloudAPI(context, ssoAccount), API_ENDPOINT_OCS).create(OcsAPI.class);
API_CACHE_OCS.put(ssoAccount.name, ocsAPI);
return ocsAPI;
}
@ -72,7 +72,7 @@ public class ApiProvider {
if (API_CACHE_NOTES.containsKey(ssoAccount.name)) {
return API_CACHE_NOTES.get(ssoAccount.name);
}
final var notesAPI = new NotesAPI(getNextcloudAPI(context, ssoAccount), preferredApiVersion);
final NotesAPI notesAPI = new NotesAPI(getNextcloudAPI(context, ssoAccount), preferredApiVersion);
API_CACHE_NOTES.put(ssoAccount.name, notesAPI);
return notesAPI;
}
@ -82,12 +82,12 @@ public class ApiProvider {
return API_CACHE.get(ssoAccount.name);
} else {
Log.v(TAG, "NextcloudRequest account: " + ssoAccount.name);
final var nextcloudAPI = new NextcloudAPI(context.getApplicationContext(), ssoAccount,
final NextcloudAPI nextcloudAPI = new NextcloudAPI(context.getApplicationContext(), ssoAccount,
new GsonBuilder()
.excludeFieldsWithoutExposeAnnotation()
.registerTypeHierarchyAdapter(Calendar.class, (JsonSerializer<Calendar>) (src, typeOfSrc, ctx) -> new JsonPrimitive(src.getTimeInMillis() / 1_000))
.registerTypeHierarchyAdapter(Calendar.class, (JsonDeserializer<Calendar>) (src, typeOfSrc, ctx) -> {
final var calendar = Calendar.getInstance();
final Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(src.getAsLong() * 1_000);
return calendar;
})
@ -117,7 +117,7 @@ public class ApiProvider {
public synchronized void invalidateAPICache(@NonNull SingleSignOnAccount ssoAccount) {
Log.v(TAG, "Invalidating API cache for " + ssoAccount.name);
if (API_CACHE.containsKey(ssoAccount.name)) {
final var nextcloudAPI = API_CACHE.get(ssoAccount.name);
final NextcloudAPI nextcloudAPI = API_CACHE.get(ssoAccount.name);
if (nextcloudAPI != null) {
nextcloudAPI.stop();
}
@ -131,10 +131,10 @@ public class ApiProvider {
* Invalidates the whole API cache for all accounts
*/
public synchronized void invalidateAPICache() {
for (final String key : API_CACHE.keySet()) {
for (String key : API_CACHE.keySet()) {
Log.v(TAG, "Invalidating API cache for " + key);
if (API_CACHE.containsKey(key)) {
final var nextcloudAPI = API_CACHE.get(key);
final NextcloudAPI nextcloudAPI = API_CACHE.get(key);
if (nextcloudAPI != null) {
nextcloudAPI.stop();
}

View file

@ -27,11 +27,11 @@ public class CapabilitiesClient {
@WorkerThread
public static Capabilities getCapabilities(@NonNull Context context, @NonNull SingleSignOnAccount ssoAccount, @Nullable String lastETag, @NonNull ApiProvider apiProvider) throws Throwable {
final var ocsAPI = apiProvider.getOcsAPI(context, ssoAccount);
final OcsAPI ocsAPI = apiProvider.getOcsAPI(context, ssoAccount);
try {
final var response = ocsAPI.getCapabilities(lastETag).blockingSingle();
final var capabilities = response.getResponse().ocs.data;
final var headers = response.getHeaders();
final ParsedResponse<OcsResponse<Capabilities>> response = ocsAPI.getCapabilities(lastETag).blockingSingle();
final Capabilities capabilities = response.getResponse().ocs.data;
final Map<String, String> headers = response.getHeaders();
if (headers != null) {
capabilities.setETag(headers.get(HEADER_KEY_ETAG));
} else {
@ -39,7 +39,7 @@ public class CapabilitiesClient {
}
return capabilities;
} catch (RuntimeException e) {
final var cause = e.getCause();
final Throwable cause = e.getCause();
if (cause != null) {
throw cause;
} else {
@ -51,11 +51,11 @@ public class CapabilitiesClient {
@WorkerThread
@Nullable
public static String getDisplayName(@NonNull Context context, @NonNull SingleSignOnAccount ssoAccount, @NonNull ApiProvider apiProvider) {
final var ocsAPI = apiProvider.getOcsAPI(context, ssoAccount);
final OcsAPI ocsAPI = apiProvider.getOcsAPI(context, ssoAccount);
try {
final var userResponse = ocsAPI.getUser(ssoAccount.userId).execute();
final Response<OcsResponse<OcsUser>> userResponse = ocsAPI.getUser(ssoAccount.userId).execute();
if (userResponse.isSuccessful()) {
final var ocsResponse = userResponse.body();
final OcsResponse<OcsUser> ocsResponse = userResponse.body();
if (ocsResponse != null) {
return ocsResponse.ocs.data.displayName;
} else {

View file

@ -42,12 +42,12 @@ public class CapabilitiesWorker extends Worker {
@NonNull
@Override
public Result doWork() {
final var repo = NotesRepository.getInstance(getApplicationContext());
for (final var account : repo.getAccounts()) {
final NotesRepository repo = NotesRepository.getInstance(getApplicationContext());
for (Account account : repo.getAccounts()) {
try {
final var ssoAccount = AccountImporter.getSingleSignOnAccount(getApplicationContext(), account.getAccountName());
final SingleSignOnAccount ssoAccount = AccountImporter.getSingleSignOnAccount(getApplicationContext(), account.getAccountName());
Log.i(TAG, "Refreshing capabilities for " + ssoAccount.name);
final var capabilities = CapabilitiesClient.getCapabilities(getApplicationContext(), ssoAccount, account.getCapabilitiesETag(), ApiProvider.getInstance());
final Capabilities capabilities = CapabilitiesClient.getCapabilities(getApplicationContext(), ssoAccount, account.getCapabilitiesETag(), ApiProvider.getInstance());
repo.updateCapabilitiesETag(account.getId(), capabilities.getETag());
repo.updateBrand(account.getId(), capabilities.getColor(), capabilities.getTextColor());
repo.updateApiVersion(account.getId(), capabilities.getApiVersion());

View file

@ -155,7 +155,7 @@ public class NotesRepository {
// Registers BroadcastReceiver to track network connection changes.
this.context.registerReceiver(networkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
final var prefs = PreferenceManager.getDefaultSharedPreferences(this.context);
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.context);
prefs.registerOnSharedPreferenceChangeListener(onSharedPreferenceChangeListener);
syncOnlyOnWifi = prefs.getBoolean(syncOnlyOnWifiKey, false);
@ -167,7 +167,7 @@ public class NotesRepository {
@AnyThread
public void addAccount(@NonNull String url, @NonNull String username, @NonNull String accountName, @NonNull Capabilities capabilities, @Nullable String displayName, @NonNull IResponseCallback<Account> callback) {
final var createdAccount = db.getAccountDao().getAccountById(db.getAccountDao().insert(new Account(url, username, accountName, displayName, capabilities)));
final Account createdAccount = db.getAccountDao().getAccountById(db.getAccountDao().insert(new Account(url, username, accountName, displayName, capabilities)));
if (createdAccount == null) {
callback.onError(new Exception("Could not read created account."));
} else {
@ -377,8 +377,8 @@ public class NotesRepository {
@NonNull
@MainThread
public LiveData<Note> addNoteAndSync(Account account, Note note) {
final var entity = new Note(0, null, note.getModified(), note.getTitle(), note.getContent(), note.getCategory(), note.getFavorite(), note.getETag(), DBStatus.LOCAL_EDITED, account.getId(), generateNoteExcerpt(note.getContent(), note.getTitle()), 0);
final var ret = new MutableLiveData<Note>();
final Note entity = new Note(0, null, note.getModified(), note.getTitle(), note.getContent(), note.getCategory(), note.getFavorite(), note.getETag(), DBStatus.LOCAL_EDITED, account.getId(), generateNoteExcerpt(note.getContent(), note.getTitle()), 0);
final MutableLiveData<Note> ret = new MutableLiveData<>();
executor.submit(() -> ret.postValue(addNote(account.getId(), entity)));
return map(ret, newNote -> {
notifyWidgets();
@ -406,7 +406,7 @@ public class NotesRepository {
@MainThread
public LiveData<Note> moveNoteToAnotherAccount(Account account, @NonNull Note note) {
final var fullNote = new Note(null, note.getModified(), note.getTitle(), note.getContent(), note.getCategory(), note.getFavorite(), null);
final Note fullNote = new Note(null, note.getModified(), note.getTitle(), note.getContent(), note.getCategory(), note.getFavorite(), null);
deleteNoteAndSync(account, note.getId());
return map(addNoteAndSync(account, fullNote), (createdNote) -> {
db.getNoteDao().updateStatus(createdNote.getId(), DBStatus.LOCAL_EDITED);
@ -518,10 +518,10 @@ public class NotesRepository {
scheduleSync(account, true);
if (SDK_INT >= O) {
final var shortcutManager = context.getSystemService(ShortcutManager.class);
ShortcutManager shortcutManager = context.getSystemService(ShortcutManager.class);
if (shortcutManager != null) {
shortcutManager.getPinnedShortcuts().forEach((shortcut) -> {
final String shortcutId = String.valueOf(id);
String shortcutId = id + "";
if (shortcut.getId().equals(shortcutId)) {
Log.v(TAG, "Removing shortcut for " + shortcutId);
shortcutManager.disableShortcuts(Collections.singletonList(shortcutId), context.getResources().getString(R.string.note_has_been_deleted));
@ -549,14 +549,14 @@ public class NotesRepository {
private void updateDynamicShortcuts(long accountId) {
executor.submit(() -> {
if (SDK_INT >= android.os.Build.VERSION_CODES.N_MR1) {
final var shortcutManager = this.context.getSystemService(ShortcutManager.class);
final ShortcutManager shortcutManager = this.context.getSystemService(ShortcutManager.class);
if (shortcutManager != null) {
if (!shortcutManager.isRateLimitingActive()) {
var newShortcuts = new ArrayList<ShortcutInfo>();
List<ShortcutInfo> newShortcuts = new ArrayList<>();
for (final var note : db.getNoteDao().getRecentNotes(accountId)) {
for (Note note : db.getNoteDao().getRecentNotes(accountId)) {
if (!TextUtils.isEmpty(note.getTitle())) {
final var intent = new Intent(this.context, EditNoteActivity.class);
Intent intent = new Intent(this.context, EditNoteActivity.class);
intent.putExtra(EditNoteActivity.PARAM_NOTE_ID, note.getId());
intent.setAction(ACTION_SHORTCUT);
@ -583,7 +583,7 @@ public class NotesRepository {
* @param raw has to be a JSON array as a string <code>["0.2", "1.0", ...]</code>
*/
public void updateApiVersion(long accountId, @Nullable String raw) {
final var apiVersions = ApiVersionUtil.parse(raw);
final Collection<ApiVersion> apiVersions = ApiVersionUtil.parse(raw);
if (apiVersions.size() > 0) {
final int updatedRows = db.getAccountDao().updateApiVersion(accountId, ApiVersionUtil.serialize(apiVersions));
if (updatedRows == 0) {
@ -613,8 +613,8 @@ public class NotesRepository {
@AnyThread
public void modifyCategoryOrder(long accountId, @NonNull NavigationCategory selectedCategory, @NonNull CategorySortingMethod sortingMethod) {
executor.submit(() -> {
final var ctx = context.getApplicationContext();
final var sp = PreferenceManager.getDefaultSharedPreferences(ctx).edit();
final Context ctx = context.getApplicationContext();
final SharedPreferences.Editor sp = PreferenceManager.getDefaultSharedPreferences(ctx).edit();
int orderIndex = sortingMethod.getId();
switch (selectedCategory.getType()) {
@ -636,7 +636,7 @@ public class NotesRepository {
if (category != null) {
if (db.getCategoryOptionsDao().modifyCategoryOrder(accountId, category, sortingMethod) == 0) {
// Nothing updated means we didn't have this yet
final var categoryOptions = new CategoryOptions();
final CategoryOptions categoryOptions = new CategoryOptions();
categoryOptions.setAccountId(accountId);
categoryOptions.setCategory(category);
categoryOptions.setSortingMethod(sortingMethod);
@ -667,7 +667,7 @@ public class NotesRepository {
@NonNull
@MainThread
public LiveData<CategorySortingMethod> getCategoryOrder(@NonNull NavigationCategory selectedCategory) {
final var sp = PreferenceManager.getDefaultSharedPreferences(context);
final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
String prefKey;
switch (selectedCategory.getType()) {
@ -838,9 +838,9 @@ public class NotesRepository {
Log.d(TAG, "... scheduled");
syncScheduled.put(account.getId(), true);
if (callbacksPush.containsKey(account.getId()) && callbacksPush.get(account.getId()) != null) {
final var callbacks = callbacksPush.get(account.getId());
final List<ISyncCallback> callbacks = callbacksPush.get(account.getId());
if (callbacks != null) {
for (final var callback : callbacks) {
for (ISyncCallback callback : callbacks) {
callback.onScheduled();
}
} else {
@ -850,9 +850,9 @@ public class NotesRepository {
} else {
Log.d(TAG, "... do nothing");
if (callbacksPush.containsKey(account.getId()) && callbacksPush.get(account.getId()) != null) {
final var callbacks = callbacksPush.get(account.getId());
final List<ISyncCallback> callbacks = callbacksPush.get(account.getId());
if (callbacks != null) {
for (final var callback : callbacks) {
for (ISyncCallback callback : callbacks) {
callback.onScheduled();
}
} else {
@ -865,12 +865,12 @@ public class NotesRepository {
public void updateNetworkStatus() {
try {
final var connMgr = (ConnectivityManager) this.context.getSystemService(Context.CONNECTIVITY_SERVICE);
final ConnectivityManager connMgr = (ConnectivityManager) this.context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connMgr == null) {
throw new NetworkErrorException("ConnectivityManager is null");
}
final var activeInfo = connMgr.getActiveNetworkInfo();
final NetworkInfo activeInfo = connMgr.getActiveNetworkInfo();
if (activeInfo == null) {
throw new NetworkErrorException("NetworkInfo is null");
}
@ -878,7 +878,7 @@ public class NotesRepository {
if (activeInfo.isConnected()) {
networkConnected = true;
final var networkInfo = connMgr.getNetworkInfo((ConnectivityManager.TYPE_WIFI));
final NetworkInfo networkInfo = connMgr.getNetworkInfo((ConnectivityManager.TYPE_WIFI));
if (networkInfo == null) {
throw new NetworkErrorException("connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI) is null");
}

View file

@ -90,7 +90,7 @@ abstract class NotesServerSyncTask extends Thread {
Log.i(TAG, "STARTING SYNCHRONIZATION");
final var status = new SyncResultStatus();
final SyncResultStatus status = new SyncResultStatus();
status.pushSuccessful = pushLocalChanges();
if (!onlyLocalChanges) {
status.pullSuccessful = pullRemoteChanges();
@ -112,7 +112,7 @@ abstract class NotesServerSyncTask extends Thread {
Log.d(TAG, "pushLocalChanges()");
boolean success = true;
final var notes = repo.getLocalModifiedNotes(localAccount.getId());
final List<Note> notes = repo.getLocalModifiedNotes(localAccount.getId());
for (Note note : notes) {
Log.d(TAG, " Process Local Note: " + (BuildConfig.DEBUG ? note : note.getTitle()));
try {
@ -122,7 +122,7 @@ abstract class NotesServerSyncTask extends Thread {
Log.v(TAG, " ...create/edit");
if (note.getRemoteId() != null) {
Log.v(TAG, " ...Note has remoteId → try to edit");
final var editResponse = notesAPI.editNote(note).execute();
final Response<Note> editResponse = notesAPI.editNote(note).execute();
if (editResponse.isSuccessful()) {
remoteNote = editResponse.body();
if (remoteNote == null) {
@ -131,7 +131,7 @@ abstract class NotesServerSyncTask extends Thread {
}
} else if (editResponse.code() == HTTP_NOT_FOUND) {
Log.v(TAG, " ...Note does no longer exist on server → recreate");
final var createResponse = notesAPI.createNote(note).execute();
final Response<Note> createResponse = notesAPI.createNote(note).execute();
if (createResponse.isSuccessful()) {
remoteNote = createResponse.body();
if (remoteNote == null) {
@ -146,7 +146,7 @@ abstract class NotesServerSyncTask extends Thread {
}
} else {
Log.v(TAG, " ...Note does not have a remoteId yet → create");
final var createResponse = notesAPI.createNote(note).execute();
final Response<Note> createResponse = notesAPI.createNote(note).execute();
if (createResponse.isSuccessful()) {
remoteNote = createResponse.body();
if (remoteNote == null) {
@ -166,7 +166,7 @@ abstract class NotesServerSyncTask extends Thread {
Log.v(TAG, " ...delete (only local, since it has never been synchronized)");
} else {
Log.v(TAG, " ...delete (from server and local)");
final var deleteResponse = notesAPI.deleteNote(note.getRemoteId()).execute();
final Response<Void> deleteResponse = notesAPI.deleteNote(note.getRemoteId()).execute();
if (!deleteResponse.isSuccessful()) {
if (deleteResponse.code() == HTTP_NOT_FOUND) {
Log.v(TAG, " ...delete (note has already been deleted remotely)");
@ -205,10 +205,10 @@ abstract class NotesServerSyncTask extends Thread {
private boolean pullRemoteChanges() {
Log.d(TAG, "pullRemoteChanges() for account " + localAccount.getAccountName());
try {
final var idMap = repo.getIdMap(localAccount.getId());
final Map<Long, Long> idMap = repo.getIdMap(localAccount.getId());
// FIXME re-reading the localAccount is only a workaround for a not-up-to-date eTag in localAccount.
final var accountFromDatabase = repo.getAccountById(localAccount.getId());
final Account accountFromDatabase = repo.getAccountById(localAccount.getId());
if (accountFromDatabase == null) {
callbacks.remove(localAccount.getId());
return true;
@ -216,18 +216,18 @@ abstract class NotesServerSyncTask extends Thread {
localAccount.setModified(accountFromDatabase.getModified());
localAccount.setETag(accountFromDatabase.getETag());
final var fetchResponse = notesAPI.getNotes(localAccount.getModified(), localAccount.getETag()).blockingSingle();
final var remoteNotes = fetchResponse.getResponse();
final var remoteIDs = new HashSet<Long>();
final ParsedResponse<List<Note>> fetchResponse = notesAPI.getNotes(localAccount.getModified(), localAccount.getETag()).blockingSingle();
final List<Note> remoteNotes = fetchResponse.getResponse();
final Set<Long> remoteIDs = new HashSet<>();
// pull remote changes: update or create each remote note
for (final var remoteNote : remoteNotes) {
for (Note remoteNote : remoteNotes) {
Log.v(TAG, " Process Remote Note: " + (BuildConfig.DEBUG ? remoteNote : remoteNote.getTitle()));
remoteIDs.add(remoteNote.getRemoteId());
if (remoteNote.getModified() == null) {
Log.v(TAG, " ... unchanged");
} else if (idMap.containsKey(remoteNote.getRemoteId())) {
Log.v(TAG, " ... found → Update");
final Long localId = idMap.get(remoteNote.getRemoteId());
Long localId = idMap.get(remoteNote.getRemoteId());
if (localId != null) {
repo.updateIfNotModifiedLocallyAndAnyRemoteColumnHasChanged(
localId, remoteNote.getModified().getTimeInMillis(), remoteNote.getTitle(), remoteNote.getFavorite(), remoteNote.getCategory(), remoteNote.getETag(), remoteNote.getContent(), generateNoteExcerpt(remoteNote.getContent(), remoteNote.getTitle()));
@ -241,7 +241,7 @@ abstract class NotesServerSyncTask extends Thread {
}
Log.d(TAG, " Remove remotely deleted Notes (only those without local changes)");
// remove remotely deleted notes (only those without local changes)
for (final var entry : idMap.entrySet()) {
for (Map.Entry<Long, Long> entry : idMap.entrySet()) {
if (!remoteIDs.contains(entry.getKey())) {
Log.v(TAG, " ... remove " + entry.getValue());
repo.deleteByNoteId(entry.getValue(), DBStatus.VOID);
@ -251,7 +251,7 @@ abstract class NotesServerSyncTask extends Thread {
// update ETag and Last-Modified in order to reduce size of next response
localAccount.setETag(fetchResponse.getHeaders().get(HEADER_KEY_ETAG));
final var lastModified = Calendar.getInstance();
final Calendar lastModified = Calendar.getInstance();
lastModified.setTimeInMillis(0);
final String lastModifiedHeader = fetchResponse.getHeaders().get(HEADER_KEY_LAST_MODIFIED);
if (lastModifiedHeader != null)

View file

@ -33,8 +33,8 @@ public class SyncWorker extends Worker {
@NonNull
@Override
public Result doWork() {
final var repo = NotesRepository.getInstance(getApplicationContext());
for (final var account : repo.getAccounts()) {
NotesRepository repo = NotesRepository.getInstance(getApplicationContext());
for (Account account : repo.getAccounts()) {
Log.v(TAG, "Starting background synchronization for " + account.getAccountName());
repo.addCallbackPull(account, () -> Log.v(TAG, "Finished background synchronization for " + account.getAccountName()));
repo.scheduleSync(account, false);
@ -53,7 +53,7 @@ public class SyncWorker extends Worker {
public static void update(@NonNull Context context, boolean backgroundSync) {
deregister(context);
if (backgroundSync) {
final var work = new PeriodicWorkRequest.Builder(SyncWorker.class, 15, TimeUnit.MINUTES)
PeriodicWorkRequest work = new PeriodicWorkRequest.Builder(SyncWorker.class, 15, TimeUnit.MINUTES)
.setConstraints(constraints).build();
WorkManager.getInstance(context.getApplicationContext()).enqueueUniquePeriodicWork(WORKER_TAG, ExistingPeriodicWorkPolicy.REPLACE, work);
Log.i(TAG, "Registering worker running each " + 15 + " " + TimeUnit.MINUTES);

View file

@ -26,14 +26,14 @@ public class Migration_10_11 extends Migration {
*/
@Override
public void migrate(@NonNull SupportSQLiteDatabase database) {
final var sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
final var editor = sharedPreferences.edit();
final var prefs = sharedPreferences.getAll();
for (final var pref : prefs.entrySet()) {
final String key = pref.getKey();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sharedPreferences.edit();
Map<String, ?> prefs = sharedPreferences.getAll();
for (Map.Entry<String, ?> pref : prefs.entrySet()) {
String key = pref.getKey();
final String DARK_THEME_KEY = "NLW_darkTheme";
if ("darkTheme".equals(key) || key.startsWith(DARK_THEME_KEY) || key.startsWith("SNW_darkTheme")) {
final Boolean darkTheme = (Boolean) pref.getValue();
Boolean darkTheme = (Boolean) pref.getValue();
editor.putString(pref.getKey(), darkTheme ? DarkModeSetting.DARK.name() : DarkModeSetting.LIGHT.name());
}
}

View file

@ -47,10 +47,10 @@ public class Migration_13_14 extends Migration {
final String SP_WIDGET_KEY = "single_note_widget";
final String SP_ACCOUNT_ID_KEY = "SNW_accountId";
final String SP_DARK_THEME_KEY = "SNW_darkTheme";
final var sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
final var editor = sharedPreferences.edit();
final var prefs = sharedPreferences.getAll();
for (final var pref : prefs.entrySet()) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sharedPreferences.edit();
Map<String, ?> prefs = sharedPreferences.getAll();
for (Map.Entry<String, ?> pref : prefs.entrySet()) {
final String key = pref.getKey();
Integer widgetId = null;
Long noteId = null;
@ -69,7 +69,7 @@ public class Migration_13_14 extends Migration {
themeMode = sharedPreferences.getBoolean(SP_DARK_THEME_KEY + widgetId, false) ? DarkModeSetting.DARK.getModeId() : DarkModeSetting.LIGHT.getModeId();
}
final var migratedWidgetValues = new ContentValues();
ContentValues migratedWidgetValues = new ContentValues();
migratedWidgetValues.put("ID", widgetId);
migratedWidgetValues.put("ACCOUNT_ID", accountId);
migratedWidgetValues.put("NOTE_ID", noteId);

View file

@ -27,7 +27,7 @@ public class Migration_14_15 extends Migration {
@Override
public void migrate(@NonNull SupportSQLiteDatabase db) {
// Rename a tmp_NOTES table.
final String tmpTableNotes = String.format("tmp_%s", "NOTES");
String tmpTableNotes = String.format("tmp_%s", "NOTES");
db.execSQL("ALTER TABLE NOTES RENAME TO " + tmpTableNotes);
db.execSQL("CREATE TABLE NOTES ( " +
"ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
@ -53,14 +53,14 @@ public class Migration_14_15 extends Migration {
createIndex(db, "CATEGORIES", "CATEGORY_ID", "CATEGORY_ACCOUNT_ID", "CATEGORY_TITLE");
// A hashtable storing categoryTitle - categoryId Mapping
// This is used to prevent too many searches in database
final var categoryTitleIdMap = new Hashtable<String, Integer>();
Hashtable<String, Integer> categoryTitleIdMap = new Hashtable<>();
int id = 1;
final var tmpNotesCursor = db.query("SELECT * FROM " + tmpTableNotes, null);
Cursor tmpNotesCursor = db.query("SELECT * FROM " + tmpTableNotes, null);
while (tmpNotesCursor.moveToNext()) {
final String categoryTitle = tmpNotesCursor.getString(8);
final int accountId = tmpNotesCursor.getInt(2);
String categoryTitle = tmpNotesCursor.getString(8);
int accountId = tmpNotesCursor.getInt(2);
Log.e("###", accountId + "");
final Integer categoryId;
Integer categoryId;
if (categoryTitleIdMap.containsKey(categoryTitle) && categoryTitleIdMap.get(categoryTitle) != null) {
categoryId = categoryTitleIdMap.get(categoryTitle);
} else {
@ -74,7 +74,7 @@ public class Migration_14_15 extends Migration {
categoryTitleIdMap.put(categoryTitle, categoryId);
}
// Move the data in tmp_NOTES to NOTES
final ContentValues values = new ContentValues();
ContentValues values = new ContentValues();
values.put("ID", tmpNotesCursor.getInt(0));
values.put("REMOTEID", tmpNotesCursor.getInt(1));
values.put("ACCOUNT_ID", tmpNotesCursor.getInt(2));
@ -99,7 +99,7 @@ public class Migration_14_15 extends Migration {
}
private static void createIndex(@NonNull SupportSQLiteDatabase db, @NonNull String table, @NonNull String column) {
final String indexName = table + "_" + column + "_idx";
String indexName = table + "_" + column + "_idx";
Log.v(TAG, "Creating database index: CREATE INDEX IF NOT EXISTS " + indexName + " ON " + table + "(" + column + ")");
db.execSQL("CREATE INDEX " + indexName + " ON " + table + "(" + column + ")");
}

View file

@ -51,10 +51,10 @@ public class Migration_15_16 extends Migration {
final String SP_DARK_THEME_KEY = "NLW_darkTheme";
final String SP_CATEGORY_KEY = "NLW_cat";
final var sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
final var editor = sharedPreferences.edit();
final var prefs = sharedPreferences.getAll();
for (final var pref : prefs.entrySet()) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sharedPreferences.edit();
Map<String, ?> prefs = sharedPreferences.getAll();
for (Map.Entry<String, ?> pref : prefs.entrySet()) {
final String key = pref.getKey();
Integer widgetId = null;
Integer mode = null;
@ -76,7 +76,7 @@ public class Migration_15_16 extends Migration {
if (mode == 2) {
final String categoryTitle = sharedPreferences.getString(SP_CATEGORY_KEY + widgetId, null);
final var cursor = db.query("SELECT CATEGORY_ID FROM CATEGORIES WHERE CATEGORY_TITLE = ? AND CATEGORY_ACCOUNT_ID = ?", new String[]{categoryTitle, String.valueOf(accountId)});
Cursor cursor = db.query("SELECT CATEGORY_ID FROM CATEGORIES WHERE CATEGORY_TITLE = ? AND CATEGORY_ACCOUNT_ID = ?", new String[]{categoryTitle, String.valueOf(accountId)});
if (cursor.moveToNext()) {
categoryId = cursor.getInt(0);
} else {
@ -85,7 +85,7 @@ public class Migration_15_16 extends Migration {
cursor.close();
}
final var migratedWidgetValues = new ContentValues();
ContentValues migratedWidgetValues = new ContentValues();
migratedWidgetValues.put("ID", widgetId);
migratedWidgetValues.put("ACCOUNT_ID", accountId);
migratedWidgetValues.put("CATEGORY_ID", categoryId);

View file

@ -90,8 +90,8 @@ public final class Migration_20_21 extends Migration {
}
private static void migrateAccounts(@NonNull SupportSQLiteDatabase db) {
final var cursor = db.query("SELECT * FROM ACCOUNTS", null);
final var values = new ContentValues(10);
final Cursor cursor = db.query("SELECT * FROM ACCOUNTS", null);
final ContentValues values = new ContentValues(10);
final int COLUMN_POSITION_ID = cursor.getColumnIndex("ID");
final int COLUMN_POSITION_URL = cursor.getColumnIndex("URL");
@ -131,8 +131,8 @@ public final class Migration_20_21 extends Migration {
}
private static void migrateCategories(@NonNull SupportSQLiteDatabase db) {
final var cursor = db.query("SELECT * FROM CATEGORIES", null);
final var values = new ContentValues(3);
final Cursor cursor = db.query("SELECT * FROM CATEGORIES", null);
final ContentValues values = new ContentValues(3);
final int COLUMN_POSITION_ACCOUNT_ID = cursor.getColumnIndex("CATEGORY_ACCOUNT_ID");
final int COLUMN_POSITION_TITLE = cursor.getColumnIndex("CATEGORY_TITLE");
@ -148,8 +148,8 @@ public final class Migration_20_21 extends Migration {
}
private static void migrateNotes(@NonNull SupportSQLiteDatabase db) {
final var cursor = db.query("SELECT NOTES.*, CATEGORIES.category_title as `CAT_TITLE` FROM NOTES LEFT JOIN CATEGORIES ON NOTES.category = CATEGORIES.category_id", null);
final var values = new ContentValues(12);
final Cursor cursor = db.query("SELECT NOTES.*, CATEGORIES.category_title as `CAT_TITLE` FROM NOTES LEFT JOIN CATEGORIES ON NOTES.category = CATEGORIES.category_id", null);
final ContentValues values = new ContentValues(12);
final int COLUMN_POSITION_ID = cursor.getColumnIndex("ID");
final int COLUMN_POSITION_REMOTEID = cursor.getColumnIndex("REMOTEID");
@ -183,8 +183,8 @@ public final class Migration_20_21 extends Migration {
}
private static void migrateNotesListWidgets(@NonNull SupportSQLiteDatabase db) {
final var cursor = db.query("SELECT WIDGET_NOTE_LISTS.*, CATEGORIES.category_title as `CATEGORY` FROM WIDGET_NOTE_LISTS LEFT JOIN CATEGORIES ON WIDGET_NOTE_LISTS.CATEGORY_ID = CATEGORIES.category_id", null);
final var values = new ContentValues(5);
final Cursor cursor = db.query("SELECT WIDGET_NOTE_LISTS.*, CATEGORIES.category_title as `CATEGORY` FROM WIDGET_NOTE_LISTS LEFT JOIN CATEGORIES ON WIDGET_NOTE_LISTS.CATEGORY_ID = CATEGORIES.category_id", null);
final ContentValues values = new ContentValues(5);
final int COLUMN_POSITION_ID = cursor.getColumnIndex("ID");
final int COLUMN_POSITION_ACCOUNT_ID = cursor.getColumnIndex("ACCOUNT_ID");
@ -204,8 +204,8 @@ public final class Migration_20_21 extends Migration {
}
private static void migrateSingleNotesWidgets(@NonNull SupportSQLiteDatabase db) {
final var cursor = db.query("SELECT * FROM WIDGET_SINGLE_NOTES", null);
final var values = new ContentValues(4);
final Cursor cursor = db.query("SELECT * FROM WIDGET_SINGLE_NOTES", null);
final ContentValues values = new ContentValues(4);
final int COLUMN_POSITION_ID = cursor.getColumnIndex("ID");
final int COLUMN_POSITION_ACCOUNT_ID = cursor.getColumnIndex("ACCOUNT_ID");

View file

@ -25,8 +25,8 @@ public class Migration_21_22 extends Migration {
@Override
public void migrate(@NonNull SupportSQLiteDatabase database) {
final var sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
final var editor = sharedPreferences.edit();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sharedPreferences.edit();
if (sharedPreferences.contains("backgroundSync")) {
editor.remove("backgroundSync");
if (sharedPreferences.getString("backgroundSync", "").equals("off")) {

View file

@ -46,8 +46,8 @@ public class Migration_22_23 extends Migration {
}
private static void sanitizeAccounts(@NonNull SupportSQLiteDatabase db) {
final var cursor = db.query("SELECT id, apiVersion FROM ACCOUNT", null);
final var values = new ContentValues(1);
final Cursor cursor = db.query("SELECT id, apiVersion FROM ACCOUNT", null);
final ContentValues values = new ContentValues(1);
final int COLUMN_POSITION_ID = cursor.getColumnIndex("id");
final int COLUMN_POSITION_API_VERSION = cursor.getColumnIndex("apiVersion");
@ -77,10 +77,10 @@ public class Migration_22_23 extends Migration {
}
}
final var result = new ArrayList<ApiVersion>();
final Collection<ApiVersion> result = new ArrayList<>();
for (int i = 0; i < a.length(); i++) {
try {
final var version = ApiVersion.of(a.getString(i));
final ApiVersion version = ApiVersion.of(a.getString(i));
if (version.getMajor() != 0 || version.getMinor() != 0) {
result.add(version);
}

View file

@ -24,9 +24,9 @@ public class Migration_9_10 extends Migration {
@Override
public void migrate(@NonNull SupportSQLiteDatabase db) {
db.execSQL("ALTER TABLE NOTES ADD COLUMN EXCERPT INTEGER NOT NULL DEFAULT ''");
final var cursor = db.query("NOTES", new String[]{"ID", "CONTENT", "TITLE"});
Cursor cursor = db.query("NOTES", new String[]{"ID", "CONTENT", "TITLE"});
while (cursor.moveToNext()) {
final var values = new ContentValues();
ContentValues values = new ContentValues();
values.put("EXCERPT", NoteUtil.generateNoteExcerpt(cursor.getString(1), cursor.getString(2)));
db.update("NOTES", OnConflictStrategy.REPLACE, values, "ID" + " = ? ", new String[]{cursor.getString(0)});
}

View file

@ -34,18 +34,18 @@ public class CapabilitiesDeserializer implements JsonDeserializer<Capabilities>
@Override
public Capabilities deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
final var response = new Capabilities();
final var data = json.getAsJsonObject();
final Capabilities response = new Capabilities();
final JsonObject data = json.getAsJsonObject();
if (data.has(CAPABILITIES)) {
final var capabilities = data.getAsJsonObject(CAPABILITIES);
final JsonObject capabilities = data.getAsJsonObject(CAPABILITIES);
if (capabilities.has(CAPABILITIES_NOTES)) {
final var notes = capabilities.getAsJsonObject(CAPABILITIES_NOTES);
final JsonObject notes = capabilities.getAsJsonObject(CAPABILITIES_NOTES);
if (notes.has(CAPABILITIES_NOTES_API_VERSION)) {
response.setApiVersion(notes.get(CAPABILITIES_NOTES_API_VERSION).toString());
}
}
if (capabilities.has(CAPABILITIES_THEMING)) {
final var theming = capabilities.getAsJsonObject(CAPABILITIES_THEMING);
final JsonObject theming = capabilities.getAsJsonObject(CAPABILITIES_THEMING);
if (theming.has(CAPABILITIES_THEMING_COLOR)) {
try {
response.setColor(Color.parseColor(ColorUtil.INSTANCE.formatColorToParsableHexString(theming.get(CAPABILITIES_THEMING_COLOR).getAsString())));

View file

@ -1,7 +1,6 @@
package it.niedermann.owncloud.notes.preferences;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.appcompat.app.AppCompatDelegate.NightMode;
import java.util.NoSuchElementException;
@ -32,14 +31,12 @@ public enum DarkModeSetting {
*/
SYSTEM_DEFAULT(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
@NightMode
private final int modeId;
DarkModeSetting(int modeId) {
this.modeId = modeId;
}
@NightMode
public int getModeId() {
return modeId;
}
@ -58,7 +55,7 @@ public enum DarkModeSetting {
* @return An instance of {@link DarkModeSetting}
*/
public static DarkModeSetting fromModeID(int id) {
for (final var value : DarkModeSetting.values()) {
for (DarkModeSetting value : DarkModeSetting.values()) {
if (value.modeId == id) {
return value;
}

View file

@ -74,7 +74,7 @@ public class PreferencesFragment extends PreferenceFragmentCompat implements Bra
Log.e(TAG, "Could not find \"" + getString(R.string.pref_key_lock) + "\"-preference.");
}
final var themePref = findPreference(getString(R.string.pref_key_theme));
final ListPreference themePref = findPreference(getString(R.string.pref_key_theme));
assert themePref != null;
themePref.setOnPreferenceChangeListener((preference, newValue) -> {
NotesApplication.setAppTheme(DarkModeSetting.valueOf((String) newValue));
@ -103,10 +103,12 @@ public class PreferencesFragment extends PreferenceFragmentCompat implements Bra
@Override
public void onStart() {
super.onStart();
final var context = requireContext();
@ColorInt final int mainColor = BrandingUtil.readBrandMainColor(context);
@ColorInt final int textColor = BrandingUtil.readBrandTextColor(context);
applyBrand(mainColor, textColor);
@Nullable Context context = getContext();
if (context != null) {
@ColorInt final int mainColor = BrandingUtil.readBrandMainColor(context);
@ColorInt final int textColor = BrandingUtil.readBrandTextColor(context);
applyBrand(mainColor, textColor);
}
}
/**

View file

@ -16,15 +16,16 @@ public class NewNoteTileService extends TileService {
@Override
public void onStartListening() {
final var tile = getQsTile();
Tile tile = getQsTile();
tile.setState(Tile.STATE_ACTIVE);
tile.updateTile();
}
@Override
public void onClick() {
// create new note intent
final var newNoteIntent = new Intent(getApplicationContext(), EditNoteActivity.class);
final Intent newNoteIntent = new Intent(getApplicationContext(), EditNoteActivity.class);
// ensure it won't open twice if already running
newNoteIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
// ask to unlock the screen if locked, then start new note intent

View file

@ -57,7 +57,7 @@ public class ApiVersion implements Comparable<ApiVersion> {
}
private static int extractNumber(String containsNumbers) {
final var matcher = NUMBER_EXTRACTION_PATTERN.matcher(containsNumbers);
final Matcher matcher = NUMBER_EXTRACTION_PATTERN.matcher(containsNumbers);
if (matcher.find()) {
return Integer.parseInt(matcher.group());
}

View file

@ -38,7 +38,7 @@ public enum CategorySortingMethod {
* @return the corresponding enum item with the index (ordinal)
*/
public static CategorySortingMethod findById(int id) {
for (final var csm : values()) {
for (CategorySortingMethod csm : values()) {
if (csm.getId() == id) {
return csm;
}

View file

@ -43,10 +43,10 @@ public class ApiVersionUtil {
}
}
final var result = new ArrayList<ApiVersion>();
final Collection<ApiVersion> result = new ArrayList<>();
for (int i = 0; i < a.length(); i++) {
try {
final var version = ApiVersion.of(a.getString(i));
final ApiVersion version = ApiVersion.of(a.getString(i));
if (version.getMajor() != 0 || version.getMinor() != 0) {
result.add(version);
}

View file

@ -16,7 +16,7 @@ public class DeviceCredentialUtil {
}
public static boolean areCredentialsAvailable(Context context) {
final var keyguardManager = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
KeyguardManager keyguardManager = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
if (keyguardManager != null) {
return keyguardManager.isKeyguardSecure();

View file

@ -1,6 +1,5 @@
package it.niedermann.owncloud.notes.shared.util;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Rect;
@ -35,8 +34,8 @@ public class DisplayUtils {
}
public static NavigationItem.CategoryNavigationItem convertToCategoryNavigationItem(@NonNull Context context, @NonNull CategoryWithNotesCount counter) {
final var res = context.getResources();
final String category = counter.getCategory().toLowerCase();
Resources res = context.getResources();
String category = counter.getCategory().toLowerCase();
int icon = NavigationAdapter.ICON_FOLDER;
if (category.equals(res.getString(R.string.category_music).toLowerCase())) {
icon = R.drawable.ic_library_music_grey600_24dp;
@ -55,7 +54,6 @@ public class DisplayUtils {
* @param parentView View
* @return keyboardVisibility Boolean
*/
@SuppressLint("WrongConstant")
public static boolean isSoftKeyboardVisible(@NonNull View parentView) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
final WindowInsetsCompat insets = ViewCompat.getRootWindowInsets(parentView);
@ -66,8 +64,8 @@ public class DisplayUtils {
//Arbitrary keyboard height
final int defaultKeyboardHeightDP = 100;
final int EstimatedKeyboardDP = defaultKeyboardHeightDP + 48;
final var rect = new Rect();
final int EstimatedKeyboardDP = defaultKeyboardHeightDP + (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? 48 : 0);
final Rect rect = new Rect();
final int estimatedKeyboardHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, EstimatedKeyboardDP, parentView.getResources().getDisplayMetrics());
parentView.getWindowVisibleDisplayFrame(rect);
final int heightDiff = parentView.getRootView().getHeight() - (rect.bottom - rect.top);

View file

@ -18,7 +18,7 @@ public final class NotesColorUtil {
}
public static boolean contrastRatioIsSufficient(@ColorInt int colorOne, @ColorInt int colorTwo) {
final var key = new ColorPair(colorOne, colorTwo);
ColorPair key = new ColorPair(colorOne, colorTwo);
Boolean ret = CONTRAST_RATIO_SUFFICIENT_CACHE.get(key);
if (ret == null) {
ret = ColorUtil.INSTANCE.getContrastRatio(colorOne, colorTwo) > 3d;
@ -37,7 +37,7 @@ public final class NotesColorUtil {
@SuppressWarnings({"EqualsWhichDoesntCheckParameterClass", "NumberEquality"})
@Override
public boolean equals(Object o) {
final var colorPair = (ColorPair) o;
final ColorPair colorPair = (ColorPair) o;
if (first != colorPair.first) return false;
return second == colorPair.second;
}

View file

@ -19,10 +19,10 @@ public class CreateNoteWidget extends AppWidgetProvider {
int appWidgetId) {
// Construct the RemoteViews object
final var views = new RemoteViews(context.getPackageName(), R.layout.widget_create_note);
final var intent = new Intent(context, EditNoteActivity.class);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_create_note);
Intent intent = new Intent(context, EditNoteActivity.class);
final var pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.widget_create_note, pendingIntent);
// Instruct the widget manager to update the widget
@ -33,7 +33,7 @@ public class CreateNoteWidget extends AppWidgetProvider {
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// There may be multiple widgets active, so update all of them
for (final int appWidgetId : appWidgetIds) {
for (int appWidgetId : appWidgetIds) {
updateAppWidget(context, appWidgetManager, appWidgetId);
}
}

View file

@ -42,9 +42,9 @@ public class NoteListViewModel extends AndroidViewModel {
return switchMap(distinctUntilChanged(repo.countFavorites$(accountId)), (favoritesCount) -> {
Log.v(TAG, "[getAdapterCategories] getFavoritesCountLiveData: " + favoritesCount);
return map(distinctUntilChanged(repo.getCategories$(accountId)), fromDatabase -> {
final var categories = convertToCategoryNavigationItem(getApplication(), fromDatabase);
final List<NavigationItem.CategoryNavigationItem> categories = convertToCategoryNavigationItem(getApplication(), fromDatabase);
final var items = new ArrayList<NavigationItem>(fromDatabase.size() + 3);
final List<NavigationItem> items = new ArrayList<>(fromDatabase.size() + 3);
items.add(new NavigationItem(MainActivity.ADAPTER_KEY_RECENT, getApplication().getString(R.string.label_all_notes), count, R.drawable.ic_access_time_grey600_24dp, RECENT));
items.add(new NavigationItem(MainActivity.ADAPTER_KEY_STARRED, getApplication().getString(R.string.label_favorites), favoritesCount, R.drawable.ic_star_yellow_24dp, FAVORITES));
@ -52,7 +52,7 @@ public class NoteListViewModel extends AndroidViewModel {
items.add(new NavigationItem(MainActivity.ADAPTER_KEY_UNCATEGORIZED, "", null, NavigationAdapter.ICON_NOFOLDER));
}
for (final var item : categories) {
for (NavigationItem item : categories) {
final int slashIndex = item.label.indexOf('/');
item.label = slashIndex < 0 ? item.label : item.label.substring(0, slashIndex);

View file

@ -23,19 +23,19 @@ public class NoteListWidget extends AppWidgetProvider {
private final ExecutorService executor = Executors.newCachedThreadPool();
static void updateAppWidget(Context context, AppWidgetManager awm, int[] appWidgetIds) {
final var repo = NotesRepository.getInstance(context);
final NotesRepository repo = NotesRepository.getInstance(context);
RemoteViews views;
for (int appWidgetId : appWidgetIds) {
try {
final var data = repo.getNoteListWidgetData(appWidgetId);
final NotesListWidgetData data = repo.getNoteListWidgetData(appWidgetId);
final var serviceIntent = new Intent(context, NoteListWidgetService.class);
final Intent serviceIntent = new Intent(context, NoteListWidgetService.class);
serviceIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
serviceIntent.setData(Uri.parse(serviceIntent.toUri(Intent.URI_INTENT_SCHEME)));
final var pendingIntent = PendingIntent.getActivity(context, 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT | Intent.FILL_IN_COMPONENT);
final PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT | Intent.FILL_IN_COMPONENT);
Log.v(TAG, "-- data - " + data);
@ -61,7 +61,7 @@ public class NoteListWidget extends AppWidgetProvider {
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
final var awm = AppWidgetManager.getInstance(context);
AppWidgetManager awm = AppWidgetManager.getInstance(context);
if (intent.getAction() != null) {
if (intent.getAction().equals(AppWidgetManager.ACTION_APPWIDGET_UPDATE)) {
@ -83,9 +83,9 @@ public class NoteListWidget extends AppWidgetProvider {
@Override
public void onDeleted(Context context, int[] appWidgetIds) {
super.onDeleted(context, appWidgetIds);
final var repo = NotesRepository.getInstance(context);
final NotesRepository repo = NotesRepository.getInstance(context);
for (final int appWidgetId : appWidgetIds) {
for (int appWidgetId : appWidgetIds) {
executor.submit(() -> repo.removeNoteListWidget(appWidgetId));
}
}

View file

@ -54,10 +54,10 @@ public class NoteListWidgetConfigurationActivity extends LockedActivity {
setResult(RESULT_CANCELED);
repo = NotesRepository.getInstance(this);
final var args = getIntent().getExtras();
final Bundle extras = getIntent().getExtras();
if (args != null) {
appWidgetId = args.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
if (extras != null) {
appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);
}
@ -73,7 +73,7 @@ public class NoteListWidgetConfigurationActivity extends LockedActivity {
adapterCategories = new NavigationAdapter(this, new NavigationClickListener() {
@Override
public void onItemClick(NavigationItem item) {
final var data = new NotesListWidgetData();
NotesListWidgetData data = new NotesListWidgetData();
data.setId(appWidgetId);
if (item.type != null) {
@ -112,7 +112,7 @@ public class NoteListWidgetConfigurationActivity extends LockedActivity {
executor.submit(() -> {
repo.createOrUpdateNoteListWidgetData(data);
final var updateIntent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE, null, getApplicationContext(), NoteListWidget.class)
final Intent updateIntent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE, null, getApplicationContext(), NoteListWidget.class)
.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
setResult(RESULT_OK, updateIntent);
getApplicationContext().sendBroadcast(updateIntent);

View file

@ -177,7 +177,8 @@ public class NoteListWidgetFactory implements RemoteViewsService.RemoteViewsFact
Log.e(TAG, "Could not find position \"" + position + "\" in dbNotes list.");
return -2;
}
return dbNotes.get(position).getId();
Note note = dbNotes.get(position);
return note.getId();
}
}

View file

@ -25,22 +25,22 @@ public class SingleNoteWidget extends AppWidgetProvider {
private final ExecutorService executor = Executors.newCachedThreadPool();
static void updateAppWidget(Context context, AppWidgetManager awm, int[] appWidgetIds) {
final var templateIntent = new Intent(context, EditNoteActivity.class);
final var repo = NotesRepository.getInstance(context);
final Intent templateIntent = new Intent(context, EditNoteActivity.class);
final NotesRepository repo = NotesRepository.getInstance(context);
for (int appWidgetId : appWidgetIds) {
final var data = repo.getSingleNoteWidgetData(appWidgetId);
final SingleNoteWidgetData data = repo.getSingleNoteWidgetData(appWidgetId);
if (data != null) {
templateIntent.putExtra(BaseNoteFragment.PARAM_ACCOUNT_ID, data.getAccountId());
final var templatePendingIntent = PendingIntent.getActivity(context, appWidgetId, templateIntent,
final PendingIntent templatePendingIntent = PendingIntent.getActivity(context, appWidgetId, templateIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
final var serviceIntent = new Intent(context, SingleNoteWidgetService.class);
final Intent serviceIntent = new Intent(context, SingleNoteWidgetService.class);
serviceIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
serviceIntent.setData(Uri.parse(serviceIntent.toUri(Intent.URI_INTENT_SCHEME)));
final var views = new RemoteViews(context.getPackageName(), R.layout.widget_single_note);
final RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_single_note);
views.setPendingIntentTemplate(R.id.single_note_widget_lv, templatePendingIntent);
views.setRemoteAdapter(R.id.single_note_widget_lv, serviceIntent);
views.setEmptyView(R.id.single_note_widget_lv, R.id.widget_single_note_placeholder_tv);
@ -62,7 +62,7 @@ public class SingleNoteWidget extends AppWidgetProvider {
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
final var awm = AppWidgetManager.getInstance(context);
AppWidgetManager awm = AppWidgetManager.getInstance(context);
updateAppWidget(context, AppWidgetManager.getInstance(context),
(awm.getAppWidgetIds(new ComponentName(context, SingleNoteWidget.class))));
@ -70,7 +70,7 @@ public class SingleNoteWidget extends AppWidgetProvider {
@Override
public void onDeleted(Context context, int[] appWidgetIds) {
final var repo = NotesRepository.getInstance(context);
final NotesRepository repo = NotesRepository.getInstance(context);
for (int appWidgetId : appWidgetIds) {
executor.submit(() -> repo.removeSingleNoteWidget(appWidgetId));

View file

@ -28,8 +28,8 @@ public class SingleNoteWidgetConfigurationActivity extends MainActivity {
setResult(Activity.RESULT_CANCELED);
fabCreate.setVisibility(View.GONE);
final var toolbar = binding.activityNotesListView.toolbar;
final var swipeRefreshLayout = binding.activityNotesListView.swiperefreshlayout;
Toolbar toolbar = binding.activityNotesListView.toolbar;
SwipeRefreshLayout swipeRefreshLayout = binding.activityNotesListView.swiperefreshlayout;
toolbar.setTitle(R.string.activity_select_single_note);
swipeRefreshLayout.setEnabled(false);
swipeRefreshLayout.setRefreshing(false);
@ -42,15 +42,15 @@ public class SingleNoteWidgetConfigurationActivity extends MainActivity {
@Override
public void onNoteClick(int position, View v) {
final var note = (Note) adapter.getItem(position);
final var args = getIntent().getExtras();
final Note note = (Note) adapter.getItem(position);
final Bundle extras = getIntent().getExtras();
if (args == null) {
if (extras == null) {
finish();
return;
}
final int appWidgetId = args.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
int appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
executor.submit(() -> {
try {
@ -62,7 +62,7 @@ public class SingleNoteWidgetConfigurationActivity extends MainActivity {
NotesApplication.getAppTheme(this).getModeId()
)
);
final var updateIntent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE, null,
final Intent updateIntent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE, null,
getApplicationContext(), SingleNoteWidget.class)
.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
setResult(RESULT_OK, updateIntent);

View file

@ -41,7 +41,7 @@ public class SingleNoteWidgetFactory implements RemoteViewsService.RemoteViewsFa
@Override
public void onDataSetChanged() {
final var data = repo.getSingleNoteWidgetData(appWidgetId);
final SingleNoteWidgetData data = repo.getSingleNoteWidgetData(appWidgetId);
if (data != null) {
final long noteId = data.getNoteId();
Log.v(TAG, "Fetch note with id " + noteId);
@ -82,14 +82,14 @@ public class SingleNoteWidgetFactory implements RemoteViewsService.RemoteViewsFa
return null;
}
final var fillInIntent = new Intent();
final var args = new Bundle();
final Intent fillInIntent = new Intent();
final Bundle extras = new Bundle();
args.putLong(EditNoteActivity.PARAM_NOTE_ID, note.getId());
args.putLong(EditNoteActivity.PARAM_ACCOUNT_ID, note.getAccountId());
fillInIntent.putExtras(args);
extras.putLong(EditNoteActivity.PARAM_NOTE_ID, note.getId());
extras.putLong(EditNoteActivity.PARAM_ACCOUNT_ID, note.getAccountId());
fillInIntent.putExtras(extras);
final var note_content = new RemoteViews(context.getPackageName(), R.layout.widget_single_note_content);
final RemoteViews note_content = new RemoteViews(context.getPackageName(), R.layout.widget_single_note_content);
note_content.setOnClickFillInIntent(R.id.single_note_content_tv, fillInIntent);
note_content.setTextViewText(R.id.single_note_content_tv, MarkdownUtil.renderForRemoteView(context, note.getContent()));

View file

@ -11,7 +11,7 @@ public class SearchableBaseNoteFragmentTest {
@SuppressWarnings("ConstantConditions")
@Test
public void testCountOccurrencesFixed() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
final var method = SearchableBaseNoteFragment.class.getDeclaredMethod("countOccurrences", String.class, String.class);
final Method method = SearchableBaseNoteFragment.class.getDeclaredMethod("countOccurrences", String.class, String.class);
method.setAccessible(true);
for (int count = 0; count <= 15; ++count) {
@ -35,7 +35,7 @@ public class SearchableBaseNoteFragmentTest {
@SuppressWarnings("ConstantConditions")
@Test
public void testNullOrEmptyInput() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
final var method = SearchableBaseNoteFragment.class.getDeclaredMethod("countOccurrences", String.class, String.class);
final Method method = SearchableBaseNoteFragment.class.getDeclaredMethod("countOccurrences", String.class, String.class);
method.setAccessible(true);
int num;

View file

@ -41,7 +41,7 @@ public class GridItemDecorationTest {
assertThrows("Requires at least one column", IllegalArgumentException.class, () -> new GridItemDecoration(itemAdapter, 0, 5, 5, 5, 5, 5));
final var oneColumn = new GridItemDecoration(itemAdapter, 1, 5, 5, 5, 5, 5);
final GridItemDecoration oneColumn = new GridItemDecoration(itemAdapter, 1, 5, 5, 5, 5, 5);
testAssertion(oneColumn, 0, 0, true, 5, 5, 5, 5);
testAssertion(oneColumn, 0, 1, false, 0, 5, 5, 5);
@ -54,7 +54,7 @@ public class GridItemDecorationTest {
testAssertion(oneColumn, 0, 8, false, 0, 5, 5, 5);
testAssertion(oneColumn, 0, 9, true, 5, 5, 5, 5);
final var twoColumns = new GridItemDecoration(itemAdapter, 2, 5, 5, 5, 5, 5);
final GridItemDecoration twoColumns = new GridItemDecoration(itemAdapter, 2, 5, 5, 5, 5, 5);
testAssertion(twoColumns, 0, 0, true, 5, 5, 5, 5);
testAssertion(twoColumns, 0, 1, false, 0, 5, 5, 5);
@ -67,7 +67,7 @@ public class GridItemDecorationTest {
testAssertion(twoColumns, 0, 8, false, 0, 5, 5, 5);
testAssertion(twoColumns, 0, 9, true, 5, 5, 5, 5);
final var threeColumns = new GridItemDecoration(itemAdapter, 3, 5, 5, 5, 5, 5);
final GridItemDecoration threeColumns = new GridItemDecoration(itemAdapter, 3, 5, 5, 5, 5, 5);
testAssertion(threeColumns, 0, 0, true, 5, 5, 5, 5);
testAssertion(threeColumns, 0, 1, false, 0, 5, 5, 5);
@ -85,7 +85,7 @@ public class GridItemDecorationTest {
private void testAssertion(GridItemDecoration gid, int spanIndex, int position, boolean fullSpan, int top, int left, int right, int bottom) {
when(layoutParams.getSpanIndex()).thenReturn(spanIndex);
when(recyclerView.getChildAdapterPosition(any())).thenReturn(position);
final var result = new Rect();
final Rect result = new Rect();
gid.getItemOffsets(result, view, recyclerView, mock(RecyclerView.State.class));
if (fullSpan) {

View file

@ -43,7 +43,7 @@ public class AccountDaoTest {
@Test
public void insertAccount() {
final long createdId = db.getAccountDao().insert(new Account("https://äöüß.example.com", "彼得", "彼得@äöüß.example.com", null, new Capabilities()));
final var createdAccount = db.getAccountDao().getAccountById(createdId);
final Account createdAccount = db.getAccountDao().getAccountById(createdId);
assertEquals("https://äöüß.example.com", createdAccount.getUrl());
assertEquals("彼得", createdAccount.getUserName());
assertEquals("彼得@äöüß.example.com", createdAccount.getAccountName());
@ -51,7 +51,7 @@ public class AccountDaoTest {
@Test
public void updateApiVersionFromNull() {
final var account = db.getAccountDao().getAccountById(db.getAccountDao().insert(new Account("https://äöüß.example.com", "彼得", "彼得@äöüß.example.com", null, new Capabilities())));
final Account account = db.getAccountDao().getAccountById(db.getAccountDao().insert(new Account("https://äöüß.example.com", "彼得", "彼得@äöüß.example.com", null, new Capabilities())));
assertNull(account.getApiVersion());
assertEquals(0, db.getAccountDao().updateApiVersion(account.getId(), null));
@ -61,9 +61,9 @@ public class AccountDaoTest {
@Test
public void updateApiVersionFromExisting() {
final var capabilities = new Capabilities();
final Capabilities capabilities = new Capabilities();
capabilities.setApiVersion("[0.2]");
final var account = db.getAccountDao().getAccountById(db.getAccountDao().insert(new Account("https://äöüß.example.com", "彼得", "彼得@äöüß.example.com", null, capabilities)));
final Account account = db.getAccountDao().getAccountById(db.getAccountDao().insert(new Account("https://äöüß.example.com", "彼得", "彼得@äöüß.example.com", null, capabilities)));
assertEquals("[0.2]", account.getApiVersion());
assertEquals(0, db.getAccountDao().updateApiVersion(account.getId(), "[0.2]"));
@ -73,7 +73,7 @@ public class AccountDaoTest {
@Test
public void updateDisplayName() {
final var account = db.getAccountDao().getAccountById(db.getAccountDao().insert(new Account("https://äöüß.example.com", "彼得", "彼得@äöüß.example.com", null, new Capabilities())));
final Account account = db.getAccountDao().getAccountById(db.getAccountDao().insert(new Account("https://äöüß.example.com", "彼得", "彼得@äöüß.example.com", null, new Capabilities())));
assertEquals("Should read userName in favor of displayName if displayName is NULL", "彼得", account.getDisplayName());
db.getAccountDao().updateDisplayName(account.getId(), "");

View file

@ -38,7 +38,7 @@ public class ApiProviderTest {
@Test
public void testGetOcsAPI() {
var api = apiProvider.getOcsAPI(ApplicationProvider.getApplicationContext(), ssoAccount);
OcsAPI api = apiProvider.getOcsAPI(ApplicationProvider.getApplicationContext(), ssoAccount);
assertNotNull(api);
assertSame(api, apiProvider.getOcsAPI(ApplicationProvider.getApplicationContext(), ssoAccount));
@ -64,7 +64,7 @@ public class ApiProviderTest {
@Test
public void testGetNotesAPI() {
final var notesAPI = apiProvider.getNotesAPI(ApplicationProvider.getApplicationContext(), ssoAccount, ApiVersion.API_VERSION_0_2);
final NotesAPI notesAPI = apiProvider.getNotesAPI(ApplicationProvider.getApplicationContext(), ssoAccount, ApiVersion.API_VERSION_0_2);
assertNotNull(notesAPI);
@ -75,7 +75,7 @@ public class ApiProviderTest {
apiProvider.invalidateAPICache();
final var newNotesAPI = apiProvider.getNotesAPI(ApplicationProvider.getApplicationContext(), ssoAccount, ApiVersion.API_VERSION_1_0);
final NotesAPI newNotesAPI = apiProvider.getNotesAPI(ApplicationProvider.getApplicationContext(), ssoAccount, ApiVersion.API_VERSION_1_0);
assertNotSame("After a manual invalidation, the returned Notes API will be a new instance",
notesAPI, newNotesAPI);

View file

@ -61,7 +61,7 @@ public class CapabilitiesClientTest {
when(responseMock.getHeaders()).thenReturn(Map.of("ETag", "1234"));
when(ocsAPI.getCapabilities(any())).thenReturn(Observable.just(responseMock));
final var capabilities = CapabilitiesClient.getCapabilities(ApplicationProvider.getApplicationContext(), ssoAccount, null, apiProvider);
final Capabilities capabilities = CapabilitiesClient.getCapabilities(ApplicationProvider.getApplicationContext(), ssoAccount, null, apiProvider);
assertEquals("[1.0]", capabilities.getApiVersion());
assertEquals("ETag should be read correctly from response but wasn't.", "1234", capabilities.getETag());
@ -76,12 +76,12 @@ public class CapabilitiesClientTest {
@SuppressWarnings("unchecked")
@Test
public void testGetDisplayName() throws IOException {
final var mockOcs = new OcsResponse<OcsUser>();
final OcsResponse<OcsUser> mockOcs = new OcsResponse<>();
mockOcs.ocs = new OcsResponse.OcsWrapper<>();
mockOcs.ocs.data = new OcsUser();
mockOcs.ocs.data.displayName = "Peter";
final var responseMock = Response.success(mockOcs);
final var callMock = mock(Call.class);
final Response<OcsResponse<OcsUser>> responseMock = Response.success(mockOcs);
final Call<OcsResponse<OcsUser>> callMock = mock(Call.class);
when(ocsAPI.getUser(any())).thenReturn(callMock);

View file

@ -105,7 +105,7 @@ public class NotesDaoTest {
@Test
public void getRemoteIds() {
final var secondAccount = setupSecondAccount();
final Account secondAccount = setupSecondAccount();
db.getNoteDao().addNote(new Note(1, 4711L, Calendar.getInstance(), "T", "C", "", false, "1", VOID, account.getId(), "", 0));
db.getNoteDao().addNote(new Note(2, 1234L, Calendar.getInstance(), "T", "C", "", false, "1", LOCAL_EDITED, account.getId(), "", 0));
@ -125,7 +125,7 @@ public class NotesDaoTest {
db.getNoteDao().addNote(new Note(666, 1234L, Calendar.getInstance(), "T", "C", "", false, "1", LOCAL_EDITED, account.getId(), "", 0));
db.getNoteDao().addNote(new Note(987, 6969L, Calendar.getInstance(), "T", "C", "", false, "1", LOCAL_DELETED, account.getId(), "", 0));
final var pair = db.getNoteDao().getRemoteIdAndId(account.getId());
final List<Note> pair = db.getNoteDao().getRemoteIdAndId(account.getId());
assertEquals(2, pair.size());
assertTrue(pair.stream().anyMatch(note -> 815 == note.getId() && Long.valueOf(4711).equals(note.getRemoteId())));
assertTrue(pair.stream().anyMatch(note -> 666 == note.getId() && Long.valueOf(1234).equals(note.getRemoteId())));
@ -157,7 +157,7 @@ public class NotesDaoTest {
@Test
public void count() throws InterruptedException {
final var secondAccount = setupSecondAccountAndTestNotes();
final Account secondAccount = setupSecondAccountAndTestNotes();
assertEquals(Integer.valueOf(7), db.getNoteDao().count(account.getId()));
assertEquals(Integer.valueOf(5), db.getNoteDao().count(secondAccount.getId()));
@ -168,15 +168,15 @@ public class NotesDaoTest {
@Test
public void getLocalModifiedNotes() {
final var secondAccount = setupSecondAccountAndTestNotes();
final Account secondAccount = setupSecondAccountAndTestNotes();
final var accountNotes = db.getNoteDao().getLocalModifiedNotes(account.getId());
final List<Note> accountNotes = db.getNoteDao().getLocalModifiedNotes(account.getId());
assertEquals(6, accountNotes.size());
for (Note note : accountNotes) {
assertNotEquals(VOID, note.getStatus());
}
final var secondAccountNotes = db.getNoteDao().getLocalModifiedNotes(secondAccount.getId());
final List<Note> secondAccountNotes = db.getNoteDao().getLocalModifiedNotes(secondAccount.getId());
assertEquals(7, secondAccountNotes.size());
for (Note note : secondAccountNotes) {
assertNotEquals(VOID, note.getStatus());
@ -185,7 +185,7 @@ public class NotesDaoTest {
@Test
public void toggleFavorite() {
final var note = new Note(1, 1L, Calendar.getInstance(), "My-Title", "My-Content", "", false, "1", LOCAL_DELETED, account.getId(), "", 0);
final Note note = new Note(1, 1L, Calendar.getInstance(), "My-Title", "My-Content", "", false, "1", LOCAL_DELETED, account.getId(), "", 0);
db.getNoteDao().addNote(note);
db.getNoteDao().toggleFavorite(note.getId());
assertTrue(db.getNoteDao().getNoteById(note.getId()).getFavorite());
@ -197,7 +197,7 @@ public class NotesDaoTest {
@Test
public void updateRemoteId() {
final var note = new Note(1, 1L, Calendar.getInstance(), "My-Title", "My-Content", "", false, "1", LOCAL_DELETED, account.getId(), "", 0);
final Note note = new Note(1, 1L, Calendar.getInstance(), "My-Title", "My-Content", "", false, "1", LOCAL_DELETED, account.getId(), "", 0);
db.getNoteDao().addNote(note);
db.getNoteDao().updateRemoteId(1, 5L);
assertEquals(Long.valueOf(5), db.getNoteDao().getNoteById(1).getRemoteId());
@ -205,8 +205,8 @@ public class NotesDaoTest {
@Test
public void updateIfNotModifiedLocallyDuringSync_NotModified() {
final var localNote = new Note(1, 1L, Calendar.getInstance(), "My-Title", "My-Content", "", false, null, VOID, account.getId(), "", 0);
final var targetNote = new Note(1, 1L, Calendar.getInstance(), "My-Title", "My-Content", "", false, null, VOID, account.getId(), "", 0);
final Note localNote = new Note(1, 1L, Calendar.getInstance(), "My-Title", "My-Content", "", false, null, VOID, account.getId(), "", 0);
final Note targetNote = new Note(1, 1L, Calendar.getInstance(), "My-Title", "My-Content", "", false, null, VOID, account.getId(), "", 0);
db.getNoteDao().addNote(localNote);
@ -215,8 +215,8 @@ public class NotesDaoTest {
@Test
public void updateIfNotModifiedLocallyDuringSync_ModifiedContent() {
final var localNote = new Note(1, 1L, Calendar.getInstance(), "My-Title", "My-Content", "", false, null, VOID, account.getId(), "", 0);
final var targetNote = new Note(1, 1L, Calendar.getInstance(), "My-Title", "My-Content", "", false, null, VOID, account.getId(), "", 0);
final Note localNote = new Note(1, 1L, Calendar.getInstance(), "My-Title", "My-Content", "", false, null, VOID, account.getId(), "", 0);
final Note targetNote = new Note(1, 1L, Calendar.getInstance(), "My-Title", "My-Content", "", false, null, VOID, account.getId(), "", 0);
db.getNoteDao().addNote(localNote);
@ -227,8 +227,8 @@ public class NotesDaoTest {
@Test
public void updateIfNotModifiedLocallyDuringSync_ModifiedFavorite() {
final var localNote = new Note(1, 1L, Calendar.getInstance(), "My-Title", "My-Content", "", false, null, VOID, account.getId(), "", 0);
final var targetNote = new Note(1, 1L, Calendar.getInstance(), "My-Title", "My-Content", "", false, null, VOID, account.getId(), "", 0);
final Note localNote = new Note(1, 1L, Calendar.getInstance(), "My-Title", "My-Content", "", false, null, VOID, account.getId(), "", 0);
final Note targetNote = new Note(1, 1L, Calendar.getInstance(), "My-Title", "My-Content", "", false, null, VOID, account.getId(), "", 0);
db.getNoteDao().addNote(localNote);
@ -239,8 +239,8 @@ public class NotesDaoTest {
@Test
public void updateIfNotModifiedLocallyDuringSync_ModifiedCategory() {
final var localNote = new Note(1, 1L, Calendar.getInstance(), "My-Title", "My-Content", "", false, null, VOID, account.getId(), "", 0);
final var targetNote = new Note(1, 1L, Calendar.getInstance(), "My-Title", "My-Content", "", false, null, VOID, account.getId(), "", 0);
final Note localNote = new Note(1, 1L, Calendar.getInstance(), "My-Title", "My-Content", "", false, null, VOID, account.getId(), "", 0);
final Note targetNote = new Note(1, 1L, Calendar.getInstance(), "My-Title", "My-Content", "", false, null, VOID, account.getId(), "", 0);
db.getNoteDao().addNote(localNote);
@ -251,95 +251,95 @@ public class NotesDaoTest {
@Test
public void updateIfNotModifiedLocallyAndAnyRemoteColumnHasChanged_Nothing() {
final var localNote = db.getNoteDao().getNoteById(db.getNoteDao().addNote(new Note(1, 1L, Calendar.getInstance(), "My-Title", "My-Content", "", false, "1", VOID, account.getId(), "", 0)));
final Note localNote = db.getNoteDao().getNoteById(db.getNoteDao().addNote(new Note(1, 1L, Calendar.getInstance(), "My-Title", "My-Content", "", false, "1", VOID, account.getId(), "", 0)));
assertEquals(0, db.getNoteDao().updateIfNotModifiedLocallyAndAnyRemoteColumnHasChanged(
localNote.getId(), localNote.getModified().getTimeInMillis(), localNote.getTitle(), localNote.getFavorite(), localNote.getCategory(), localNote.getETag(), localNote.getContent(), localNote.getExcerpt()));
}
@Test
public void updateIfNotModifiedLocallyAndAnyRemoteColumnHasChanged_Nothing_ETagWasAndIsNull() {
final var localNote = db.getNoteDao().getNoteById(db.getNoteDao().addNote(new Note(1, 1L, Calendar.getInstance(), "My-Title", "My-Content", "", false, null, VOID, account.getId(), "", 0)));
final Note localNote = db.getNoteDao().getNoteById(db.getNoteDao().addNote(new Note(1, 1L, Calendar.getInstance(), "My-Title", "My-Content", "", false, null, VOID, account.getId(), "", 0)));
assertEquals(1, db.getNoteDao().updateIfNotModifiedLocallyAndAnyRemoteColumnHasChanged(
localNote.getId(), localNote.getModified().getTimeInMillis(), localNote.getTitle(), localNote.getFavorite(), localNote.getCategory(), null, localNote.getContent(), localNote.getExcerpt()));
}
@Test
public void updateIfNotModifiedLocallyAndAnyRemoteColumnHasChanged_Nothing_ETagWasNullButChanged() {
final var localNote = db.getNoteDao().getNoteById(db.getNoteDao().addNote(new Note(1, 1L, Calendar.getInstance(), "My-Title", "My-Content", "", false, null, VOID, account.getId(), "", 0)));
final Note localNote = db.getNoteDao().getNoteById(db.getNoteDao().addNote(new Note(1, 1L, Calendar.getInstance(), "My-Title", "My-Content", "", false, null, VOID, account.getId(), "", 0)));
assertEquals(1, db.getNoteDao().updateIfNotModifiedLocallyAndAnyRemoteColumnHasChanged(
localNote.getId(), localNote.getModified().getTimeInMillis(), localNote.getTitle(), localNote.getFavorite(), localNote.getCategory(), "1", localNote.getContent(), localNote.getExcerpt()));
}
@Test
public void updateIfNotModifiedLocallyAndAnyRemoteColumnHasChanged_Modified() {
final var localNote = db.getNoteDao().getNoteById(db.getNoteDao().addNote(new Note(1, 1L, Calendar.getInstance(), "My-Title", "My-Content", "", false, "1", VOID, account.getId(), "", 0)));
final Note localNote = db.getNoteDao().getNoteById(db.getNoteDao().addNote(new Note(1, 1L, Calendar.getInstance(), "My-Title", "My-Content", "", false, "1", VOID, account.getId(), "", 0)));
assertEquals(1, db.getNoteDao().updateIfNotModifiedLocallyAndAnyRemoteColumnHasChanged(
localNote.getId(), localNote.getModified().getTimeInMillis() + 1000, localNote.getTitle(), localNote.getFavorite(), localNote.getCategory(), localNote.getETag(), localNote.getContent(), localNote.getExcerpt()));
}
@Test
public void updateIfNotModifiedLocallyAndAnyRemoteColumnHasChanged_Title() {
final var localNote = db.getNoteDao().getNoteById(db.getNoteDao().addNote(new Note(1, 1L, Calendar.getInstance(), "My-Title", "My-Content", "", false, "1", VOID, account.getId(), "", 0)));
final Note localNote = db.getNoteDao().getNoteById(db.getNoteDao().addNote(new Note(1, 1L, Calendar.getInstance(), "My-Title", "My-Content", "", false, "1", VOID, account.getId(), "", 0)));
assertEquals(1, db.getNoteDao().updateIfNotModifiedLocallyAndAnyRemoteColumnHasChanged(
localNote.getId(), localNote.getModified().getTimeInMillis(), localNote.getTitle() + " ", localNote.getFavorite(), localNote.getCategory(), localNote.getETag(), localNote.getContent(), localNote.getExcerpt()));
}
@Test
public void updateIfNotModifiedLocallyAndAnyRemoteColumnHasChanged_Favorite() {
final var localNote = db.getNoteDao().getNoteById(db.getNoteDao().addNote(new Note(1, 1L, Calendar.getInstance(), "My-Title", "My-Content", "", false, "1", VOID, account.getId(), "", 0)));
final Note localNote = db.getNoteDao().getNoteById(db.getNoteDao().addNote(new Note(1, 1L, Calendar.getInstance(), "My-Title", "My-Content", "", false, "1", VOID, account.getId(), "", 0)));
assertEquals(1, db.getNoteDao().updateIfNotModifiedLocallyAndAnyRemoteColumnHasChanged(
localNote.getId(), localNote.getModified().getTimeInMillis(), localNote.getTitle(), !localNote.getFavorite(), localNote.getCategory(), localNote.getETag(), localNote.getContent(), localNote.getExcerpt()));
}
@Test
public void updateIfNotModifiedLocallyAndAnyRemoteColumnHasChanged_Category() {
final var localNote = db.getNoteDao().getNoteById(db.getNoteDao().addNote(new Note(1, 1L, Calendar.getInstance(), "My-Title", "My-Content", "", false, "1", VOID, account.getId(), "", 0)));
final Note localNote = db.getNoteDao().getNoteById(db.getNoteDao().addNote(new Note(1, 1L, Calendar.getInstance(), "My-Title", "My-Content", "", false, "1", VOID, account.getId(), "", 0)));
assertEquals(1, db.getNoteDao().updateIfNotModifiedLocallyAndAnyRemoteColumnHasChanged(
localNote.getId(), localNote.getModified().getTimeInMillis(), localNote.getTitle(), localNote.getFavorite(), localNote.getCategory() + " ", localNote.getETag(), localNote.getContent(), localNote.getExcerpt()));
}
@Test
public void updateIfNotModifiedLocallyAndAnyRemoteColumnHasChanged_ETag() {
final var localNote = db.getNoteDao().getNoteById(db.getNoteDao().addNote(new Note(1, 1L, Calendar.getInstance(), "My-Title", "My-Content", "", false, "1", VOID, account.getId(), "", 0)));
final Note localNote = db.getNoteDao().getNoteById(db.getNoteDao().addNote(new Note(1, 1L, Calendar.getInstance(), "My-Title", "My-Content", "", false, "1", VOID, account.getId(), "", 0)));
assertEquals(1, db.getNoteDao().updateIfNotModifiedLocallyAndAnyRemoteColumnHasChanged(
localNote.getId(), localNote.getModified().getTimeInMillis(), localNote.getTitle(), localNote.getFavorite(), localNote.getCategory(), localNote.getETag() + " ", localNote.getContent(), localNote.getExcerpt()));
}
@Test
public void updateIfNotModifiedLocallyAndAnyRemoteColumnHasChanged_Content() {
final var localNote = db.getNoteDao().getNoteById(db.getNoteDao().addNote(new Note(1, 1L, Calendar.getInstance(), "My-Title", "My-Content", "", false, "1", VOID, account.getId(), "", 0)));
final Note localNote = db.getNoteDao().getNoteById(db.getNoteDao().addNote(new Note(1, 1L, Calendar.getInstance(), "My-Title", "My-Content", "", false, "1", VOID, account.getId(), "", 0)));
assertEquals(1, db.getNoteDao().updateIfNotModifiedLocallyAndAnyRemoteColumnHasChanged(
localNote.getId(), localNote.getModified().getTimeInMillis(), localNote.getTitle(), localNote.getFavorite(), localNote.getCategory(), localNote.getETag(), localNote.getContent() + " ", localNote.getExcerpt()));
}
@Test
public void updateIfNotModifiedLocallyAndAnyRemoteColumnHasChanged_Excerpt() {
final var localNote = db.getNoteDao().getNoteById(db.getNoteDao().addNote(new Note(1, 1L, Calendar.getInstance(), "My-Title", "My-Content", "", false, "1", VOID, account.getId(), "", 0)));
final Note localNote = db.getNoteDao().getNoteById(db.getNoteDao().addNote(new Note(1, 1L, Calendar.getInstance(), "My-Title", "My-Content", "", false, "1", VOID, account.getId(), "", 0)));
assertEquals("Excerpt is a local property, and therefore should not prevent updating if different", 0, db.getNoteDao().updateIfNotModifiedLocallyAndAnyRemoteColumnHasChanged(
localNote.getId(), localNote.getModified().getTimeInMillis(), localNote.getTitle(), localNote.getFavorite(), localNote.getCategory(), localNote.getETag(), localNote.getContent(), localNote.getExcerpt() + " "));
}
@Test
public void updateIfNotModifiedLocallyAndAnyRemoteColumnHasChanged_ContentChangedButWasLocalEdited() {
final var localNote = db.getNoteDao().getNoteById(db.getNoteDao().addNote(new Note(1, 1L, Calendar.getInstance(), "My-Title", "My-Content", "", false, "1", LOCAL_EDITED, account.getId(), "", 0)));
final Note localNote = db.getNoteDao().getNoteById(db.getNoteDao().addNote(new Note(1, 1L, Calendar.getInstance(), "My-Title", "My-Content", "", false, "1", LOCAL_EDITED, account.getId(), "", 0)));
assertEquals(0, db.getNoteDao().updateIfNotModifiedLocallyAndAnyRemoteColumnHasChanged(
localNote.getId(), localNote.getModified().getTimeInMillis(), localNote.getTitle(), localNote.getFavorite(), localNote.getCategory(), localNote.getETag(), localNote.getContent() + " ", localNote.getExcerpt()));
}
@Test
public void updateIfNotModifiedLocallyAndAnyRemoteColumnHasChanged_ContentChangedButWasLocalDeleted() {
final var localNote = db.getNoteDao().getNoteById(db.getNoteDao().addNote(new Note(1, 1L, Calendar.getInstance(), "My-Title", "My-Content", "", false, "1", LOCAL_DELETED, account.getId(), "", 0)));
final Note localNote = db.getNoteDao().getNoteById(db.getNoteDao().addNote(new Note(1, 1L, Calendar.getInstance(), "My-Title", "My-Content", "", false, "1", LOCAL_DELETED, account.getId(), "", 0)));
assertEquals(0, db.getNoteDao().updateIfNotModifiedLocallyAndAnyRemoteColumnHasChanged(
localNote.getId(), localNote.getModified().getTimeInMillis(), localNote.getTitle(), localNote.getFavorite(), localNote.getCategory(), localNote.getETag(), localNote.getContent() + " ", localNote.getExcerpt()));
}
@Test
public void getCategoriesLiveData() throws InterruptedException {
final var secondAccount = setupSecondAccountAndTestNotes();
final Account secondAccount = setupSecondAccountAndTestNotes();
final var accountCategories = NotesTestingUtil.getOrAwaitValue(db.getNoteDao().getCategories$(account.getId()));
final List<CategoryWithNotesCount> accountCategories = NotesTestingUtil.getOrAwaitValue(db.getNoteDao().getCategories$(account.getId()));
assertEquals(4, accountCategories.size());
for (final var category : accountCategories) {
for (CategoryWithNotesCount category : accountCategories) {
assertEquals(account.getId(), category.getAccountId());
}
@ -348,9 +348,9 @@ public class NotesDaoTest {
assertTrue(accountCategories.stream().anyMatch(cat -> "ToDo".equals(cat.getCategory()) && Integer.valueOf(1).equals(cat.getTotalNotes())));
assertTrue(accountCategories.stream().anyMatch(cat -> "日记".equals(cat.getCategory()) && Integer.valueOf(1).equals(cat.getTotalNotes())));
final var secondAccountCategories = NotesTestingUtil.getOrAwaitValue(db.getNoteDao().getCategories$(secondAccount.getId()));
final List<CategoryWithNotesCount> secondAccountCategories = NotesTestingUtil.getOrAwaitValue(db.getNoteDao().getCategories$(secondAccount.getId()));
assertEquals(2, secondAccountCategories.size());
for (final var category : secondAccountCategories) {
for (CategoryWithNotesCount category : secondAccountCategories) {
assertEquals(secondAccount.getId(), category.getAccountId());
}
assertTrue(secondAccountCategories.stream().anyMatch(cat -> "Movies".equals(cat.getCategory()) && Integer.valueOf(4).equals(cat.getTotalNotes())));
@ -361,7 +361,7 @@ public class NotesDaoTest {
@Test
public void searchCategories() throws InterruptedException {
final var secondAccount = setupSecondAccountAndTestNotes();
final Account secondAccount = setupSecondAccountAndTestNotes();
assertEquals(2, NotesTestingUtil.getOrAwaitValue(db.getNoteDao().searchCategories$(account.getId(), "M%")).size());
assertEquals(1, NotesTestingUtil.getOrAwaitValue(db.getNoteDao().searchCategories$(account.getId(), "Mo%")).size());
@ -375,10 +375,10 @@ public class NotesDaoTest {
@Test
public void searchRecentByModified() {
final var secondAccount = setupSecondAccountAndTestNotes();
final var result = db.getNoteDao().searchRecentByModified(secondAccount.getId(), "T");
final Account secondAccount = setupSecondAccountAndTestNotes();
final List<Note> result = db.getNoteDao().searchRecentByModified(secondAccount.getId(), "T");
assertEquals(5, result.size());
for (final var note : result) {
for (Note note : result) {
assertNotEquals(DBStatus.LOCAL_DELETED, note.getStatus());
assertEquals(secondAccount.getId(), note.getAccountId());
assertTrue(note.getTitle().toLowerCase().contains("t") || note.getTitle().toLowerCase().contains("t"));
@ -400,10 +400,10 @@ public class NotesDaoTest {
}
private Account setupSecondAccountAndTestNotes() {
final var secondAccount = setupSecondAccount();
final Account secondAccount = setupSecondAccount();
long uniqueId = 1;
final var notes = new Note[]{
final Note[] notes = new Note[]{
new Note(uniqueId++, uniqueId++, Calendar.getInstance(), "T", "C", "Movies", false, null, VOID, account.getId(), "", 0),
new Note(uniqueId++, uniqueId++, Calendar.getInstance(), "T", "C", "Movies", false, null, LOCAL_EDITED, account.getId(), "", 0),
new Note(uniqueId++, uniqueId++, Calendar.getInstance(), "T", "C", "Movies", false, null, LOCAL_EDITED, account.getId(), "", 0),
@ -425,7 +425,7 @@ public class NotesDaoTest {
new Note(uniqueId++, uniqueId++, Calendar.getInstance(), "T", "C", "ToDo", true, null, LOCAL_DELETED, secondAccount.getId(), "", 0),
new Note(uniqueId++, uniqueId, Calendar.getInstance(), "T", "C", "ToDo", true, null, LOCAL_DELETED, secondAccount.getId(), "", 0)
};
for (final var note : notes) {
for (Note note : notes) {
db.getNoteDao().addNote(note);
}
return secondAccount;

View file

@ -65,15 +65,15 @@ public class NotesRepositoryTest {
@Before
public void setupDB() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, JSONException {
final var context = ApplicationProvider.getApplicationContext();
final Context context = ApplicationProvider.getApplicationContext();
db = Room
.inMemoryDatabaseBuilder(ApplicationProvider.getApplicationContext(), NotesDatabase.class)
.allowMainThreadQueries()
.build();
final var constructor = NotesRepository.class.getDeclaredConstructor(Context.class, NotesDatabase.class, ExecutorService.class, ExecutorService.class, ApiProvider.class);
final Constructor<NotesRepository> constructor = NotesRepository.class.getDeclaredConstructor(Context.class, NotesDatabase.class, ExecutorService.class, ExecutorService.class, ApiProvider.class);
constructor.setAccessible(true);
final var executor = MoreExecutors.newDirectExecutorService();
final ExecutorService executor = MoreExecutors.newDirectExecutorService();
repo = constructor.newInstance(context, db, executor, executor, ApiProvider.getInstance());
repo.addAccount("https://äöüß.example.com", "彼得", "彼得@äöüß.example.com", new Capabilities(), null, new IResponseCallback<Account>() {
@ -122,20 +122,20 @@ public class NotesRepositoryTest {
@Test
public void testGetInstance() {
final var repo = NotesRepository.getInstance(ApplicationProvider.getApplicationContext());
final NotesRepository repo = NotesRepository.getInstance(ApplicationProvider.getApplicationContext());
assertNotNull("Result of NotesRepository.getInstance() must not be null", repo);
assertSame("Result of NotesRepository.getInstance() must always return the same instance", repo, NotesRepository.getInstance(ApplicationProvider.getApplicationContext()));
}
@Test
public void testGetIdMap() {
final var idMapOfFirstAccount = repo.getIdMap(account.getId());
final Map<Long, Long> idMapOfFirstAccount = repo.getIdMap(account.getId());
assertEquals(3, idMapOfFirstAccount.size());
assertEquals(Long.valueOf(1L), idMapOfFirstAccount.get(1001L));
assertEquals(Long.valueOf(3L), idMapOfFirstAccount.get(1003L));
assertEquals(Long.valueOf(5L), idMapOfFirstAccount.get(1005L));
final var idMapOfSecondAccount = repo.getIdMap(secondAccount.getId());
final Map<Long, Long> idMapOfSecondAccount = repo.getIdMap(secondAccount.getId());
assertEquals(1, idMapOfSecondAccount.size());
assertEquals(Long.valueOf(8L), idMapOfSecondAccount.get(1008L));
}
@ -170,13 +170,13 @@ public class NotesRepositoryTest {
@Test
public void testAddNote() {
final var localNote = new Note(null, Calendar.getInstance(), "Fancy Title", "MyContent", "Samples", false, "123");
final Note localNote = new Note(null, Calendar.getInstance(), "Fancy Title", "MyContent", "Samples", false, "123");
localNote.setId(99);
final var createdNoteFromLocal = repo.addNote(account.getId(), localNote);
final Note createdNoteFromLocal = repo.addNote(account.getId(), localNote);
assertEquals(LOCAL_EDITED, createdNoteFromLocal.getStatus());
assertEquals("MyContent", createdNoteFromLocal.getExcerpt());
final var createdNoteFromRemote = repo.addNote(account.getId(), new Note(null, Calendar.getInstance(), "Fancy Title", "MyContent", "Samples", false, "123"));
final Note createdNoteFromRemote = repo.addNote(account.getId(), new Note(null, Calendar.getInstance(), "Fancy Title", "MyContent", "Samples", false, "123"));
assertEquals(VOID, createdNoteFromRemote.getStatus());
assertEquals("MyContent", createdNoteFromRemote.getExcerpt());
}
@ -210,8 +210,8 @@ public class NotesRepositoryTest {
@Test
public void moveNoteToAnotherAccount() throws InterruptedException {
final var repoSpy = spy(repo);
final var noteToMove = repoSpy.getNoteById(1);
final NotesRepository repoSpy = spy(repo);
final Note noteToMove = repoSpy.getNoteById(1);
assertEquals(VOID, noteToMove.getStatus());
assertEquals(3, repoSpy.getLocalModifiedNotes(secondAccount.getId()).size());
@ -219,7 +219,7 @@ public class NotesRepositoryTest {
doNothing().when(repoSpy).deleteNoteAndSync(any(), anyLong());
doNothing().when(repoSpy).scheduleSync(any(), anyBoolean());
final var movedNote = getOrAwaitValue(repoSpy.moveNoteToAnotherAccount(secondAccount, noteToMove));
final Note movedNote = getOrAwaitValue(repoSpy.moveNoteToAnotherAccount(secondAccount, noteToMove));
assertEquals(4, repoSpy.getLocalModifiedNotes(secondAccount.getId()).size());
assertEquals("美好的一天", movedNote.getTitle());
@ -261,7 +261,7 @@ public class NotesRepositoryTest {
@Test
public void updateDisplayName() {
final var account = db.getAccountDao().getAccountById(db.getAccountDao().insert(new Account("https://äöüß.example.com", "彼得", "彼得@äöüß.example.com", null, new Capabilities())));
final Account account = db.getAccountDao().getAccountById(db.getAccountDao().insert(new Account("https://äöüß.example.com", "彼得", "彼得@äöüß.example.com", null, new Capabilities())));
assertEquals("Should read userName in favor of displayName if displayName is NULL", "彼得", account.getDisplayName());
repo.updateDisplayName(account.getId(), "");

View file

@ -28,9 +28,9 @@ public class NotesTestingUtil {
* @see <a href="https://gist.github.com/JoseAlcerreca/1e9ee05dcdd6a6a6fa1cbfc125559bba">Source</a>
*/
public static <T> T getOrAwaitValue(final LiveData<T> liveData) throws InterruptedException {
final var data = new Object[1];
final var latch = new CountDownLatch(1);
var observer = new Observer<T>() {
final Object[] data = new Object[1];
final CountDownLatch latch = new CountDownLatch(1);
Observer<T> observer = new Observer<T>() {
@Override
public void onChanged(@Nullable T o) {
data[0] = o;
@ -53,7 +53,7 @@ public class NotesTestingUtil {
* @param ssoAccount this account will be added
*/
public static void mockSingleSignOn(@NonNull SingleSignOnAccount ssoAccount) throws IOException {
final var sharedPrefs = ApplicationProvider.getApplicationContext().getSharedPreferences("TEMP_SHARED_PREFS_" + currentLong++, Context.MODE_PRIVATE);
final SharedPreferences sharedPrefs = ApplicationProvider.getApplicationContext().getSharedPreferences("TEMP_SHARED_PREFS_" + currentLong++, Context.MODE_PRIVATE);
sharedPrefs.edit().putString("PREF_ACCOUNT_STRING" + ssoAccount.name, SingleSignOnAccount.toString(ssoAccount)).commit();
AccountImporter.setSharedPreferences(sharedPrefs);
}

View file

@ -38,7 +38,7 @@ public class CapabilitiesDeserializerTest {
" }" +
" }" +
"}";
final var capabilities = deserializer.deserialize(JsonParser.parseString(response), null, null);
final Capabilities capabilities = deserializer.deserialize(JsonParser.parseString(response), null, null);
assertNull(capabilities.getETag());
assertNull(capabilities.getApiVersion());
assertEquals(Color.parseColor("#1E4164"), capabilities.getColor());
@ -71,7 +71,7 @@ public class CapabilitiesDeserializerTest {
" }" +
" }" +
"}";
final var capabilities = deserializer.deserialize(JsonParser.parseString(response), null, null);
final Capabilities capabilities = deserializer.deserialize(JsonParser.parseString(response), null, null);
assertNull(capabilities.getETag());
assertEquals("[\"0.2\",\"1.1\"]", capabilities.getApiVersion());
assertEquals(Color.parseColor("#1E4164"), capabilities.getColor());
@ -104,7 +104,7 @@ public class CapabilitiesDeserializerTest {
" }" +
" }" +
"}";
final var capabilities = deserializer.deserialize(JsonParser.parseString(response), null, null);
final Capabilities capabilities = deserializer.deserialize(JsonParser.parseString(response), null, null);
assertNull(capabilities.getETag());
assertEquals("\"1.0\"", capabilities.getApiVersion());
assertEquals(Color.parseColor("#1E4164"), capabilities.getColor());
@ -300,7 +300,7 @@ public class CapabilitiesDeserializerTest {
" }" +
" }" +
"}";
final var capabilities = deserializer.deserialize(JsonParser.parseString(response), null, null);
final Capabilities capabilities = deserializer.deserialize(JsonParser.parseString(response), null, null);
assertNull(capabilities.getETag());
assertEquals("[\"0.2\",\"1.1\"]", capabilities.getApiVersion());
assertEquals(Color.parseColor("#44616B"), capabilities.getColor());

View file

@ -20,11 +20,11 @@ import static org.junit.Assert.assertTrue;
public class NotesColorUtilTest {
@Test
public void testContrastRatioIsSufficient() {
final var sufficientContrastColorPairs = new ArrayList<Pair<Integer, Integer>>();
final List<Pair<Integer, Integer>> sufficientContrastColorPairs = new ArrayList<>();
sufficientContrastColorPairs.add(new Pair<>(Color.BLACK, Color.WHITE));
sufficientContrastColorPairs.add(new Pair<>(Color.WHITE, Color.parseColor("#0082C9")));
for (final var colorPair : sufficientContrastColorPairs) {
for (Pair<Integer, Integer> colorPair : sufficientContrastColorPairs) {
assert colorPair.first != null;
assert colorPair.second != null;
assertTrue(
@ -33,11 +33,11 @@ public class NotesColorUtilTest {
);
}
final var insufficientContrastColorPairs = new ArrayList<Pair<Integer, Integer>>();
final List<Pair<Integer, Integer>> insufficientContrastColorPairs = new ArrayList<>();
insufficientContrastColorPairs.add(new Pair<>(Color.WHITE, Color.WHITE));
insufficientContrastColorPairs.add(new Pair<>(Color.BLACK, Color.BLACK));
for (final var colorPair : insufficientContrastColorPairs) {
for (Pair<Integer, Integer> colorPair : insufficientContrastColorPairs) {
assert colorPair.first != null;
assert colorPair.second != null;
assertFalse(

View file

@ -10,25 +10,25 @@ public class NavigationCategorySortingMethodTest {
@Test
public void getId() {
final var csm0 = CategorySortingMethod.SORT_MODIFIED_DESC;
CategorySortingMethod csm0 = CategorySortingMethod.SORT_MODIFIED_DESC;
assertEquals(0, csm0.getId());
final var csm1 = CategorySortingMethod.SORT_LEXICOGRAPHICAL_ASC;
CategorySortingMethod csm1 = CategorySortingMethod.SORT_LEXICOGRAPHICAL_ASC;
assertEquals(1, csm1.getId());
}
@Test
public void getTitle() {
final var csm0 = CategorySortingMethod.SORT_MODIFIED_DESC;
CategorySortingMethod csm0 = CategorySortingMethod.SORT_MODIFIED_DESC;
assertEquals("MODIFIED DESC", csm0.getTitle());
final var csm1 = CategorySortingMethod.SORT_LEXICOGRAPHICAL_ASC;
CategorySortingMethod csm1 = CategorySortingMethod.SORT_LEXICOGRAPHICAL_ASC;
assertEquals("TITLE COLLATE NOCASE ASC", csm1.getTitle());
}
@Test
public void findById() {
final var csm0 = CategorySortingMethod.SORT_MODIFIED_DESC;
CategorySortingMethod csm0 = CategorySortingMethod.SORT_MODIFIED_DESC;
assertEquals(csm0, CategorySortingMethod.findById(0));
final var csm1 = CategorySortingMethod.SORT_LEXICOGRAPHICAL_ASC;
CategorySortingMethod csm1 = CategorySortingMethod.SORT_LEXICOGRAPHICAL_ASC;
assertEquals(csm1, CategorySortingMethod.findById(1));
}
}

View file

@ -81,10 +81,10 @@ public class MarkdownUtil {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
return input;
}
final var ssb = new SpannableStringBuilder(input);
final var originalQuoteSpans = ssb.getSpans(0, ssb.length(), QuoteSpan.class);
final SpannableStringBuilder ssb = new SpannableStringBuilder(input);
final QuoteSpan[] originalQuoteSpans = ssb.getSpans(0, ssb.length(), QuoteSpan.class);
@ColorInt final int colorBlockQuote = ContextCompat.getColor(context, R.color.block_quote);
for (final var originalQuoteSpan : originalQuoteSpans) {
for (QuoteSpan originalQuoteSpan : originalQuoteSpans) {
final int start = ssb.getSpanStart(originalQuoteSpan);
final int end = ssb.getSpanEnd(originalQuoteSpan);
ssb.removeSpan(originalQuoteSpan);
@ -96,7 +96,7 @@ public class MarkdownUtil {
@NonNull
public static String replaceCheckboxesWithEmojis(@NonNull String content) {
return runForEachCheckbox(content, (line) -> {
for (final var listType : EListType.values()) {
for (EListType listType : EListType.values()) {
if (CHECKBOX_CHECKED_EMOJI.isPresent()) {
line = line.replace(listType.checkboxChecked, CHECKBOX_CHECKED_EMOJI.get());
line = line.replace(listType.checkboxCheckedUpperCase, CHECKBOX_CHECKED_EMOJI.get());
@ -124,7 +124,7 @@ public class MarkdownUtil {
? new String[]{"", "", "☑️", "✔️"}
: new String[]{"", "", "\uD83D\uDD32", "☐️"};
}
final var paint = new Paint();
final Paint paint = new Paint();
for (String emoji : emojis) {
if (paint.hasGlyph(emoji)) {
return Optional.of(emoji);
@ -143,7 +143,7 @@ public class MarkdownUtil {
boolean isInFencedCodeBlock = false;
int fencedCodeBlockSigns = 0;
for (int i = 0; i < lines.length; i++) {
final var matcher = PATTERN_CODE_FENCE.matcher(lines[i]);
final Matcher matcher = PATTERN_CODE_FENCE.matcher(lines[i]);
if (matcher.find()) {
final String fence = matcher.group(1);
if (fence != null) {
@ -187,19 +187,19 @@ public class MarkdownUtil {
public static Optional<String> getListItemIfIsEmpty(@NonNull String line) {
final String trimmedLine = line.trim();
// TODO use Java 11 String::repeat
final var builder = new StringBuilder();
final StringBuilder builder = new StringBuilder();
final int indention = line.indexOf(trimmedLine);
for (int i = 0; i < indention; i++) {
builder.append(" ");
}
for (final var listType : EListType.values()) {
for (EListType listType : EListType.values()) {
if (trimmedLine.equals(listType.checkboxUnchecked)) {
return Optional.of(builder.append(listType.checkboxUncheckedWithTrailingSpace).toString());
} else if (trimmedLine.equals(listType.listSymbol)) {
return Optional.of(builder.append(listType.listSymbolWithTrailingSpace).toString());
}
}
final var matcher = PATTERN_ORDERED_LIST_ITEM_EMPTY.matcher(line.substring(indention));
final Matcher matcher = PATTERN_ORDERED_LIST_ITEM_EMPTY.matcher(line.substring(indention));
if (matcher.find()) {
return Optional.of(builder.append(matcher.group()).toString());
}
@ -212,7 +212,7 @@ public class MarkdownUtil {
boolean isInFencedCodeBlock = false;
int fencedCodeBlockSigns = 0;
for (int i = 0; i < lines.length; i++) {
final var matcher = PATTERN_CODE_FENCE.matcher(lines[i]);
final Matcher matcher = PATTERN_CODE_FENCE.matcher(lines[i]);
if (matcher.find()) {
final String fence = matcher.group(1);
if (fence != null) {
@ -263,7 +263,7 @@ public class MarkdownUtil {
* @return the number of the ordered list item if the line is an ordered list, otherwise -1.
*/
public static Optional<Integer> getOrderedListNumber(@NonNull String line) {
final var matcher = PATTERN_ORDERED_LIST_ITEM.matcher(line);
final Matcher matcher = PATTERN_ORDERED_LIST_ITEM.matcher(line);
if (matcher.find()) {
final String groupNumber = matcher.group(1);
if (groupNumber != null) {
@ -293,7 +293,7 @@ public class MarkdownUtil {
// handle special case: italic (that damn thing will match like ANYTHING (regarding bold / bold+italic)....)
final boolean isItalic = punctuation.length() == 1 && punctuation.charAt(0) == '*';
if (isItalic) {
final var result = handleItalicEdgeCase(editable, initialString, selectionStart, selectionEnd);
final Optional<Integer> result = handleItalicEdgeCase(editable, initialString, selectionStart, selectionEnd);
// The result is only present if this actually was an edge case
if (result.isPresent()) {
return result.get();
@ -307,7 +307,7 @@ public class MarkdownUtil {
// in this case let's make optional asterisks around it, so it wont match anything between two (bold+italic)s
? "\\*?\\*?" + punctuationRex + wildcardRex + punctuationRex + "\\*?\\*?"
: punctuationRex + wildcardRex + punctuationRex;
final var searchPattern = Pattern.compile(pattern);
final Pattern searchPattern = Pattern.compile(pattern);
int relevantStart = selectionStart - 2;
relevantStart = Math.max(relevantStart, 0);
int relevantEnd = selectionEnd + 2;
@ -319,7 +319,7 @@ public class MarkdownUtil {
// this resets the matcher, while keeping the required region
matcher.region(relevantStart, relevantEnd);
final int punctuationLength = punctuation.length();
final var startEnd = new LinkedList<Pair<Integer, Integer>>();
final List<Pair<Integer, Integer>> startEnd = new LinkedList<>();
int removedCount = 0;
while (matcher.find()) {
startEnd.add(new Pair<>(matcher.start(), matcher.end()));
@ -327,7 +327,7 @@ public class MarkdownUtil {
}
// start from the end
Collections.reverse(startEnd);
for (final var item : startEnd) {
for (Pair<Integer, Integer> item : startEnd) {
deletePunctuation(editable, punctuationLength, item.first, item.second);
}
int offsetAtEnd = 0;
@ -362,9 +362,9 @@ public class MarkdownUtil {
@NonNull
private static Optional<Integer> handleItalicEdgeCase(Editable editable, String editableAsString, int selectionStart, int selectionEnd) {
// look if selection is bold, this is the only edge case afaik
final var searchPattern = Pattern.compile("(^|[^*])" + PATTERN_QUOTE_BOLD_PUNCTUATION + "([^*])*" + PATTERN_QUOTE_BOLD_PUNCTUATION + "([^*]|$)");
final Pattern searchPattern = Pattern.compile("(^|[^*])" + PATTERN_QUOTE_BOLD_PUNCTUATION + "([^*])*" + PATTERN_QUOTE_BOLD_PUNCTUATION + "([^*]|$)");
// look the selection expansion by 1 is intended, so the NOT '*' has a chance to match. we don't want to match ***blah***
final var matcher = searchPattern.matcher(editableAsString)
final Matcher matcher = searchPattern.matcher(editableAsString)
.region(Math.max(selectionStart - 1, 0), Math.min(selectionEnd + 1, editableAsString.length()));
if (matcher.find()) {
return Optional.of(insertPunctuation(editable, selectionStart, selectionEnd, "*"));
@ -454,7 +454,7 @@ public class MarkdownUtil {
public static boolean selectionIsInLink(@NonNull CharSequence text, int start, int end) {
final var matcher = PATTERN_MARKDOWN_LINK.matcher(text);
final Matcher matcher = PATTERN_MARKDOWN_LINK.matcher(text);
while (matcher.find()) {
if ((start >= matcher.start() && start < matcher.end()) || (end > matcher.start() && end <= matcher.end())) {
return true;
@ -465,7 +465,7 @@ public class MarkdownUtil {
public static void searchAndColor(@NonNull Spannable editable, @Nullable CharSequence searchText, @Nullable Integer current, @ColorInt int mainColor, @ColorInt int highlightColor, boolean darkTheme) {
if (searchText != null) {
final var m = Pattern
final Matcher m = Pattern
.compile(searchText.toString(), Pattern.CASE_INSENSITIVE | Pattern.LITERAL)
.matcher(editable);
@ -483,7 +483,7 @@ public class MarkdownUtil {
* Removes all spans of {@param spanType} from {@param spannable}.
*/
public static <T> void removeSpans(@NonNull Spannable spannable, @SuppressWarnings("SameParameterValue") Class<T> spanType) {
for (final var span : spannable.getSpans(0, spannable.length(), spanType)) {
for (T span : spannable.getSpans(0, spannable.length(), spanType)) {
spannable.removeSpan(span);
}
}
@ -493,12 +493,12 @@ public class MarkdownUtil {
* Otherwise it will create a new {@link SpannableString} from the content, set this as new content of the {@param textView} and return it.
*/
public static Spannable getContentAsSpannable(@NonNull TextView textView) {
final var content = textView.getText();
final CharSequence content = textView.getText();
if (content.getClass() == SpannableString.class || content instanceof Spannable) {
return (Spannable) content;
} else {
Log.w(TAG, "Expected " + TextView.class.getSimpleName() + " content to be of type " + Spannable.class.getSimpleName() + ", but was of type " + content.getClass() + ". Search highlighting will be not performant.");
final var spannableContent = new SpannableString(content);
final Spannable spannableContent = new SpannableString(content);
textView.setText(spannableContent, TextView.BufferType.SPANNABLE);
return spannableContent;
}

View file

@ -35,16 +35,16 @@ public class MentionUtil {
* @param target target {@link TextView}
*/
public static void setupMentions(@NonNull SingleSignOnAccount account, @NonNull Map<String, String> mentions, @NonNull TextView target) {
final var context = target.getContext();
final Context context = target.getContext();
// Step 1
// Add avatar icons and display names
final var messageBuilder = replaceAtMentionsWithImagePlaceholderAndDisplayName(context, mentions, target.getText());
final SpannableStringBuilder messageBuilder = replaceAtMentionsWithImagePlaceholderAndDisplayName(context, mentions, target.getText());
// Step 2
// Replace avatar icons with real avatars
final var list = messageBuilder.getSpans(0, messageBuilder.length(), MentionSpan.class);
for (final var span : list) {
final MentionSpan[] list = messageBuilder.getSpans(0, messageBuilder.length(), MentionSpan.class);
for (MentionSpan span : list) {
final int spanStart = messageBuilder.getSpanStart(span);
final int spanEnd = messageBuilder.getSpanEnd(span);
Glide.with(context)
@ -69,7 +69,7 @@ public class MentionUtil {
}
private static SpannableStringBuilder replaceAtMentionsWithImagePlaceholderAndDisplayName(@NonNull Context context, @NonNull Map<String, String> mentions, @NonNull CharSequence text) {
final var messageBuilder = new SpannableStringBuilder(text);
final SpannableStringBuilder messageBuilder = new SpannableStringBuilder(text);
for (String userId : mentions.keySet()) {
final String mentionId = "@" + userId;
final String mentionDisplayName = " " + mentions.get(userId);

View file

@ -57,8 +57,8 @@ public class MarkwonMarkdownEditor extends AppCompatEditText implements Markdown
public MarkwonMarkdownEditor(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
final var markwon = createMarkwonBuilder(context).build();
final var editor = createMarkwonEditorBuilder(markwon).build();
final Markwon markwon = createMarkwonBuilder(context).build();
final MarkwonEditor editor = createMarkwonEditorBuilder(markwon).build();
combinedWatcher = new CombinedTextWatcher(editor, this);
addTextChangedListener(combinedWatcher);
@ -91,7 +91,7 @@ public class MarkwonMarkdownEditor extends AppCompatEditText implements Markdown
@Override
public void setSearchColor(@ColorInt int color) {
final var searchHighlightTextWatcher = combinedWatcher.get(SearchHighlightTextWatcher.class);
final SearchHighlightTextWatcher searchHighlightTextWatcher = combinedWatcher.get(SearchHighlightTextWatcher.class);
if (searchHighlightTextWatcher == null) {
Log.w(TAG, SearchHighlightTextWatcher.class.getSimpleName() + " is not a registered " + TextWatcher.class.getSimpleName());
} else {
@ -101,7 +101,7 @@ public class MarkwonMarkdownEditor extends AppCompatEditText implements Markdown
@Override
public void setSearchText(@Nullable CharSequence searchText, @Nullable Integer current) {
final var searchHighlightTextWatcher = combinedWatcher.get(SearchHighlightTextWatcher.class);
final SearchHighlightTextWatcher searchHighlightTextWatcher = combinedWatcher.get(SearchHighlightTextWatcher.class);
if (searchHighlightTextWatcher == null) {
Log.w(TAG, SearchHighlightTextWatcher.class.getSimpleName() + " is not a registered " + TextWatcher.class.getSimpleName());
} else {

Some files were not shown because too many files have changed in this diff Show more