Nicky Apriliani
Nicky Apriliani

Reputation: 441

Delete Item from Arraylist in SharedPreferences with Android Studio

I want to remove the item that i choose in listView from sharedPreferences too. But, after i delete the item from the listview, it still remain in sharedPrefereces. Because when i display the data from SharedPreferences the data doesn't change at all. Can anyone help me to solve this problem?? Thank you

SharedPreferences.Java

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

import com.amobi.picassogridview.model.Product;
import com.google.gson.Gson;

public class SharedPreference {

    public static final String PREFS_NAME = "PRODUCT_APP";
    public static final String FAVORITES = "Product_Favorite";

    public SharedPreference() {
        super();
    }

    // This four methods are used for maintaining favorites.
    public void saveFavorites(Context context, List<Product> favorites) {
        SharedPreferences settings;
        Editor editor;

        settings = context.getSharedPreferences(PREFS_NAME,Context.MODE_PRIVATE);
        editor = settings.edit();

        Gson gson = new Gson();
        String jsonFavorites = gson.toJson(favorites);

        editor.putString(FAVORITES, jsonFavorites);

        editor.commit();
    }

    public void addFavorite(Context context, Product product) {
        List<Product> favorites = getFavorites(context);
        if (favorites == null)
            favorites = new ArrayList<Product>();
        favorites.add(product);
        saveFavorites(context, favorites);
    }

    public void removeFavorite(Context context, Product product) {
        ArrayList<Product> favorites = getFavorites(context);
        if (favorites != null) {
            favorites.remove(product);
            saveFavorites(context, favorites);
        }
    }

    public ArrayList<Product> getFavorites(Context context) {
        SharedPreferences settings;
        List<Product> favorites;

        settings = context.getSharedPreferences(PREFS_NAME,
                Context.MODE_PRIVATE);

        if (settings.contains(FAVORITES)) {
            String jsonFavorites = settings.getString(FAVORITES, null);
            Gson gson = new Gson();
            Product[] favoriteItems = gson.fromJson(jsonFavorites,
                    Product[].class);

            favorites = Arrays.asList(favoriteItems);
            favorites = new ArrayList<Product>(favorites);
        } else
            return null;

        return (ArrayList<Product>) favorites;
    }
}

CartActivity.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.amobi.picassogridview.adapter.ProductListAdapter;
import com.amobi.picassogridview.model.Product;
import com.amobi.picassogridview.utils.SharedPreference;

import java.util.List;

public class cartActivity extends AppCompatActivity {

    public static final String ARG_ITEM_ID = "favorite_list";

    ListView favoriteList;
    SharedPreference sharedPreference;
    List<Product> favorites;
    ProductListAdapter productListAdapter;
    Button home;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cart);

        sharedPreference = new SharedPreference();
        favorites = sharedPreference.getFavorites(this);

        favoriteList = (ListView) findViewById(R.id.listView);
        if (favorites == null) {
            Toast.makeText(cartActivity.this, "Error - No Data Available", Toast.LENGTH_SHORT).show();
        } else {

            if (favorites.size() == 0) {
                Toast.makeText(this, "Anda Belum Punya Belanjaan", Toast.LENGTH_SHORT).show();
            }

            if (favorites != null) {
                productListAdapter = new ProductListAdapter(this, favorites);
                favoriteList.setAdapter(productListAdapter);
                favoriteList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                    @Override
                    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

                        sharedPreference.removeFavorite(cartActivity.this, favorites.get(position));
                        favorites.remove(position);
                        productListAdapter.notifyDataSetChanged();
                        Toast.makeText(cartActivity.this, "Success Remove",Toast.LENGTH_SHORT).show();

                        return true;
                    }
                });
            }
        }

        home=(Button) findViewById(R.id.bbtnHome);
        home.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            }
        });
    }
    @Override
    public void onResume()
    {
        super.onResume();
    }

}

Upvotes: 1

Views: 3248

Answers (2)

urgas9
urgas9

Reputation: 826

Check this line, I think that the product does not get removed from your list:

favorites.remove(product);

Java uses equals method to compare objects and find the one that is "the same", equal. By default it compares references to objects (or values of non-objects: int, long,...). So if two objects doesn't have the same reference (even if the content is the same) the equals method will return false. This is the case in your example as you are loading the list from SharedPreferences once again.

One solution is to override equals method in your Product class, or iterate through list on your own, comparing values you want.

Upvotes: 1

Shree Krishna
Shree Krishna

Reputation: 8562

Try like this, Create a method called refreshDisplay

public void refreshDisplay(){
    productListAdapter = new ProductListAdapter(this, favorites);
    favoriteList.setAdapter(productListAdapter);
    productListAdapter.notifyDataSetChanged();
}

Then use this method like,

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

        sharedPreference.removeFavorite(cartActivity.this, favorites.get(position));
        favorites.remove(position);
        refreshDisplay();
        Toast.makeText(cartActivity.this, "Success Remove",Toast.LENGTH_SHORT).show();

        return true;
    }

Upvotes: 1

Related Questions