Files
financial-viewer/app/src/main/java/com/financialviewer/utils/SharedPreferencesHelper.kt

94 lines
2.9 KiB
Kotlin

package com.financialviewer.utils
import android.content.Context
import android.util.Log
import java.io.File
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
class SharedPreferencesHelper(
private val context: Context
) {
private val fileName = "app_prefs"
private val sharedPreferences = context.getSharedPreferences(fileName, Context.MODE_PRIVATE)
private fun saveData(key: String, value: String) {
val editor = sharedPreferences.edit()
editor.putString(key, value)
editor.apply()
}
fun saveDefaultYear(value: Int) {
val editor = sharedPreferences.edit()
editor.putInt("default_year_of_bank_Transaction", value)
editor.apply()
}
fun saveAuthStatus(key: String, value: Boolean) {
val editor = sharedPreferences.edit()
editor.putBoolean(key, value)
editor.apply()
}
fun saveCurrentUpdateTimeToSharedPreferences() {
val currentDateTime = LocalDateTime.now()
val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
val formattedDateTime = currentDateTime.format(formatter)
saveData("bank_transaction_last_Update_date", formattedDateTime)
}
fun saveCalculateFixedCostTime() {
val currentDateTime = LocalDateTime.now()
val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
val formattedDateTime = currentDateTime.format(formatter)
saveData("calculate_fixed_cost_time", formattedDateTime)
}
private fun readData(key: String): String {
return sharedPreferences.getString(key, "") ?: ""
}
fun readDefaultYear(defaultValue: Int): Int {
return sharedPreferences.getInt("default_year_of_bank_Transaction", defaultValue)
}
fun readLastUpdateTimeToSharedPreferences(): String {
return readData("bank_transaction_last_Update_date")
}
fun readCalculateFixedCostTime(): String {
return readData("calculate_fixed_cost_time")
}
fun getAllSharedPreferences(): MutableList<String> {
val allEntries: Map<String, *> = sharedPreferences.all
for ((key, value) in allEntries) {
Log.d("SharedPreferences", "$key: $value")
}
return sharedPreferences.all.keys.toMutableList()
}
fun removeSpecificSharedPreference(key: String) {
val editor = sharedPreferences.edit()
editor.remove(key)
editor.apply() // or editor.commit()
}
fun clearAllSharedPreferences() {
val editor = sharedPreferences.edit()
editor.clear()
editor.apply() // or editor.commit()
}
private fun deleteSharedPreferencesFile(fileName: String) {
val dir = context.filesDir.parentFile
val sharedPrefsFile = File(dir, "shared_prefs/$fileName.xml")
if (sharedPrefsFile.exists()) {
sharedPrefsFile.delete()
}
}
}