Как сохранить массив List в SharedPreference?
вот моя переменная и лист
val basket = ArrayList<ProductInBasket>()
я не знаю как сохранить этот лист в SharedPreference
и заполняю массив при клике добавить в корзину
app.basket.add(ProductInBasket(app.currentProduct!!))
//аpp -класс
class MyApp: Application() {
var currentProduct: Product?=null;
val basket = ArrayList<ProductInBasket>()
}
//класс товары в корзине
class ProductInBasket {
var product: Product
var quantity: Int = 1
constructor(product: Product){
this.product = product
}
}
//класс продукты
data class Product(
val id: Int,
val Title: String,
val productTypeID: Int,
val articleNumber: String,
val description: String?,
val image: String,
val minCost: String,
val Quantity:Int,
)
Окно где выводиться детальная информация о товаре ,а также заполняется массив при клике добавить в корзину
class DetaileInfo : AppCompatActivity() {
private lateinit var app: MyApp
private lateinit var testV: TextView
private lateinit var conten: TextView
private lateinit var im: ImageView
private lateinit var pric: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_detaile_info)
app = applicationContext as MyApp
val product = app.currentProduct;
if (product == null) {
Toast.makeText(this, "Что-то пошло не так!.", Toast.LENGTH_LONG).show()
finish();
return;
} else {
findViewById<TextView>(R.id.title).setText(product.Title)
//findViewById<TextView>(R.id.article).setText(product.articleNumber)
findViewById<TextView>(R.id.priceProd).setText("Цена: ${product.minCost.toString()} руб.")
findViewById<TextView>(R.id.priceProd1).setText("Цена: ${product.minCost.toString()}P")
findViewById<TextView>(R.id.Quantity).setText("В наличии: ${product.Quantity.toString()} шт.")
findViewById<TextView>(R.id.description).setText(product.description)
}
private fun sssd() {
startActivity(Intent(this, korzina::class.java))
}
fun ADD1(view: View) {
var found=false
for (i in 0 until app.basket.size) {
val item = app.basket[i]
if (item.product.id == app.currentProduct!!.id) {
found=true
item.quantity++
break
}
}
if (!found)
app.basket.add(ProductInBasket(app.currentProduct!!))
val fab: View = findViewById(R.id.btn1)
fab.visibility = View.GONE;
val fab1: View = findViewById(R.id.btn2)
fab1.visibility = View.VISIBLE;
val fab3: View = findViewById(R.id.Quantityy)
fab3.visibility = View.VISIBLE;
}
fun sss(view: View) {
// app.currentProduct
startActivity(Intent(this, korzina::class.java))
}
fun ADDDDplus(view: View) {
var found=false
for (i in 0 until app.basket.size) {
val item = app.basket[i]
if (item.product.id == app.currentProduct!!.id) {
found=true
item.quantity++
break
}
}
if (!found)
app.basket.add(ProductInBasket(app.currentProduct!!))
val toast1 = Toast.makeText(
applicationContext,
"Добавлено", Toast.LENGTH_SHORT
)
toast1.show()
}
fun saveArrayList(list: java.util.ArrayList<String?>?, key: String?) {
val prefs: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity)
val editor: SharedPreferences.Editor = prefs.edit()
val gson = Gson()
val json: String = gson.toJson(list)
editor.putString(key, json)
editor.apply()
}
}
Ответы (1 шт):
sharedPreferences хранят типы String, Int, Boolean, Long, Float
Если вам приниципиально схранить в sharedPreferences список, то одним из вариантов будет преобразовать объект в json строку и сохранять его ввиде строки
import android.content.Context
import android.content.SharedPreferences
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import dagger.android.AndroidInjection
import ru.sarawan.android.databinding.ActivityMainBinding
import ru.sarawan.android.model.data.AppState
import ru.sarawan.android.model.data.ProductsItem
class ExampleActivity : AppCompatActivity() {
private companion object {
//ключ по которому мы получаем и под которым сохраняем данные
const val SHARED_KEY = "SHARED_KEY"
}
var list = ArrayList<ProductsItem>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initListData()
//получили список из sharedPref
val newList = getArrayList()
//добавили полученный список newList в список list, можно list = newList
list.addAll(newList)
}
private fun initListData() {
//добавили данные в список
list.add(ProductsItem(quantity = 1))
list.add(ProductsItem(quantity = 2))
list.add(ProductsItem(quantity = 3))
list.add(ProductsItem(quantity = 4))
list.add(ProductsItem(quantity = 5))
list.add(ProductsItem(quantity = 6))
list.add(ProductsItem(quantity = 7))
//сохранили
saveArrayList(list)
}
private fun saveArrayList(list: ArrayList<ProductsItem>) {
val prefs: SharedPreferences = this.getPreferences(Context.MODE_PRIVATE)
val editor: SharedPreferences.Editor = prefs.edit()
val gson = Gson()
val json: String = gson.toJson(list)
editor.putString(SHARED_KEY, json)
editor.apply()
}
private fun getArrayList() : ArrayList<ProductsItem>{
val prefs: SharedPreferences = this.getPreferences(Context.MODE_PRIVATE)
val gson = Gson()
val json = prefs.getString(SHARED_KEY, null);
val type = object : TypeToken<ArrayList<ProductsItem>>() {}.type
return gson.fromJson(json, type);
}
}
Для использования библиотеки Gson надо в build.gradle подключить зависимость в блоке dependencies implementation 'com.google.code.gson:gson:2.8.6', а после синхронизироваться
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 29
defaultConfig {
applicationId "ru.ifr0z.fabuserlocation.example"
minSdkVersion 21
targetSdkVersion 29
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
//------------------------------------------------
implementation 'com.google.code.gson:gson:2.8.6'
//------------------------------------------------
}
Но для списков обычно используют локальную базу данных, а не sharedPreferences, почитайте о sqllite и room в Android и используйте их для хранения полей объектов