Create favorite listview with shared preferences - android

I have a listview of ringtones .. I feed the list via mysql database.. (such as song names,song urls ...). I dynamically add products(ringtones) in my listview by adding new item in my database, so none of this data are inside my app except row icons.
This is the view
As you can see I have a bookmark border icon that when user clicks on it, it will turn into selected...This is how it works :
#Override
public void favOnClick(int position) {
Product product = productList.get(position);
if (product.faved) {
sharedPreference.addFavorite(activity,product);
product.setFavId(R.mipmap.bookmarked);
product.faved=false;
}else {
sharedPreference.removeFavorite(activity,product);
product.setFavId(R.mipmap.bookmark_border);
product.faved = true;
}
adapter.notifyDataSetChanged();
};
but nothing will happen in my "FAVORITES" tab .. Even the state of bookmark icon when it is selected will not be saved..
Custom Adapter
public class FunDapter<T> extends BaseAdapter {
public interface PlayPauseClick {
void favOnClick(int position);
}
private PlayPauseClick callback;
public void setPlayPauseClickListener(PlayPauseClick listener) {
this.callback = listener;
}
protected List<T> mDataItems;
protected List<T> mOrigDataItems;
protected final Context mContext;
private final int mLayoutResource;
private final BindDictionary<T> mBindDictionary;
public FunDapter(Context context, List<T> dataItems, int layoutResource,
BindDictionary<T> dictionary) {
this(context, dataItems, layoutResource, null, dictionary);
}
public FunDapter(Context context, List<T> dataItems, int layoutResource,
LongExtractor<T> idExtractor, BindDictionary<T> dictionary) {
this.mContext = context;
this.mDataItems = dataItems;
this.mOrigDataItems = dataItems;
this.mLayoutResource = layoutResource;
this.mBindDictionary = dictionary;
sharedPreference = new SharedPreference();
}
public void updateData(List<T> dataItems) {
this.mDataItems = dataItems;
this.mOrigDataItems = dataItems;
notifyDataSetChanged();
}
#Override
public int getCount() {
if (mDataItems == null || mBindDictionary == null) return 0;
return mDataItems.size();
}
#Override
public T getItem(int position) {
return mDataItems.get(position);
}
#Override
public long getItemId(int position) {
if(idExtractor == null) return position;
else return idExtractor.getLongValue(getItem(position), position);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = convertView;
final GenericViewHolder holder;
if (null == v) {
LayoutInflater vi =
(LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(mLayoutResource, null);
holder = new GenericViewHolder();
holder.root = v;
//init the sub views and put them in a holder instance
FunDapterUtils.initViews(v, holder, mBindDictionary);
v.setTag(holder);
}else {
holder = (GenericViewHolder) v.getTag();
}
final T item = getItem(position);
showData(item, holder, position);
Product product = (Product) mDataItems.get(position);
holder.favImage=(ImageView)v.findViewById(R.id.favImage);
holder.favImage.setImageResource(product.getFavId());
holder.favImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (callback != null) {
callback.favOnClick(position);
}
}
});
return v;
}
}
Product model class
#SuppressWarnings("serial")
public class Product implements Serializable {
#SerializedName("pid")
public int pid;
#SerializedName("name")
public String name;
#SerializedName("qty")
public int qty;
#SerializedName("price")
public String description;
#SerializedName("song_url")
public String song_url;
#SerializedName("date")
public String date;
public boolean paused = true;
public boolean faved = true;
private int favId;
public int getFavId() {
return favId;}
public void setFavId(int favId) {
this.favId = favId;}
}
SharedPreferences class
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;
}
}
I'm stuck here for a few days, Can you help me please !
This is my project link if you would like to look into it for further info
http://symphonyrecords.ir/RingtoneApp.rar

There are two problems here (based on your project)
First (saving state of bookmark Imageview)
In adapter create a method that checks whether a particular product exists in SharedPreferences
public boolean checkFavoriteItem(Product checkProduct) {
boolean check = false;
List<Product> favorites = sharedPreference.getFavorites(null, mContext);
if (favorites != null) {
for (Product product : favorites) {
if (product.equals(checkProduct)) {
check = true;
break;
}
}
}
return check;
}
Inside adapter check if a product exists in shared preferences then set bookmarked drawable and set a tag
if (checkFavoriteItem(product)) {
holder.favoriteImg.setImageResource(R.mipmap.bookmarked);
holder.favoriteImg.setTag("bookmarked");
} else {
holder.favoriteImg.setImageResource(R.mipmap.bookmark_border);
holder.favoriteImg.setTag("bookmark_border");
}
Then inside favOnClick callback method
#Override
public boolean favOnClick(int position ,View v) {
Product product = (Product) productList.get(position);
ImageView button = (ImageView) v.findViewById(R.id.favImage);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("bookmark_border")) {
sharedPreference.addFavorite(activity,product);
Toast.makeText(activity,"Added to Favorites",Toast.LENGTH_SHORT).show();
button.setTag("bookmarked");
button.setImageResource(R.mipmap.bookmarked);
} else {
sharedPreference.removeFavorite(activity,product);
button.setTag("bookmark_border");
button.setImageResource(R.mipmap.bookmark_border);
Toast.makeText(activity,"Removed from Favorites",Toast.LENGTH_SHORT).show();
}
return true;
}
Second (get favorite product and pass it to "FAVORITE" Fragment)
Inside getFavorite method add a String parameter
Then in your "FAVORITE" Fragment with processFinish(your AsyncResponse) call your getFavorite in order to get your Favorite product list then set your adapter :
Context mContext;
`mContext = getContext();`
#Override
public void processFinish(String s) {
productList = sharedPreference.getFavorites(s, mContext);
BindDictionary<Product> dict = new BindDictionary<Product>();
dict.addStringField(R.id.tvName, new StringExtractor<Product>() {
#Override
public String getStringValue(Product product, int position) {
return product.name;
}
});
dict.addStringField(R.id.tvDescription, new StringExtractor<Product>() {
#Override
public String getStringValue(Product product, int position) {
return product.description;
}
});
dict.addStringField(R.id.tvQty, new StringExtractor<Product>() {
#Override
public String getStringValue(Product product, int position) {
return "" + product.qty;
}
});
adapter = new FunDapter<>(getActivity(), productList, R.layout.d_layout_list_d, dict);
lvProduct.setAdapter(adapter);
}

Make sure favOnClick method change the object in FunDapter.mDataItems.
So, Change the callback method:
#Override
public void favOnClick(int position) {
Product product = adapter.get(position);
if (product.faved) {
sharedPreference.addFavorite(activity, product);
product.setFavId(R.mipmap.bookmarked);
product.faved=false;
}else {
sharedPreference.removeFavorite(activity, product);
product.setFavId(R.mipmap.bookmark_border);
product.faved = true;
}
adapter.notifyDataSetChanged();
};

Check this, 99% working code
On click Fav Btn
List< RvModel > favorites_list = storageFavorites.loadFavourite();
boolean exist = false;
if (favorites_list == null) {
favorites_list = new ArrayList<>();
}
for (int i = 0; i < favorites_list.size(); i++) {
if (favorites_list.get(i).getId().equals(rvModelArrayList.get(position).getId())) {
exist = true;
}
}
if (!exist) {
ArrayList< RvModel > audios = new ArrayList< RvModel >(favorites_list);
audios.add(rvModelArrayList.get(position));
storageFavorites.storeImage(audios);
holder.bookMarkBtn.setImageDrawable(activity.getResources().getDrawable(R.drawable.ic_bookmark_full));
} else {
ArrayList< RvModel > new_favorites = new ArrayList< RvModel >();
for (int i = 0; i < favorites_list.size(); i++) {
if (!favorites_list.get(i).getId().equals(rvModelArrayList.get(position).getId())) {
new_favorites.add(favorites_list.get(i));
}
}
if (favorites) {
Log.v("DOWNLOADED", "favorites==true");
rvModelArrayList.remove(position);
notifyDataSetChanged();
//holder.ripple_view_wallpaper_item.setVisibility(View.GONE);
}
storageFavorites.storeImage(new_favorites);
holder.bookMarkBtn.setImageDrawable(activity.getResources().getDrawable(R.drawable.ic_bookmark));
}
}

Related

How to compare two arraylist and enable toggle accordingly in android

I have an app in which listview with two arraylist suppose 1st "listStorage" and second is "existingDataSet" i have to compare these two arraylist value if found same then enable toggle of that index.
code:-
private LayoutInflater layoutInflater;
private List<AllAppList> listStorage;
private Context mContext;
ArrayList<WhiteListModel> newDataSet, existingDataSet;
private String TAG = AppAdapter.class.getSimpleName();
private MySharedPreference sharedPreference;
private WhiteListModel whiteListModel;
private Gson gson;
public AppAdapter(Context context, List<AllAppList> customizedListView) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
listStorage = customizedListView;
this.mContext = context;
existingDataSet = new ArrayList<>();
newDataSet = new ArrayList<>();
gson = new Gson();
sharedPreference = new MySharedPreference(mContext);
whiteListModel = new WhiteListModel();
//retrieve data from shared preference
String jsonScore = sharedPreference.getAppsArrayListData();
Type type = new TypeToken<ArrayList<WhiteListModel>>() {
}.getType();
existingDataSet = gson.fromJson(jsonScore, type);
}
#Override
public int getCount() {
return listStorage.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder listViewHolder;
if (convertView == null) {
listViewHolder = new ViewHolder();
convertView = layoutInflater.inflate(R.layout.installed_app_list_item, parent, false);
listViewHolder.textInListView = (TextView) convertView.findViewById(R.id.list_app_name);
listViewHolder.imageInListView = (ImageView) convertView.findViewById(R.id.app_icon);
listViewHolder.switchCompat = (SwitchCompat) convertView.findViewById(R.id.toggleButton);
convertView.setTag(listViewHolder);
} else {
listViewHolder = (ViewHolder) convertView.getTag();
}
listViewHolder.textInListView.setText(listStorage.get(position).getName());
listViewHolder.imageInListView.setImageDrawable(listStorage.get(position).getIcon());
for (int i = 0; i<existingDataSet.size(); i++){
for (int j= 0; j<listStorage.size(); j++){
if (existingDataSet.get(i).getPackName().equalsIgnoreCase(listStorage.get(j).getPackName())){
listViewHolder.switchCompat.setChecked(true);
}
}
}
listViewHolder.switchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(final CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
new AlertDialog.Builder(mContext, R.style.AppCompatAlertDialogStyle).setTitle("Warning").setMessage("You want to whiteList this application?").setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Adding items in Dataset
AllAppList appList = listStorage.get(position);
whiteListModel.setName(appList.getName());
whiteListModel.setPackName(appList.getPackName());
if (existingDataSet != null) {
existingDataSet.add(whiteListModel);
saveScoreListToSharedpreference(existingDataSet);
} else {
newDataSet.add(whiteListModel);
saveScoreListToSharedpreference(newDataSet);
}
//Notifying adapter data has been changed.....
notifyDataSetChanged();
listViewHolder.switchCompat.setChecked(false);
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
listViewHolder.switchCompat.setChecked(false);
}
}).show();
}
}
});
return convertView;
}
/**
* Save list of scores to own sharedpref
*
* #param whiteListApps
*/
private void saveScoreListToSharedpreference(ArrayList<WhiteListModel> whiteListApps) {
Gson gson = new Gson();
//convert ArrayList object to String by Gson
String jsonScore = gson.toJson(whiteListApps);
Log.e(TAG, "LIST::" + jsonScore);
//save to shared preference
sharedPreference.saveAppsArrayListData(jsonScore);
}
private static class ViewHolder {
static SwitchCompat switchCompat;
TextView textInListView;
ImageView imageInListView;
}
}
for (int i = 0 ; i < existingDataSet.size() ; i++){
if (existingDataSet.get(i).getPackName().equalsIgnoreCase(listStorage.get(i).getPackName())){
listViewHolder.switchCompat.setChecked(true);
}
}
}
can you try this? switch should retain its value false if not contains within 2 list when on getView because it trigger several times.
boolean isChecked = false
for (int i = 0; i<existingDataSet.size(); i++){
for (int j= 0; j<listStorage.size(); j++){
if (existingDataSet.get(i).getPackName().equalsIgnoreCase(listStorage.get(j).getPackName())){
isChecked = true;
}
}
}
listViewHolder.switchCompat.setChecked(isChecked);

Store and retrive Listview data using Shared Preferences

I have a listview of ringtones .. I feed the list via mysql database.. (such as song names,song urls ...).
I dynamically add products(ringtones) in my listview by adding new item in my database, so none of this data are inside my app except row icons.
This is the view
As you can see I have a bookmark border icon that when user clicks on it, it will turn into selected...This is how it works :
holder.favImage=(ImageView)v.findViewById(R.id.favImage);
holder.favImage.setImageResource(product.getFavId());
holder.favImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Product product = (Product) mDataItems.get(position);
if(product.faved){
product.setFavId(R.mipmap.bookmarked);
sharedPreference.addFavorite(mContext,product);
product.faved=false;
}
else {
sharedPreference.removeFavorite(mContext,product);
product.setFavId(R.mipmap.bookmark_border);
product.faved = true;
}
notifyDataSetChanged();
}
});
but nothing will happen in my "FAVORITES" tab .. Even the state of bookmark icon when it is selected will not be saved..
Custom Adapter
public class FunDapter<T> extends BaseAdapter {
protected List<T> mDataItems;
protected List<T> mOrigDataItems;
protected final Context mContext;
private final int mLayoutResource;
private final BindDictionary<T> mBindDictionary;
SharedPreference sharedPreference;
public FunDapter(Context context, List<T> dataItems, int layoutResource,
BindDictionary<T> dictionary) {
this(context, dataItems, layoutResource, null, dictionary);
}
public FunDapter(Context context, List<T> dataItems, int layoutResource,
LongExtractor<T> idExtractor, BindDictionary<T> dictionary) {
this.mContext = context;
this.mDataItems = dataItems;
this.mOrigDataItems = dataItems;
this.mLayoutResource = layoutResource;
this.mBindDictionary = dictionary;
sharedPreference = new SharedPreference();
}
public void updateData(List<T> dataItems) {
this.mDataItems = dataItems;
this.mOrigDataItems = dataItems;
notifyDataSetChanged();
}
#Override
public int getCount() {
if (mDataItems == null || mBindDictionary == null) return 0;
return mDataItems.size();
}
#Override
public T getItem(int position) {
return mDataItems.get(position);
}
#Override
public long getItemId(int position) {
if(idExtractor == null) return position;
else return idExtractor.getLongValue(getItem(position), position);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = convertView;
final GenericViewHolder holder;
if (null == v) {
LayoutInflater vi =
(LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(mLayoutResource, null);
holder = new GenericViewHolder();
holder.root = v;
//init the sub views and put them in a holder instance
FunDapterUtils.initViews(v, holder, mBindDictionary);
v.setTag(holder);
}else {
holder = (GenericViewHolder) v.getTag();
}
final T item = getItem(position);
showData(item, holder, position);
final Product product = (Product) mDataItems.get(position);
holder.favImage=(ImageView)v.findViewById(R.id.favImage);
holder.favImage.setImageResource(product.getFavId());
holder.favImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(product.faved){
product.setFavId(R.mipmap.bookmarked);
sharedPreference.addFavorite(mContext,product);
product.faved=false;
}
else {
sharedPreference.removeFavorite(mContext,product);
product.setFavId(R.mipmap.bookmark_border);
product.faved = true;
}
notifyDataSetChanged();
}
});
return v;
}
}
Product model class
#SuppressWarnings("serial")
public class Product implements Serializable {
#SerializedName("pid")
public int pid;
#SerializedName("name")
public String name;
#SerializedName("qty")
public int qty;
#SerializedName("price")
public String description;
#SerializedName("song_url")
public String song_url;
#SerializedName("date")
public String date;
public boolean paused = true;
public boolean faved = true;
private int favId;
public int getFavId() {
return favId;}
public void setFavId(int favId) {
this.favId = favId;}
}
SharedPreferences class
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;
}
}
I'm stuck here for a few days, Can you help me please !
Actually your implementation more complex for the favorite, I thing simply take one column into your database like name isFavorite and by default added zero into this column when you press button then change value zero to one but every time we are not connected with internet so use SQLite database reason behind that size and speed of the SQLite database is more compare to SharedPreferences.
But here you not want to use SQLite database so first download json from the your web service and only change made when user click on the favorite button like
Json format before click:
{unieq_id:”1”, isFavorite :”0”}
Json format after click:
{unieq_id:”1”, isFavorite :”1”}
If isFavourite 0 then your non favorite icon display else display your favorite icon.

listview with increment and decrement buttons with quantity

In listview I have a increment and decrement buttons for change the quantity. increasing and decreasing operations are working fine. but quantity will display in array in other activity. please help me i am new to android development. Here first activity and second activity snaps
MainActivity
public class CatalogActivity extends Activity implements CustomButtonListener{
private List<Product> mProductList;
static int quantity2;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.catalog);
// Obtain a reference to the product catalog
mProductList = ShoppingCartHelper.getCatalog(getResources());
// Make sure to clear the selections
for(int i=0; i<mProductList.size(); i++) {
mProductList.get(i).selected = false;
}
// Create the list
ListView listViewCatalog = (ListView) findViewById(R.id.ListViewCatalog);
listViewCatalog.setAdapter(new ProductAdapter(mProductList, getLayoutInflater(), false));
Button viewShoppingCart = (Button) findViewById(R.id.ButtonViewCart);
ProductAdapter.setCustomButtonListener(this);
viewShoppingCart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent viewShoppingCartIntent = new Intent(getBaseContext(), ShoppingCartActivity.class);
startActivity(viewShoppingCartIntent);
}
});
}
#Override
public void onButtonClickListener(int position, TextView editText, int value) {
quantity2 = Integer.parseInt(editText.getText().toString());
quantity2 = quantity2+1*value;
if(quantity2<0)
quantity2=0;
editText.setText(quantity2+"");
}
}
Product Adapter
public class ProductAdapter extends BaseAdapter {
private List<Product> mProductList;
private LayoutInflater mInflater;
private boolean mShowQuantity;
public static int quantity = 0;
public Context context;
public static ArrayList<Integer> quantity1 = new ArrayList<Integer>();
static CustomButtonListener customButtonListener;
public static int quant;
public ProductAdapter(List<Product> list, LayoutInflater inflater, boolean showQuantity) {
mProductList = list;
mInflater = inflater;
mShowQuantity = showQuantity;
for (int i = 0; i < list.size(); i++) {
quantity1.add(0);
}
}
public static void setCustomButtonListener(CustomButtonListener customButtonListner) {
customButtonListener = customButtonListner;
}
#Override
public int getCount() {
return mProductList.size();
}
#Override
public Product getItem(int position) {
return mProductList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewItem item;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.item, null);
item = new ViewItem();
item.productImageView = (ImageView) convertView
.findViewById(R.id.ImageViewItem);
item.productTitle = (TextView) convertView
.findViewById(R.id.TextViewItem);
item.productQuantity = (TextView) convertView
.findViewById(R.id.textViewQuantity);
item.productCost = (TextView) convertView
.findViewById(R.id.itemcost);
item.productbtn = (Button) convertView.findViewById(R.id.btn_plus);
item.textquanty = (TextView) convertView.findViewById(R.id.num);
item.productbtnminus = (Button) convertView.findViewById(R.id.btn_minus);
item.Layout = (View) convertView.findViewById(R.id.add);
getItem(position).setSelected(false);
convertView.setTag(item);
} else {
item = (ViewItem) convertView.getTag();
}
final Product product = getItem(position);
try {
item.textquanty.setText(quantity1.get(position) + "");
} catch (Exception e) {
e.printStackTrace();
}
item.productbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (customButtonListener != null) {
customButtonListener.onButtonClickListener(position, item.textquanty, 1);
quantity1.set(position, quantity1.get(position) + 1);
ShoppingCartHelper.setQuantity(curProduct, quantity1, position);
}
}
});
item.productbtnminus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (customButtonListener != null) {
customButtonListener.onButtonClickListener(position, item.textquanty, -1);
if (quantity1.get(position) > 0)
quantity1.set(position, quantity1.get(position) - 1);
ShoppingCartHelper.setQuantity(curProduct, quantity1, position);
}
}
});
item.productImageView.setImageDrawable(product.productImage);
item.productTitle.setText(product.title);
item.productCost.setText("" + product.price);
if (mShowQuantity) {
item.productQuantity.setText("Quantity: " + ShoppingCartHelper.getProductQuantity(product, position));
item.Layout.setVisibility(View.GONE);
} else {
item.productQuantity.setVisibility(View.GONE);
}
return convertView;
}
public static Integer getProductQuantity(Product product, int position) {
ShoppingCartEntry curEntry = ShoppingCartHelper.cartMap.get(product);
if (curEntry != null)
quant=Integer.parseInt((quantity1.get(position)+""));
return quant;
}
private class ViewItem {
ImageView productImageView;
TextView productTitle;
TextView productQuantity;
TextView productCost;
public Button productbtn;
public Button productbtnminus;
View Layout;
public TextView textquanty;
}
}
Product
public class Product {
public String title;
public Drawable productImage;
public String description;
public double price;
private int quantity;
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public Product(String title, Drawable productImage, String description,
double price) {
this.title = title;
this.productImage = productImage;
this.description = description;
this.price = price;
}
}
ShoppingCartEntry
public class ShoppingCartEntry {
private Product mProduct;
private ArrayList<Integer> mQuantity;
public ShoppingCartEntry(Product product, ArrayList<Integer> quantity1) {
mProduct = product;
mQuantity = quantity1;
}
public Product getProduct() {
return mProduct;
}
public ArrayList<Integer> getQuantity(int position) {
return mQuantity;
}
public void setQuantity(ArrayList<Integer> quantity1) {
mQuantity = quantity1;
}
}
ShoppingCartHelper
public class ShoppingCartHelper {
public static final String PRODUCT_INDEX = "PRODUCT_INDEX";
protected static List<Product> catalog;
public static Map<Product, ShoppingCartEntry> cartMap = new HashMap<Product, ShoppingCartEntry>();
public static List<Product> getCatalog(Resources res){
if(catalog == null) {
catalog = new Vector<Product>();
catalog.add(new Product("Chiken Curry", res .getDrawable(R.drawable.deadoralive),"Dead or Alive by Tom Clancy with Grant Blackwood", 29.99));
catalog.add(new Product("Mutton Curry", res .getDrawable(R.drawable.switchbook), "Switch by Chip Heath and Dan Heath", 24.99));
catalog.add(new Product("Aloo Curry", res.getDrawable(R.drawable.watchmen), "Watchmen by Alan Moore and Dave Gibbons", 14.99));
catalog.add(new Product("ChikenBiryani", res .getDrawable(R.drawable.deadoralive),"Dead or Alive by Tom Clancy with Grant Blackwood", 25.99));
catalog.add(new Product("MuttonBiryani", res .getDrawable(R.drawable.switchbook), "Switch by Chip Heath and Dan Heath", 21.99));
catalog.add(new Product("Aloo Curry", res.getDrawable(R.drawable.watchmen), "Watchmen by Alan Moore and Dave Gibbons", 12.99));
catalog.add(new Product("Chiken Curry", res .getDrawable(R.drawable.deadoralive),"Dead or Alive by Tom Clancy with Grant Blackwood", 30.99));
catalog.add(new Product("Mutton Curry", res .getDrawable(R.drawable.switchbook), "Switch by Chip Heath and Dan Heath", 28.99));
catalog.add(new Product("Aloo Curry", res.getDrawable(R.drawable.watchmen), "Watchmen by Alan Moore and Dave Gibbons", 18.99));
}
return catalog;
}
public static void setQuantity(Product product, ArrayList<Integer> quantity1, int position) {
// Get the current cart entry
ShoppingCartEntry curEntry = cartMap.get(product);
// If the quantity is zero or less, remove the products
if(ProductAdapter.quantity1.get(position) <= 0) {
if(curEntry != null)
removeProduct(product);
return;
}
// If a current cart entry doesn't exist, create one
if(curEntry == null) {
curEntry = new ShoppingCartEntry(product, quantity1);
cartMap.put(product, curEntry);
return;
}
// Update the quantity
curEntry.setQuantity(quantity1);
}
public static ArrayList<Integer> getProductQuantity(Product product, int position) {
// Get the current cart entry
ShoppingCartEntry curEntry = cartMap.get(product);
if(curEntry != null)
return curEntry.getQuantity(position);
return null;
}
public static void removeProduct(Product product) {
cartMap.remove(product);
}
public static List<Product> getCartList() {
List<Product> cartList = new Vector<Product>(cartMap.keySet().size());
for(Product p : cartMap.keySet()) {
cartList.add(p);
}
return cartList;
}
}

Adding favorites in list view using shared preferences

My app has a lost view and every listitem has a favorite button which when clicked should save the list item and save it in shared preferences. All the favorites list items should be displayed in another my favorites activity and when the list item from my favorites activity is long press it should be removed from favorites. When the favorites button is clicked it should turn dark indicating its added to favorites . in my case
1) when list item is added to favorites the favorites button turn dark but when the activity is closed and reopened the button is no longer dark
2)the list items are getting added to my favorites activity but on long press are not getting removed
sharedpreference.java
public class SharedPreference
{
public static final String PREFS_NAME = "MY_APP";
public static final String FAVORITES = "code_Favorite";
public SharedPreference(){
super();
}
public void saveFavorites(Context context, List<CodeList> 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, CodeList code){
List<CodeList> favorites = getFavorites(context);
if(favorites == null)
favorites = new ArrayList<CodeList>();
favorites.add(code);
saveFavorites(context,favorites);
}
public void removeFavorite(Context context, CodeList code) {
ArrayList<CodeList> favorites = getFavorites(context);
if (favorites != null) {
favorites.remove(code);
saveFavorites(context, favorites);
}
}
public ArrayList<CodeList> getFavorites(Context context) {
SharedPreferences settings;
List<CodeList> favorites;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
if (settings.contains(FAVORITES)) {
String jsonFavorites = settings.getString(FAVORITES, null);
Gson gson = new Gson();
CodeList[] favoriteItems = gson.fromJson(jsonFavorites,
CodeList[].class);
favorites = Arrays.asList(favoriteItems);
favorites = new ArrayList<CodeList>(favorites);
} else
return null;
return (ArrayList<CodeList>) favorites;
}
}
my base adapter
public View getView(final int position, View view, ViewGroup parent)
{
final ViewHolder holder;
if(view == null){
holder = new ViewHolder();
view = inflater.inflate(R.layout.beg_list_item,null);
holder.listHeading = (TextView) view.findViewById(R.id.beg_list_itemTextView);
// holder.listHash = (TextView) view.findViewById(R.id.listview_hashtags);
holder.alphabetList = (ImageView) view.findViewById(R.id.beg_list_itemImageView);
holder.favoriteImg = (ImageView) view.findViewById(R.id.favbtn);
view.setTag(holder);
}else{
holder = (ViewHolder) view.getTag();
}
CodeList code = (CodeList) getItem(position);
holder.listHeading.setText(codeList.get(position).getListHeading());
imageLoader.DisplayImage(codeList.get(position).getAlphabetimg(),
holder.alphabetList);
// holder.listHash.setText(codeList.get(position).getListHashTags());
if (checkFavoriteItem(code)) {
holder.favoriteImg.setImageResource(R.drawable.favorite);
holder.favoriteImg.setTag("yes");
} else {
holder.favoriteImg.setImageResource(R.drawable.unfavorite);
holder.favoriteImg.setTag("no");
}
view.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0){
Intent intent = new Intent(context, SingleItemView.class);
//intent.putExtra("listheading",
// (codeList.get(position).getListHeading()));
//intent.putExtra("alphabetimg",
// (codeList.get(position).getAlphabetimg()));
intent.putExtra("demovideo",
(codeList.get(position).getDailogdemovideo()));
intent.putExtra("download",
(codeList.get(position).getDownloadCode()));
// Start SingleItemView Class
context.startActivity(intent);
}
});
final ImageView favoritesbutton = (ImageView) view.findViewById(R.id.favbtn);
favoritesbutton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
String tag = favoritesbutton.getTag().toString();
if(tag.equalsIgnoreCase("no")){
shrdPrefence.addFavorite(context, codeList.get(position));
Toast.makeText(context, R.string.fav_added, Toast.LENGTH_SHORT).show();
favoritesbutton.setTag("yes");
favoritesbutton.setImageResource(R.drawable.favorite);
}else{
shrdPrefence.removeFavorite(context, codeList.get(position));
favoritesbutton.setTag("no");
favoritesbutton.setImageResource(R.drawable.unfavorite);
Toast.makeText(context, R.string.fav_removed, Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
//Checks whether a particular product exists in SharedPreferences*/
public boolean checkFavoriteItem(CodeList checkCode) {
boolean check = false;
List<CodeList> favorites = shrdPrefence.getFavorites(context);
if (favorites != null) {
for (CodeList code : favorites) {
if (code.equals(checkCode)) {
check = true;
break;
}
}
}
return check;
}
public void add(CodeList code) {
codeList.add(code);
notifyDataSetChanged();
}
public void remove(CodeList code) {
codeList.remove(code);
notifyDataSetChanged();
}
my favorite..java
public class MyFavActivity extends Activity
{
SharedPreference shrdPrfence;
List<CodeList> favorites;
FinalAdapter fnlAdpter;
Context context = this.context;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fav_layout);
shrdPrfence = new SharedPreference();
favorites = shrdPrfence.getFavorites(MyFavActivity.this);
if(favorites == null){
Dialog dialog = new Dialog(MyFavActivity.this);
dialog.setTitle(R.string.nofav_title);
dialog.show();
}else{
if(favorites.size() == 0){
Dialog dialog = new Dialog(MyFavActivity.this);
dialog.setTitle(R.string.nofav_title);
dialog.show();
}
ListView favList = (ListView) findViewById(R.id.fav_layoutListView);
if(favorites != null){
fnlAdpter = new FinalAdapter(MyFavActivity.this, favorites);
favList.setAdapter(fnlAdpter);
favList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View arg1,
int position, long arg3) {
}
});
favList.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
ImageView button = (ImageView) view
.findViewById(R.id.favbtn);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("no")) {
shrdPrfence.addFavorite(MyFavActivity.this,
favorites.get(position));
Toast.makeText(
MyFavActivity.this,
R.string.fav_added,
Toast.LENGTH_SHORT).show();
button.setTag("yes");
button.setImageResource(R.drawable.favorite);
} else {
shrdPrfence.removeFavorite(MyFavActivity.this,
favorites.get(position));
button.setTag("no");
button.setImageResource(R.drawable.unfavorite);
fnlAdpter.remove(favorites.get(position));
Toast.makeText(
MyFavActivity.this,
R.string.fav_removed,
Toast.LENGTH_SHORT).show();
}
return true;
}
});
}
}
}
}
codelist.java
public class CodeList
{
private String description;
private String dailogdemovideo;
private String downloadCode;
public void setDailogdemovideo(String dailogdemovideo)
{
this.dailogdemovideo = dailogdemovideo;
}
public String getDailogdemovideo()
{
return dailogdemovideo;
}
public void setDownloadCode(String downloadCode)
{
this.downloadCode = downloadCode;
}
public String getDownloadCode()
{
return downloadCode;
}
public void setDescription(String description)
{
this.description = description;
}
public String getDescription()
{
return description;
}
}

Unable to use Shared Preferences for Arraylist

This is my list of songs from the NewList.class: http://postimg.org/image/uieab0wuv/ and i want in another activity to have a favorite list with the songs i get when the star button is long-pressed .
I used this tutorial(http://androidopentutorials.com/android-how-to-store-list-of-values-in-sharedpreferences/) to adapt my project but it doesn't work for an ArrayList
**the activity which generates the list **:
public class NewList extends Activity implements
AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener {
public static final String ARG_ITEM_ID = "product_list";
Activity activity;
ListView productListView;
ArrayList<Track> tracks;
SharedPreference sharedPreference;
private ListView newListView;
private EditText inputSearch;
private int TRACK_POSITION;
private AdapterExploreListView adapterExploreListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_explore_music);
newListView = (ListView) findViewById(R.id.newListView);
Bundle extras = getIntent().getExtras();
int temp = extras.getInt("id");
TextView mTextView = (TextView) findViewById(R.id.title_genre);
mTextView.setText(Consts.genresArray[temp]);
fillListWithStyle(Consts.genresArray[temp]);
newListView.setOnItemClickListener(this);
newListView.setOnItemLongClickListener(this);
Toast.makeText(getApplicationContext(),
"Position :" + temp, Toast.LENGTH_LONG)
.show();
}
private void fillListWithStyle(final String style)
{
new AsyncTask<Void,Void,ArrayList<Track>>()
{
#Override
protected ArrayList<Track> doInBackground(Void... voids) {
JsonParser parser = new JsonParser();
String encodedURL="";
try {
encodedURL = URLEncoder.encode(style, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return parser.getTracksForUrl(Consts.url1 + encodedURL + Consts.url2, "tracks");
}
#Override
protected void onPostExecute(ArrayList<Track> tracks) {
super.onPostExecute(tracks);
DataHolder.getInstance().setTracks(tracks);
adapterExploreListView = new AdapterExploreListView(NewList.this, tracks);
newListView.setAdapter(adapterExploreListView);
}
}.execute();
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(this, PlayerActivity.class);
intent.putExtra(PlayerActivity.TRACK_POSITION, i);
startActivityForResult(intent, 1);
TRACK_POSITION=i;
}
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View view,
int position, long arg3) {
ImageView button = (ImageView) view.findViewById(R.id.favbutton);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(activity, tracks.get(position));
Toast.makeText(activity,
activity.getResources().getString(R.string.add_favr),
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.favoritespic);
} else {
sharedPreference.removeFavorite(activity, tracks.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.favoritespicg);
Toast.makeText(activity,
activity.getResources().getString(R.string.remove_favr),
Toast.LENGTH_SHORT).show();
}
return true;
}
}
the adapter
public class AdapterExploreListView extends ArrayAdapter<Track> {
private Context context;
ArrayList<Track> tracks;
SharedPreference sharedPreference;
public AdapterExploreListView(Context context, ArrayList<Track> tracks) {
super(context, R.layout.row_list_explore, tracks);
this.context = context;
this.tracks = new ArrayList<>();
this.tracks = tracks;
sharedPreference = new SharedPreference();
}
#Override
public int getCount() {
return tracks.size();
}
#Override
public Track getItem(int position) {
return tracks.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
View rowView = view;
// reuse views
if (rowView == null) {
LayoutInflater inflater = LayoutInflater.from(context);
rowView = inflater.inflate(R.layout.row_list_explore, null);
// configure view holder
ViewHolder viewHolder = new ViewHolder();
viewHolder.title = (TextView) rowView.findViewById(R.id.titleTextView);
viewHolder.userName = (TextView) rowView.findViewById(R.id.userNameTextView);
viewHolder.favoriteImg = (ImageView) rowView.findViewById(R.id.favbutton);
rowView.setTag(viewHolder);
}
// fill data
final ViewHolder holder = (ViewHolder) rowView.getTag();
Track track = tracks.get(i);
holder.title.setText(track.getTitle());
holder.userName.setText(track.getUsername());
if (checkFavoriteItem(track)) {
holder.favoriteImg.setImageResource(R.drawable.favoritespic);
holder.favoriteImg.setTag("red");
} else {
holder.favoriteImg.setImageResource(R.drawable.favoritespicg);
holder.favoriteImg.setTag("grey");
}
return rowView;
}
static class ViewHolder {
TextView title;
TextView userName;
ImageView favoriteImg;
}
/*Checks whether a particular product exists in SharedPreferences*/
public boolean checkFavoriteItem(Track checkProduct) {
boolean check = false;
List<Track> favorites = sharedPreference.getFavorites(context);
if (favorites != null) {
for (Track track : favorites) {
if (track.equals(checkProduct)) {
check = true;
break;
}
}
}
return check;
}
#Override
public void add(Track track) {
super.add(track);
tracks.add(track);
notifyDataSetChanged();
}
#Override
public void remove(Track track) {
super.remove(track);
tracks.remove(track);
notifyDataSetChanged();
}
}
**the SharedPreference class **
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, ArrayList<Track> 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, Track track) {
ArrayList<Track> favorites = getFavorites(context);
if (favorites == null)
favorites = new ArrayList<Track>();
favorites.add(track);
saveFavorites(context, favorites);
}
public void removeFavorite(Context context, Track track) {
ArrayList<Track> favorites = getFavorites(context);
if (favorites != null) {
favorites.remove(track);
saveFavorites(context, favorites);
}
}
public ArrayList<Track> getFavorites(Context context) {
SharedPreferences settings;
ArrayList<Track> favorites;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
if (settings.contains(FAVORITES)) {
String jsonFavorites = settings.getString(FAVORITES, null);
Gson gson = new Gson();
Track[] favoriteItems = gson.fromJson(jsonFavorites,
Track[].class);
favorites = (ArrayList<Track>) Arrays.asList(favoriteItems);
favorites = new ArrayList<Track>(favorites);
} else
return null;
return (ArrayList<Track>) favorites;
}
}
and the activity where i want to generate my list of favorites
public class ForthActivity extends Activity {
SharedPreference sharedPreference;
ArrayList<Track> favorites;
ListView favoriteList;
AdapterExploreListView adapterExploreListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.forthact);
// Get favorite items from SharedPreferences.
sharedPreference = new SharedPreference();
favorites = sharedPreference.getFavorites(ForthActivity.this);
if (favorites == null) {
} else {
if (favorites.size() == 0) {
}
favoriteList = (ListView) findViewById(R.id.forthlistview);
if (favorites != null) {
adapterExploreListView = new AdapterExploreListView(ForthActivity.this, favorites);
favoriteList.setAdapter(adapterExploreListView);
favoriteList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View arg1,
int position, long arg3) {
}
});
favoriteList
.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(
AdapterView<?> parent, View view,
int position, long id) {
ImageView button = (ImageView) view
.findViewById(R.id.favbutton);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(ForthActivity.this,
favorites.get(position));
Toast.makeText(
ForthActivity.this,
ForthActivity.this.getResources().getString(
R.string.add_favr),
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.favoritespic);
} else {
sharedPreference.removeFavorite(ForthActivity.this,
favorites.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.favoritespicg);
adapterExploreListView.remove(favorites
.get(position));
Toast.makeText(
ForthActivity.this,
ForthActivity.this.getResources().getString(
R.string.remove_favr),
Toast.LENGTH_SHORT).show();
}
return true;
}
});
}
}
}
}
Please help me .Thank you !
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View view,
int position, long arg3) {
ImageView button = (ImageView) view.findViewById(R.id.favbutton);
sharedPreference = new SharedPreference();
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(NewList.this, tracks.get(position));
Toast.makeText(NewList.this,
NewList.this.getResources().getString(R.string.add_favr),
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.favoritespic);
} else {
sharedPreference.removeFavorite(NewList.this, tracks.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.favoritespicg);
Toast.makeText(NewList.this,
NewList.this.getResources().getString(R.string.remove_favr),
Toast.LENGTH_SHORT).show();
}
return true;
}
and this code
private void fillListWithStyle(final String style)
{
new AsyncTask<Void,Void,ArrayList<Track>>()
{
#Override
protected ArrayList<Track> doInBackground(Void... voids) {
JsonParser parser = new JsonParser();
String encodedURL="";
try {
encodedURL = URLEncoder.encode(style, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return parser.getTracksForUrl(Consts.url1 + encodedURL + Consts.url2, "tracks");
}
#Override
protected void onPostExecute(ArrayList<Track> trackss) {
super.onPostExecute(trackss);
DataHolder.getInstance().setTracks(trackss);
adapterExploreListView = new AdapterExploreListView(NewList.this, trackss);
tracks = trackss;
newListView.setAdapter(adapterExploreListView);
}
}.execute();
}
I solved my problem ,these are the edits .I hope it will help someone else !
on the new list .class
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View view,
int position, long arg3) {
TextView textView4 = (TextView)view.findViewById(R.id.titleTextView);
TextView textView5 = (TextView)view.findViewById(R.id.userNameTextView);
n =textView4.getText().toString();
m=textView5.getText().toString();
MyObject=new CustomObject(n,m);
sharedPreference = new SharedPreference();
sharedPreference.addFavorite(NewList.this, MyObject);
Toast.makeText(NewList.this,
NewList.this.getResources().getString(R.string.add_favr),
Toast.LENGTH_SHORT).show();
return true;
}
}
the favorites activity *
public class FavActivity extends Activity {
ListView lv;
SharedPreference sharedPreference;
List<CustomObject> favorites;
ProductListAdapter productListAdapter;
Activity context = this;
public static final String FAVORITES = "Favorite";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.forthact);
sharedPreference = new SharedPreference();
favorites = sharedPreference.getFavorites(context);
lv = (ListView) findViewById(R.id.forthlistview);
fillFavoriteList();
}
private void fillFavoriteList() {
if (favorites != null) {
productListAdapter = new ProductListAdapter(ForthActivity.this, favorites);
lv.setAdapter(productListAdapter);
productListAdapter.notifyDataSetChanged();
}
}
}
the SharedPreferences class
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<CustomObject> favorites) {
SharedPreferences settings;
SharedPreferences.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, CustomObject product) {
List<CustomObject> favorites = getFavorites(context);
String s=product.getProp1();
if (favorites == null)
favorites = new ArrayList<CustomObject>();
favorites.add(product);
saveFavorites(context, favorites);
}
public void removeFavorite(Context context, CustomObject product) {
ArrayList<CustomObject> favorites = getFavorites(context);
if (favorites != null) {
favorites.remove(product);
saveFavorites(context, favorites);
}
}
public ArrayList<CustomObject> getFavorites(Context context) {
SharedPreferences settings;
List<CustomObject> favorites;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
if (settings.contains(FAVORITES)) {
String jsonFavorites = settings.getString(FAVORITES, null);
Gson gson = new Gson();
CustomObject[] favoriteItems = gson.fromJson(jsonFavorites,
CustomObject[].class);
favorites = Arrays.asList(favoriteItems);
favorites = new ArrayList<CustomObject>(favorites);
} else
return null;
return (ArrayList<CustomObject>) favorites;
}
}

Categories

Resources