我的申请包含2项活动。 第一个包含一个列表,从中我逐行向第二个活动发送行:http://postimg.org/image/5pmlso0ct/ 第二个活动(我添加了一些行):http://postimg.org/image/sr9zvqp2d/
当我关闭应用程序并再次启动时出现我的问题,在第二个活动中,我只获得了第一个活动发送的最后一行: http://postimg.org/image/7tuu2ptdl/ 我还尝试创建另一个类来保存填充listview的arraylist,但它似乎不起作用我想
〜第一次活动〜
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View view,
int position, long arg3) {
SharedPreferences sp = context.getSharedPreferences("Save",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
textView4 = (TextView)view.findViewById(R.id.titleTextView);
textView5 = (TextView)view.findViewById(R.id.userNameTextView);
n =textView4.getText().toString();
m=textView5.getText().toString();
MyObject=new CustomObject(n,m);
Gson gson = new Gson();
String json = gson.toJson(MyObject);
editor.putString("MyObject", json);
editor.apply();
〜第二次活动〜
public class Favorites extends Activity{
private ListView lv;
private String n, m;
private CustomObject obj;
private SaveData save;
SharedPreferences sharedpreferences;
List<CustomObject> favorites=new ArrayList<>();
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favorites);
lv = (ListView) findViewById(R.id.forthlistview);
sharedpreferences = getSharedPreferences("Save",
Context.MODE_PRIVATE);
}
private void fillFavoriteList() {
Gson gson = new Gson();
String json = sharedpreferences.getString("MyObject", "");
obj = gson.fromJson(json, CustomObject.class);
favorites.add(obj);
HashSet<CustomObject> hs = new HashSet<CustomObject>();
hs.addAll(favorites);
favorites.clear();
favorites.addAll(hs);
save.setGlobalArrayOfCustomObjects(favorites);
adapter = new AdapterFavorites(Favorites.this, favorites);
lv.setAdapter(adapter);
}
protected void onResume() {
super.onResume();
if(favorites==null)
{favorites=save.getGlobalArrayOfCustomObjects(); fillFavoriteList();}
else fillFavoriteList();
}
}
~SaveData类〜
public class SaveData extends Favorites {
private List<CustomObject> globalArray;
public void setGlobalArrayOfCustomObjects(List<CustomObject> newArray){
globalArray = newArray;
}
public List<CustomObject> getGlobalArrayOfCustomObjects(){
return globalArray;
}
}