我正在尝试做什么:
Item(String name, int price, int owned){
this.name = name;
this.price = price;
this.owned = owned;
}
商店活动:
public class ShopActivity extends AppCompatActivity {
private ArrayList<AbstractItem> items = new ArrayList<AbstractItem>();
private Game game;
private BuySell buySell;
Item item1 = new Item("Item1", 10, 0);
Item item2 = new Item("Item2", 5, 0);
Item item3 = new Item("Item3", 7, 0);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shop);
game = (Game) SingletonManager.getInstance().getClassReference(Game.class);
items.add(item1);
items.add(item2);
items.add(item3);
ListView listView = (ListView) findViewById(R.id.shopList);
final ItemsAdapter adapter = new ItemsAdapter (this, items);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
AbstractItem selectedItem = items.get(position);
buySell.buy(selectedItem, game);
adapter.notifyDataSetChanged();
}
});
}
}
现在我的问题。每次我进入ShopActivity,它都会创建新的Object。我可以购买,比如说30个Item1,回到菜单再去购物,我得到0拥有的对象。我该怎么办这些对象只有一个?如果有人理解并可以提供帮助,非常感谢;)
答案 0 :(得分:0)
有很多选择:
答案 1 :(得分:0)
add dependency
compile 'com.google.code.gson:gson:2.6.2'
然后使用它来保存和检索项目。
public class Temp {
private class Item {
public Item(String name, int price, int owned) {
}
}
private class ItemHolder {
private ArrayList<Item> items;
public ItemHolder(ArrayList<Item> items) {
this.items = items;
}
public ArrayList<Item> getItems() {
return items;
}
}
public void yourMethod() {
Context c = null;
Item myItem1 = new Item("name", 0, 1);
Item myItem2 = new Item("name", 0, 1);
Item myItem3 = new Item("name", 0, 1);
ArrayList<Item> items = new ArrayList<>();
items.add(myItem1);
items.add(myItem2);
items.add(myItem3);
//save your items
savePersistent(new ItemHolder(items), c);
//retrieve them anywhere
ItemHolder savedItems = getPersistentData(c);
}
private void savePersistent(ItemHolder holder, Context ctx) {
Gson gson = new Gson();
String jsonString = gson.toJson(holder);
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(ctx);
SharedPreferences.Editor editor = pref.edit();
editor.putString("key", jsonString);
editor.commit();
}
private ItemHolder getPersistentData(Context ctx) {
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(ctx);
String jsonString = pref.getString("key", null);
Gson gson = new Gson();
ItemHolder obj = gson.fromJson(jsonString, ItemHolder.class);
return obj;
}
}