在一个单独的类中使用SharedPreference?

huangapple go评论72阅读模式
英文:

SharedPreference in a separate class?

问题

我正在尝试创建一个包含保存和加载对象ArrayList到SharedPreferences的方法的类然而当我尝试加载之前保存的数据时就好像它没有保存过一样我正在使用Google的Gson库来帮助处理

**Instance_Read_Write.java** 

public class Instance_Read_Write {
    public void saveData(Context context, ArrayList<Example> Examples){
        SharedPreferences sharedPreferences = context.getSharedPreferences("instanceKey",Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        Gson gson = new Gson();
        String json = gson.toJson(Examples);
        editor.putString("list", json);
        editor.apply();
    }

    public void loadData(Context context, ArrayList<Example> Examples) {
        SharedPreferences sharedPreferences = context.getSharedPreferences("instanceKey",Context.MODE_PRIVATE);
        Gson gson = new Gson();
        String json = sharedPreferences.getString("list", null);
        Type type = new TypeToken<ArrayList<Example>>() {}.getType();
        Examples = gson.fromJson(json, type);

        if (Examples == null) {
            Examples = new ArrayList<>();
        }
    }
}

这是我如何引用它们的方式。

MainActivity.java

Instance_Read_Write instance_read_write = new Instance_Read_Write();
instance_read_write.loadData(context, Examples);
Examples.add(new Example("test"));

// ...

instance_read_write.saveData(context, Examples);

有办法使这个工作吗?或者也许有更好的方法来做到这一点吗?


<details>
<summary>英文:</summary>

I am attempting to create a class that will contain methods for saving and loading an ArrayList of objects into SharedPreferences. However, when I attempt to load back data I had previously saved. It is as if it has not saved. I am using Googles Gson Libraries to help.

**Instance_Read_Write.java** 

    public class Instance_Read_Write {
        public void saveData(Context context, ArrayList&lt;Example&gt; Examples){
            SharedPreferences sharedPreferences = context.getSharedPreferences(&quot;instanceKey&quot;,Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            Gson gson = new Gson();
            String json = gson.toJson(Examples);
            editor.putString(&quot;list&quot;, json);
            editor.apply();
        }
    
        public void loadData(Context context, ArrayList&lt;Example&gt; Examples) {
            SharedPreferences sharedPreferences = context.getSharedPreferences(&quot;instanceKey&quot;,Context.MODE_PRIVATE);
            Gson gson = new Gson();
            String json = sharedPreferences.getString(&quot;list&quot;, null);
            Type type = new TypeToken&lt;ArrayList&lt;Example&gt;&gt;() {}.getType();
            Examples = gson.fromJson(json, type);
    
            if (Examples == null) {
                Examples = new ArrayList&lt;&gt;();
            }
        }
    
    }

and this is how I am referencing them.

**MainActivity.java** 

    Instance_Read_Write instance_read_write = new Instance_Read_Write();
    instance_read_write.loadData(context,Examples);
    Examples.add(new Example(&quot;test&quot;));
    
        ...
        ...
        ...
    
       instance_read_write.saveData(context,Examples);

Is there a way to make this work? or perhaps a better way to do this?

</details>


# 答案1
**得分**: 0

将"Instead of the Token for the Type, put"翻译为:

用于类型的令牌,替换为

<details>
<summary>英文:</summary>

Instead of the Token for the Type, put

    Examples = gson.fromJson(json, Example.class);

Tell me if it works

</details>



# 答案2
**得分**: 0

这解决了您发布的代码中的一个错误,即在`loadData`方法中处理`Examples`参数的方法。

由于您的`loadData`方法的意图似乎是始终生成一个ArrayList&lt;Example&gt;,因此我建议返回该实例。或者,您可以首先创建一个空的ArrayList&lt;Example&gt;,将其传递进去,然后对其进行操作。

因此,使用返回ArrayList&lt;Example&gt;的方法:

```java
public ArrayList&lt;Example&gt; loadData(Context context) {
    ArrayList&lt;Example&gt; result;
    SharedPreferences sharedPreferences = context.getSharedPreferences("instanceKey", Context.MODE_PRIVATE);
    Gson gson = new Gson();
    String json = sharedPreferences.getString("list", null);
    Type type = new TypeToken&lt;ArrayList&lt;Example&gt;&gt;() {}.getType();
    result = gson.fromJson(json, type);

    if (result == null) {
        result = new ArrayList&lt;&gt;();
    }
    return result;
}

// ... 调用代码(在MainActivity中)如下:
Examples = instance_read_write.loadData(context);

不想引发传值 vs 传引用的讨论,似乎您期望通过在方法体中对其赋值来更新Example实际参数 - 但实际上不会这样 - 您只能对对象进行操作以影响它:https://stackoverflow.com/a/40523/2711811。

为了完成这个主题,这里有一个解决方案,可以继续传入Examples对象的意图:

// 在调用方法中...
Examples = new ArrayList<Example>;
instance_read_write.loadData(context, Examples);

//...在类Instance_Read_Write中...

public void loadData(Context context, ArrayList<Example> Examples) {
SharedPreferences sharedPreferences = context.getSharedPreferences("instanceKey", Context.MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("list", null);
Type type = new TypeToken<ArrayList<Example>>() {}.getType();
ArrayList<Example> t = gson.fromJson(json, type);

if (t != null) {
    Examples.addAll(t);
}

}


<details>
<summary>英文:</summary>

This addresses one error in your posted code namely the treatment of the `Examples` parameter in the method `loadData` method.

Since it seems your intention of the `loadData` is to always produce an ArrayList&lt;Example&gt; then I&#39;d recommend returning the instance.  Alternatively, you would have to first create an empty ArrayList&lt;Example&gt; and pass that in and then operate on it.

So using the approach of returning the ArrayList&lt;Example&gt;:

    public ArrayList&lt;Example&gt; loadData(Context context) {
        ArrayList&lt;Example&gt; result;
        SharedPreferences sharedPreferences = context.getSharedPreferences(&quot;instanceKey&quot;,Context.MODE_PRIVATE);
        Gson gson = new Gson();
        String json = sharedPreferences.getString(&quot;list&quot;, null);
        Type type = new TypeToken&lt;ArrayList&lt;Example&gt;&gt;() {}.getType();
        result = gson.fromJson(json, type);

        if (result == null) {
            result = new ArrayList&lt;&gt;();
        }
        return result;
    }
    
    // ... and the calling code (in MainActivity) looks like:
    Examples = instance_read_write.loadData(context);

Not to stoke up a pass-by-value vs pass-by-reference discussion - it appears you are expecting `Example` actual parameter to be updated by assigning it in the body of the method - which it will not - you can only operate on the object to affect it: https://stackoverflow.com/a/40523/2711811.

To complete the topic, here&#39;s a solution which would continue your intention of passing in the `Examples` object:

    // In calling method...
    Examples = new ArrayList&lt;Example&gt;;
    instance_read_write.loadData(context,Examples);
    
    
    
    //...in class Instance_Read_Write...
    
    public void loadData(Context context, ArrayList&lt;Example&gt; Examples) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(&quot;instanceKey&quot;,Context.MODE_PRIVATE);
        Gson gson = new Gson();
        String json = sharedPreferences.getString(&quot;list&quot;, null);
        Type type = new TypeToken&lt;ArrayList&lt;Example&gt;&gt;() {}.getType();
        ArrayList&lt;Example&gt; t = gson.fromJson(json, type);
       
        if (t != null) {
            Examples.addAll(t);
        }
    }



</details>



huangapple
  • 本文由 发表于 2020年9月7日 16:02:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/63773566.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定