使用Gson将动态ListView保存在SharedPreferences中

时间:2019-01-03 10:54:33

标签: android listview

我有一个动态增长的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);

如何将此代码段的第一行应用于Listview?我看不到办法。

1 个答案:

答案 0 :(得分:2)

使用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中,请使用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);
    }