Skip to content

Commit 81b7e27

Browse files
committed
Add label history
Save and display recently printed labels and allow easily selecting one to print again.
1 parent cfb44bc commit 81b7e27

File tree

3 files changed

+272
-47
lines changed

3 files changed

+272
-47
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
package com.hestonliebowitz.labelmaker
2+
3+
import android.content.Context
4+
5+
const val HISTORY_DELIMITER = "~"
6+
const val MAX_HISTORY_ITEMS = 10
7+
8+
class HistoryService(private val ctx: Context) {
9+
private val _items : MutableList<String> = emptyList<String>().toMutableList()
10+
11+
fun getAll(): List<String> {
12+
_items.clear()
13+
val prefs = ctx.getSharedPreferences(DEFAULT, Context.MODE_PRIVATE)
14+
val history = prefs.getString(
15+
ctx.getString(R.string.pref_history),
16+
""
17+
)
18+
if (!history.isNullOrEmpty()) {
19+
_items.addAll(history.split(HISTORY_DELIMITER))
20+
}
21+
return _items.toList()
22+
}
23+
24+
fun save(value: String) {
25+
// If item already exists, remove it
26+
val idx = _items.indexOf(value)
27+
if (idx > -1) {
28+
_items.removeAt(idx)
29+
}
30+
31+
// Add item to front of list
32+
_items.add(0, value)
33+
34+
// Ensure list of favorites never exceeds MAX_HISTORY_ITEMS in length
35+
if (_items.size > MAX_HISTORY_ITEMS) {
36+
_items.subList(MAX_HISTORY_ITEMS, _items.size).clear()
37+
}
38+
39+
// Serialize list into a string and save it
40+
val newItems = _items.joinToString(HISTORY_DELIMITER)
41+
val prefs = ctx.getSharedPreferences(DEFAULT, Context.MODE_PRIVATE)
42+
val editor = prefs.edit()
43+
editor.putString(
44+
ctx.getString(R.string.pref_history),
45+
newItems
46+
)
47+
editor.apply()
48+
}
49+
50+
fun deleteAll() {
51+
val prefs = ctx.getSharedPreferences(DEFAULT, Context.MODE_PRIVATE)
52+
val editor = prefs.edit()
53+
editor.putString(
54+
ctx.getString(R.string.pref_history),
55+
""
56+
)
57+
editor.apply()
58+
}
59+
}

0 commit comments

Comments
 (0)