【发布时间】:2020-01-12 23:52:14
【问题描述】:
我有已安装应用程序的列表,当我单击其中任何一个时,我可以获得单击的应用程序的包名称,现在我想将单击的包名称保存在字符串的 ArrayList 中,使用 Gson 到 SharedPreferences。并获取保存的包名。
我检查了一些以前的答案,但没有得到我想要的解决方案。
这是我要保存被点击应用的包名的代码。
String ApplicationPackageName = adapter.stringList.get(position);
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(ApplicationPackageName);
editor.putString("task list", json);
editor.apply();
这是我要获取保存的包名称的代码。
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("task list", null);
Type type = new TypeToken<ArrayList<String>>() {}.getType();
arrayList = gson.fromJson(json, type);
if (arrayList == null) {
arrayList = new ArrayList<>();
}
但是我收到了这个错误。 Caused by: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 2 path $
有什么帮助吗?
【问题讨论】:
-
它会在哪一行崩溃?
-
@just_user 这一行崩溃了`arrayList = gson.fromJson(json, type);`
-
我想我刚刚看到了问题:
String ApplicationPackageName = adapter.stringList.get(position);这已经是一个字符串了。因此,您在 sharedpreferences 中存储的不是 json 数组。在String json = sharedPreferences.getString("task list", null);这一行放一个断点或一条日志消息,看看你得到的值。 -
@just_user 我得到了这个“任务列表”。我怎样才能得到包名呢?
标签: android json arraylist gson