RastaMan27 RastaMan27 - 1 year ago 114
Android Question

How create object only once and use it in code?

What i'm trying to do :

Item(String name, int price, int owned){
this.name = name;
this.price = price;
this.owned = owned;

Shop Activity:

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);

protected void onCreate(Bundle savedInstanceState) {

game = (Game) SingletonManager.getInstance().getClassReference(Game.class);


ListView listView = (ListView) findViewById(R.id.shopList);
final ItemsAdapter adapter = new ItemsAdapter (this, items);
listView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

AbstractItem selectedItem = items.get(position);
buySell.buy(selectedItem, game);


And now my question. Every time i go in ShopActivity it creates new Object. I can buy, let's say 30pcs of Item1, go back to menu and to Shop again, and i get object with 0 owned. What should i do with those object to have only one of each? If anyone understand and can help, big thanks ;)

Answer Source
add dependency
compile 'com.google.code.gson:gson:2.6.2'

Then use this to save and retrieve items.

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<>();

        //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);

    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;

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download