[英]Save an arraylist with sharedpreferences and show it in listview
我有两个活动。 我想从 Note.java 获取 edittext 数据并将其放入 MainActivity.java 的列表视图中。 但我无法以列表格式进行。
笔记.java
public class Note extends FragmentActivity implements
EditText editText,editText2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note);
editText = (EditText)findViewById(R.id.editText);
SharedPreferences sharedPref = getSharedPreferences("note", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("myKey", editText.getText().toString());
editor.commit();
}
主活动.java
public class MainActivity extends AppCompatActivity{
ListView listView;
List list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
SharedPreferences sharedPref = getSharedPreferences("note", Context.MODE_PRIVATE);
String baslik = sharedPref.getString("myKey",null);
list = new ArrayList<String>();
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,list);
list.add(baslik);
listView.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
}
SharedPreferences
只能存储原始数据类型。您不能在SharedPreferences
存储 References 类型。对于这种情况,我使用Gson
库。
第 1 步:将列表转换为字符串
Gson g = new Gson();
String str = g.toJson(list);
第 2 步:在SharedPreferences
存储字符串
要从SharedPreferences
获取数据,您必须像这样反序列化您的字符串:
Gson g = new Gson();
Type type = new TypeToken<ArrayList<YourClass>>(){}.getType();
List<YourClass> clazz = g.fromJson(yourString,type);
假设您想通过 Sharedprefernces 保存和加载 List:
public static final String NEWS = "news";
private SharedPreferences mPreferences;
public void saveNews(List<ResponseNews> news) {
mPreferences.edit().putString(NEWS, new Gson().toJson(news)).commit();
}
public List<ResponseNews> loadNews() {
return new Gson().fromJson(mPreferences.getString(NEWS, ""), new TypeToken<List<ResponseNews>>() {
}.getType());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.