From 3afd9b903c1ea72806dff8933e58adeb06bfe859 Mon Sep 17 00:00:00 2001 From: leinadsened <84383252+leinadsened@users.noreply.github.com> Date: Mon, 9 Oct 2023 23:07:40 +0200 Subject: [PATCH] Allow creating a counter without specifying a name Resolves #110. --- .../counter/view/dialogs/AddDialog.java | 36 ++++++++++++++----- 1 file changed, 27 insertions(+), 9 deletions(-) diff --git a/app/src/main/java/me/tsukanov/counter/view/dialogs/AddDialog.java b/app/src/main/java/me/tsukanov/counter/view/dialogs/AddDialog.java index c1dc7548..36b10117 100644 --- a/app/src/main/java/me/tsukanov/counter/view/dialogs/AddDialog.java +++ b/app/src/main/java/me/tsukanov/counter/view/dialogs/AddDialog.java @@ -11,7 +11,12 @@ import android.widget.Toast; import androidx.annotation.NonNull; import androidx.fragment.app.DialogFragment; + + import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; + import me.tsukanov.counter.CounterApplication; import me.tsukanov.counter.R; import me.tsukanov.counter.activities.MainActivity; @@ -46,15 +51,7 @@ public Dialog onCreateDialog(Bundle savedInstanceState) { .setPositiveButton( getResources().getText(R.string.dialog_button_add), (dialog1, which) -> { - final String name = nameInput.getText().toString().trim(); - if (name.isEmpty()) { - Toast.makeText( - getActivity(), - getResources().getText(R.string.toast_no_name_message), - Toast.LENGTH_SHORT) - .show(); - return; - } + String name = checkCounterName(nameInput.getText().toString().trim()); int value; final String valueInputContents = valueInput.getText().toString().trim(); @@ -94,4 +91,25 @@ private void addCounter(@NonNull final IntegerCounter counter) { CounterApplication.getComponent().localStorage().write(counter); new BroadcastHelper(requireContext()).sendSelectCounterBroadcast(counter.getName()); } + + private String checkCounterName(String name){ + if (name.isEmpty()) { + int counterCount; + String genericName = getString(R.string.app_name) + " "; + boolean runAgain = true; + Set counterNames; + counterNames = CounterApplication.getComponent().localStorage().readAll(false).stream().map(IntegerCounter::getName).collect(Collectors.toSet()); + counterCount = counterNames.size() + 1; + while (runAgain) { + runAgain = false; + if (counterNames.contains(genericName + counterCount)){ + runAgain = true; + counterCount++; + } + } + name = genericName + counterCount; + } + return name; + } + }