【问题标题】:How can I cast a stringarray to an ArrayList in Android?如何在 Android 中将字符串数组转换为 ArrayList?
【发布时间】:2015-06-02 15:53:09
【问题描述】:

我在 SharedPreferences 中保存了一个带有 json 的列表。这工作得很好,但是当我尝试加载它时,Android Studio 告诉我我不能

private List<AppInfo> apps;

apps = new ArrayList<AppInfo>();

// Storing in method
ArrayList<String> lollist = new ArrayList<>();
lollist = new ArrayList<>(Arrays.asList(String.valueOf(apps)));
setStringArrayPref(this, "urls", lollist);

// Loading which doesn't work
lollist = getStringArrayPref(this, "urls");
apps = (String[]) lollist.toArray();

我得到的错误是

Required: java.util.list <com.....AppInfo>
Found: java.lang.String[]

我该怎么做?

【问题讨论】:

  • 恐怕String 的数组将永远成为AppInfo 的列表
  • @RC 我正在做的是将所有包名(已安装的应用程序)的列表保存到 SharedPreferences。这适用于保存。只是不加载。我发现序列化最好,所以我用这个序列化:stackoverflow.com/questions/7361627/…
  • 如果您将其转换为String[],那么apps 不应该也是String[] 类型吗?
  • @Carl 我想你误解了String.valueOf,你应该阅读“相关”问题

标签: android list arraylist


【解决方案1】:

您可能想为此使用Gson 库。 这为您提供了更简单的单行选项来将数据结构转换为 Json,反之亦然。

用法:

private Gson gson = new Gson();
private List<AppInfo> apps = new ArrayList<AppInfo>();

String jsonString = gson.toJson(apps); //You may store this string in your shared preference
Type type = new TypeToken<List<AppInfo>>() {}.getType();
apps = gson.fromJson(jsonString, type);

注意: 您应该公开数据模型类中的变量以使用 Gson。像这样。

@Expose
private String name;

【讨论】:

    猜你喜欢
    • 2015-09-30
    • 1970-01-01
    • 2012-02-14
    • 2012-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-24
    • 2013-11-19
    相关资源
    最近更新 更多