简体   繁体   English

在 SharedPreferences Between Activity 中保存和检索 http 响应列表 object

[英]Save and Retrieve http Response List object in SharedPreferences Between Activities

I am having some trouble understanding sharedPreferences and how to save and retrieve a list of objects between different activities.我在理解 sharedPreferences 以及如何在不同活动之间保存和检索对象列表时遇到了一些麻烦。 I followed the steps from multiple other questions, I will list them below,but I keep running into a mismatch in conversion no matter how I change it.我遵循了其他多个问题的步骤,我将在下面列出它们,但是无论我如何更改它,我都会遇到转换不匹配的问题。 I do get access to the list saved in sharedPreference but I am unable to convert it back to the object list.我确实可以访问保存在 sharedPreference 中的列表,但我无法将其转换回 object 列表。 My main activity code that does an http request and saves the response object list to sharedpreferences and finally starts the next intent is:我执行 http 请求并将响应 object 列表保存到 sharedpreferences 并最终开始下一个意图的主要活动代码是:

    private fun getItems(authResponse: AuthResponseModel) {
            val url = "/Api/items";
    
            val formBody = FormBody.Builder()
                    .add("token", authResponse.cloverToken.toString())
                    .build()
    
            // creating request
            var request = Request.Builder()
                    .addHeader("Authorization", "Bearer " + authResponse.token.toString())
                    .url(url)
                    .post(formBody)
                    .build()
    
            var client = OkHttpClient();
            runOnUiThread{
    
                client.newCall(request).enqueue(object : Callback {
                    override fun onResponse(call: Call, response: Response) {
    
                        var response = response.body?.string();
    
                        //save auth token
                        val gson = Gson()
    
                        System.out.println("clover 2: " + gson.toJson(response));
                        val preferences = getSharedPreferences("items", MODE_PRIVATE)
                        preferences.edit().putString("items", gson.toJson(response)).commit()
    
                        val intent = Intent(this@MainActivity, OrderActivity::class.java)
                        intent.putExtra("SHOW_WELCOME", true)
                        startActivity(intent)
                        finish()
                    }
    
                })
            }
        }

How I retrieve the data in the other activity is below:我如何在其他活动中检索数据如下:

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_order)
        initialize()
        var arrayItems: List<ItemModel>;


        initPermissions()
        val itemList = getSharedPreferences("items", MODE_PRIVATE)
        val gson = Gson()
        if (itemList != null) {
            val type = object : TypeToken<List<ItemModel>>() {}.type
            arrayItems = gson.fromJson(gson.toJson(itemList), type)
            println("here items " +arrayItems.toString())

        }

        //this.items = (itemList);

    }

I need the items to be a list of ItemModel objects that are returned from sharedpreferences.我需要这些项目是从 sharedpreferences 返回的 ItemModel 对象的列表。 My main errors I am getting are with the conversions.我得到的主要错误是转换。 Let me know if any further information is needed and I will update my question.让我知道是否需要任何进一步的信息,我会更新我的问题。

The ItemModel code is: ItemModel 代码是:

package com.robotemi.sdk.dinengo.models;

import java.util.ArrayList;

public class ItemModel {
        private String id;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    private String name;
        private String alternateName;
        private String code;
        private String priceType;
        private String unitName;
        private boolean sku;
        private boolean isRevenue;
        private boolean available;
        private boolean autoManage;
        private boolean defaultTaxRates;
        private double price;
        private double cost;
        private double stockCount;
        private int modifiedTime;

        public ItemModel() {}
        public ItemModel(ItemModel itemModel) {
            this.id = itemModel.id;
            this.name = itemModel.name;
            this.alternateName = itemModel.alternateName;
            this.code = itemModel.code;
            this.priceType = itemModel.priceType;
            this.unitName = itemModel.unitName;
            this.sku = itemModel.sku;
            this.isRevenue = itemModel.isRevenue;
            this.available = itemModel.available;

            this.autoManage = itemModel.autoManage;
            this.defaultTaxRates = itemModel.defaultTaxRates;
            this.price = itemModel.price;
            this.cost = itemModel.cost;
            this.stockCount = itemModel.stockCount;
            this.modifiedTime = itemModel.modifiedTime;
        }

        public ArrayList<ItemModel> ItemModel(ItemModel[] itemModel) {
            ArrayList items = new ArrayList<ItemModel>();
            for(int i = 0; i <itemModel.length ; i++ ){
                ItemModel item = new ItemModel();
                item.id = itemModel[i].id;
                item.name = itemModel[i].name;
                item.alternateName = itemModel[i].alternateName;
                item.code = itemModel[i].code;
                item.priceType = itemModel[i].priceType;
                item.unitName = itemModel[i].unitName;
                item.sku = itemModel[i].sku;
                item.isRevenue = itemModel[i].isRevenue;
                item.available = itemModel[i].available;
                item.autoManage = itemModel[i].autoManage;
                item.defaultTaxRates = itemModel[i].defaultTaxRates;
                item.price = itemModel[i].price;
                item.cost = itemModel[i].cost;
                item.stockCount = itemModel[i].stockCount;
                item.modifiedTime = itemModel[i].modifiedTime;
                items.add(item);
            }

            return items;

        }

}

The list of other questions I looked into but no luck:我调查过但没有运气的其他问题列表:

How to save List<Object> to SharedPreferences? 如何将 List<Object> 保存到 SharedPreferences?

How to save List<Object> to SharedPreferences? 如何将 List<Object> 保存到 SharedPreferences?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM