【问题标题】:Save dynamic ListView in SharedPreferences using Gson使用 Gson 在 SharedPreferences 中保存动态 ListView
【发布时间】:2019-05-29 23:04:19
【问题描述】:

我有一个动态增长的 ListView。它就像一个简单的待办事项列表应用程序。用户输入一个字符串,该字符串被添加到listView。可以使用删除按钮删除 listView 中的数据。没有什么特别的。问题是当您按下后退按钮关闭应用程序时,此 listView 消失了。 我现在发现 gson 可以保存我的 listView 并在以后检索它。

很遗憾,我有一些理解上的问题。首先,这是我的代码:

public class MainActivity extends AppCompatActivity {
public SharedPreferences pref;
public SharedPreferences.Editor editor;
EditText editText;

Context context;
ListView listView;
ArrayAdapter<String> adapter;
ImageButton imageButtondelete;
TextView textViewAdd;
Gson gson = new Gson();
List<String> arrayList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.todolist);

    editText = findViewById(R.id.editText);
    listView = findViewById(R.id.listview);
    textViewAdd = findViewById(R.id.textViewAdd);
    imageButtondelete = findViewById(R.id.imageButton2);

    initListView();
    text2List();
    deleteItemsinListView();
}
    // init the listview
public void initListView() {
    arrayList = new ArrayList<String>();
    arrayList.add("");

    listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
    adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_checked, arrayList);
    adapter.remove("");
    listView.setAdapter(adapter);

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // when checked, strike through the data in the list
            if (listView.isItemChecked(position)) {
                TextView text = (TextView) view;
                text.setPaintFlags(text.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
            } else {
                TextView text = (TextView) view;
                text.setPaintFlags(0);
            }
       }
    });
}
// add user input from edittext to the list
public void text2List() {
    textViewAdd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!(editText.getText().toString().isEmpty()))
                // this line adds the data of your EditText and puts in your array
                arrayList.add(editText.getText().toString());
            // next thing you have to do is check if your adapter has changed
            adapter.notifyDataSetChanged();
            editText.getText().clear();
        }
    });
}

public void deleteItemsinListView() {
    imageButtondelete.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            adapter.clear();
        }
    });
}

}

现在,我读了这篇文章How to convert List to a JSON Object using GSON?,不接受但有效的答案是

Type listType = new TypeToken<List<String>>() {}.getType();
 List<String> target = new LinkedList<String>();
 target.add("blah");
 Gson gson = new Gson();
 String json = gson.toJson(target, listType);
 List<String> target2 = gson.fromJson(json, listType);

如何将此代码的第一行 sn-p 应用于我的 Listview?我看不到方法。

【问题讨论】:

  • 您确定要使用 GSON 吗?我可以向您展示一种非常简单的 2 行代码方式,使用 org.json 库将任何内容转换为 json 字符串。
  • @Daniel B. 你能告诉我如何保存我的列表吗? Gson 不是必需的。

标签: android listview


【解决方案1】:

使用 org.json

您可以使用 org.json 库而不是使用 GSON

像这样使用它:

private void test(){
        List<String> strings = new ArrayList();
        JSONArray jsonArray = new JSONArray(strings);
        String stringTosave = jsonArray.toString();
    }

这里是下载库的链接:

https://mvnrepository.com/artifact/org.json/json/20180813

文件位于文件行下。

保存到 SharedPreferences

要将字符串保存在 SharedPreferences 中,请使用 Editor editor = getSharedPreferences("prefs",Context.MODE_PRIVATE).edit(); 获取对 SharedPreferences 编辑器的引用

然后使用editor.putString("yourkey",stringToSave);

当您完成放置字符串后,您需要调用editor.commit(),以保存您的更改。

检索使用getSharedPreferences("prefs",Context.MODE_PRIVATE).getString("yourkey");

完整示例

  private void test(){
      List<String> strings = new ArrayList();
      JSONArray jsonArray = new JSONArray(strings);
      String stringTosave = jsonArray.toString();

      SharedPreferences.Editor editor = getSharedPreferences("prefs",Context.MODE_PRIVATE).edit();
      editor.putString("key","string");
      editor.commit();

      SharedPreferences sharedPreferences = getSharedPreferences("prefs",Context.MODE_PRIVATE);
      String saved = sharedPreferences.getString("key","defaultvalue");
      JSONArray savedJsonArray = new JSONArray(saved);
    }

【讨论】:

  • 好的,谢谢,但是现在如何保存呢?并稍后检索它
  • @Blnpwr 已编辑以向您展示如何将字符串保存到 SharedPrefernces。
  • 非常感谢。如果发生了,我可以问你问题吗?
  • @Blnpwr 当然。我还编辑了答案以使用JSONArray 而不是JSONObject 将列表转换为字符串,因为列表是一个集合,您应该使用JSONArray 进行集合。
  • 1.是的。 2.你可以随时使用,没有时间限制
猜你喜欢
  • 2016-06-09
  • 1970-01-01
  • 2022-09-27
  • 2017-11-03
  • 1970-01-01
  • 2017-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多