【发布时间】: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 不是必需的。