When Deleting View with Swipe in RecyclerView doesn't deletin in SharedPreference - android

I am trying delete View with Swipe in RecylerView, I saved in SharedPreferences to selected View with favorite button. After I saved to selected View in SharedPreferences, I am trying remove Favorite Activity with Swipe to left ,I was done this but When I return Favorite Activity, I saw old items doesn't updated SharedPreferences When I swipe to left.
How can I do this?
public class SharedPreference {
public static final String PREFS_NAME = "NKDROID_APP";
public static final String FAVORITES = "Favorite";
public SharedPreference() {
super();
}
public void storeFavorites(Context context, List<OrderModel> 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 ArrayList<OrderModel> loadFavorites(Context context) {
SharedPreferences settings;
List<OrderModel> favorites;
settings = context.getSharedPreferences(PREFS_NAME,Context.MODE_PRIVATE);
if (settings.contains(FAVORITES)) {
String jsonFavorites = settings.getString(FAVORITES, null);
Gson gson = new Gson();
OrderModel[] favoriteItems = gson.fromJson(jsonFavorites,OrderModel[].class);
favorites = Arrays.asList(favoriteItems);
favorites = new ArrayList<OrderModel>(favorites);
} else
return null;
return (ArrayList<OrderModel>) favorites;
}
public void addFavorite(Context context, OrderModel beanSampleList) {
List<OrderModel> favorites = loadFavorites(context);
if (favorites == null)
favorites = new ArrayList<OrderModel>();
favorites.add(beanSampleList);
storeFavorites(context, favorites);
}
public void removeFavorite(Context context, OrderModel beanSampleList) {
ArrayList<OrderModel> favorites = loadFavorites(context);
if (favorites != null) {
favorites.remove(beanSampleList);
storeFavorites(context, favorites);
}
}
/*
public void saveHighScoreList(String scoreString) {
editor.putString(FAVORITES, scoreString);
editor.commit();
}
public String getHighScoreList() {
return settings.getString(FAVORITES, "");
}
*/
}
#Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction, int position) {
if (viewHolder instanceof OrderAdapter.OrderViewHolder) {
// get the removed item name to display it in snack bar
String name = order_models.get(viewHolder.getAdapterPosition()).getOrder_name();
final OrderModel deletedItem = order_models.get(viewHolder.getAdapterPosition());
final int deletedIndex = viewHolder.getAdapterPosition();
order_adapter.removeItem(viewHolder.getAdapterPosition());
//remove from shared preferences
sharedPreference.removeFavorite(Orders.this, deletedItem);
order_models.remove(deletedItem);
order_adapter.notifyDataSetChanged();
Toast.makeText(Orders.this, "Success Remove",Toast.LENGTH_SHORT).show();
// showing snack bar with Undo option
Snackbar snackbar = Snackbar
.make(constraint, name + " removed from cart!", Snackbar.LENGTH_LONG);
snackbar.setAction("UNDO", new View.OnClickListener() {
#Override
public void onClick(View view) {
// undo is selected, restore the deleted item
order_adapter.restoreItem(deletedItem, deletedIndex);
}
});
snackbar.setActionTextColor(Color.YELLOW);
snackbar.show();
}
}

For one, you probably shouldn't be loading the list of favorites from preferences every single time you want to query or modify the list. Instead, query it once when the Activity this RecyclerView belongs to is created (you could do that from the Adapter itself or from the Activity), and store that to a global variable. ie:
class SomeActivity extends Activity {
private ArrayList<OrderModel> favorites = new ArrayList<>();
private SharedPreference prefsHelper = new SharedPreference();
#Override
public void onCreate(Bundle savedInstanceState) {
//....
favorites.addAll(prefsHelper.loadFavorites(this));
}
}
Then, when you want to change something, modify that ArrayList and then save it directly:
public void addFavorite(OrderModel model) {
favorites.add(model);
prefsHelper.storeFavorites(this, favorites);
}
You'll probably need to modify this to fit your code, but it's an example of what to do.
What you currently have won't work, because every time you go to modify the list, you're recreating it from a String representation. That means that the list of favorites you have loaded contains completely different instances of the models, even if they contain the same values.
When you pass an OrderModel to your removeFavorite() method, it's not going to remove anything, because nothing is equal; by reloading the list, you have completely fresh instances.
If you really want to keep your current code structure, switch to indexes instead of passing the object. Or, override equals() in OrderModel and have it manually compare the values, so even different instances can be matched.

Related

Arraylist is showing only 1 value in android?

I have a listview in which i am getting data set and saving value from data set into another arraylist and save them in shared preference and getting same arraylist in another activity . But problem is that Arraylist is always showing only 1 value. Pls help me out to resolve.
code:-
//here i am adding items to another arraylist
ArrayList<WhiteListModel> res = new ArrayList<WhiteListModel>();
WhiteListModel whiteListModel = new WhiteListModel();
whiteListModel.setName(listStorage.get(position).getName());
whiteListModel.setPackName(listStorage.get(position).getPackName());
res.add(whiteListModel);
saveScoreListToSharedpreference(res);
/**
* Save list of scores to own sharedpref
*
* #param scoresList
*/
private void saveScoreListToSharedpreference(ArrayList<WhiteListModel> scoresList) {
sharedPreference = new MySharedPreference(mContext);
Gson gson = new Gson();
//convert ArrayList object to String by Gson
String jsonScore = gson.toJson(scoresList);
Log.e(TAG, "LIST::" + jsonScore);
//save to shared preference
sharedPreference.saveHighScoreList(jsonScore);
}
code for MySharedPreference
private SharedPreferences pref;
private SharedPreferences.Editor editor;
// Context
private Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Sharedpref file name
private static final String PREF_NAME = "pref";
private static final String SCORES = "scores";
public MySharedPreference(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void saveHighScoreList(String scoreString) {
editor.putString(SCORES, scoreString);
editor.commit();
}
public String getHighScoreList() {
return pref.getString(SCORES, "");
}
}
code of SwitchCompatButton
listViewHolder.switchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(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) {
ArrayList<WhiteListModel> res = null;
for (int position = 0; position < listStorage.size(); position++) {
//here i am adding items to another arraylist
res = new ArrayList<WhiteListModel>();
WhiteListModel whiteListModel = new WhiteListModel();
whiteListModel.setName(listStorage.get(position).getName());
whiteListModel.setPackName(listStorage.get(position).getPackName());
res.add(whiteListModel);
}
saveScoreListToSharedpreference(res);
listStorage.remove(position);
notifyDataSetChanged();
listViewHolder.switchCompat.setChecked(false);
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
listViewHolder.switchCompat.setChecked(false);
}
}).show();
}
}
});
When you add multiple elements to the array list using a loop please remember to instantiate the object again.
for(int position=0;position<10;position++){
WhiteListModel whiteListModel = new WhiteListModel(); //has to be done repeatedly
whiteListModel.setName(listStorage.get(position).getName());
whiteListModel.setPackName(listStorage.get(position).getPackName());
res.add(whiteListModel);
}
You are adding only one item to array list so you retrieve only one item. You should add more items to it. You can do it in following way.
ArrayList<WhiteListModel> res = new ArrayList<WhiteListModel>();
for(int i = 0; i < listStorage.size(); i++){
WhiteListModel whiteListModel = new WhiteListModel();
whiteListModel.setName(listStorage.get(i).getName());
whiteListModel.setPackName(listStorage.get(i).getPackName());
res.add(whiteListModel);
saveScoreListToSharedpreference(res);
}
You are inserting only one value, you are not using loop to insert value. you have to change code like this.
for(int position=o;position<listStorage.size;position++)
{
ArrayList<WhiteListModel> res = new ArrayList<WhiteListModel>();
WhiteListModel whiteListModel = new WhiteListModel();
whiteListModel.setName(listStorage.get(position).getName());
whiteListModel.setPackName(listStorage.get(position).getPackName());
res.add(whiteListModel);
}
itemtext.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
menuEnquiryCartBean = new MenuEnquiryCartBean();
itemList.add(menuEnquirycartBean.getName());
// itemList.add(mainList.get(i).getName());
buttonView.setChecked(true);
Toast.makeText(context, buttonView.getText().toString(), Toast.LENGTH_SHORT).show();
} else {
itemList.remove(buttonView.getText().toString());
buttonView.setChecked(false);
Toast.makeText(context, buttonView.getText().toString(), Toast.LENGTH_SHORT).show();
}
}
});

set SharedPreferences name dynamically

I'm using this sequence for designing an app:
(This classes will not change and I'm gonna use them for multiple activities)
Custom adapter
Model Class
Shared Preferences
And Activity with tab Layouts(with two Fragments) wich contains:
I'm gonna name this: (Package #1)
MainActivity
Fragment One
Fragment Two
Now I want to duplicate Package #1 and change some contents then name it as Package #2. But I have a problem here.
I'm using one shared preferences for Package #1, Package #2, Package #3..., right?
please have a look into my shared preferences class:
public class SharedPreference_light {
private SharedPreferences settings;
private SharedPreferences.Editor editor;
private Gson gson = new Gson();
private static final String PREFS_NAME = "Light_Products";
private static final String FAVORITES = "Favorite_Tones_Light";
public SharedPreference_light(Context context) {
settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
editor = settings.edit();
}
private void saveFavorites(List<ProductLocal> favorites) {
String jsonFavorites = gson.toJson(favorites);
editor.putString(FAVORITES, jsonFavorites);
editor.apply();
}
public void addFavorite(ProductLocal product) {
List <ProductLocal> favorites = getFavorites();
if (favorites == null)
favorites = new ArrayList<>();
favorites.add(product);
saveFavorites(favorites);
}
public void removeFavorite(ProductLocal product) {
ArrayList <ProductLocal> favorites = getFavorites();
if (favorites != null) {
favorites.remove(product);
saveFavorites(favorites);
}
}
public ArrayList <ProductLocal> getFavorites() {
List<ProductLocal> favorites;
if (settings.contains(FAVORITES)) {
String jsonFavorites = settings.getString(FAVORITES, null);
ProductLocal[] favoriteItems = gson.fromJson(jsonFavorites, ProductLocal[].class);
favorites = Arrays.asList(favoriteItems);
favorites = new ArrayList <> (favorites);
} else
return null;
return (ArrayList <ProductLocal> ) favorites;
}
}
The problem is if I use this two variables:
private static final String PREFS_NAME = "Light_Products";
private static final String FAVORITES = "Favorite_Tones_Light";
There will be a conflict between those packages. because I'm going to add some list items into shared preferences and use getSharedPreferences. then all those items from multiple packages will be added into one shared preferences, and I don't want that.
Now my real question would be:
How can I set shared preferences names(variables) dynamically?
Note:
I have one usage of shared preferences in custom adapter:
private boolean checkFavoriteItem(ProductLocal checkProduct) {
boolean check = false;
List<ProductLocal> favorites = sharedPreference.getFavorites();
if (favorites != null) {
for (ProductLocal product : favorites) {
if (product.equals(checkProduct)) {
check = true;
break;
}
}
}
return check;
}
Adapter:
public class LocalAdapter extends RecyclerView.Adapter<LocalAdapter.MyViewHolder>{
private SharedPreference_light sharedPreference;
public LocalAdapter(Activity activity, List<ProductLocal> dataList, RelativeLayout snackLayout) {
this.snackLayout=snackLayout;
this.activity = activity;
this.dataList = dataList ;
this.dataListFilter = dataList ;
sharedPreference = new SharedPreference_light(activity);
methods = new Methods(activity);
}
first you would like to use an interface providing the package name:
public interface LightPrefs {
String getPackageName();
}
Secondly, you can reuse your class and make it implementing the previous interface but making it abstract:
public abstract class SharedPreference_light implements LightPrefs {
private SharedPreferences settings;
private SharedPreferences.Editor editor;
protected final String PREFS_NAME = "Light_Products_" + getPackageName();
protected final String FAVORITES = "Favorite_Tones_Light_" + getPackageName();
public SharedPreference_light(Context context) {
settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
editor = settings.edit();
}
private void saveFavorites(List<ProductLocal> favorites) {
String jsonFavorites = gson.toJson(favorites);
editor.putString(FAVORITES, jsonFavorites);
editor.apply();
}
public void addFavorite(ProductLocal product) {
List <ProductLocal> favorites = getFavorites();
if (favorites == null)
favorites = new ArrayList<>();
favorites.add(product);
saveFavorites(favorites);
}
public void removeFavorite(ProductLocal product) {
ArrayList <ProductLocal> favorites = getFavorites();
if (favorites != null) {
favorites.remove(product);
saveFavorites(favorites);
}
}
}
Especially pay attention to some visibility modifiers that have changed.
And finally extend this abstract class in your packages:
public class SharedPreference_package1 extends SharedPreference_light {
private static final String TAG = "SharedPref_package1";
public SharedPreference_package1(Context context) {
super(context);
Log.d(TAG, PREFS_NAME);
}
#Override
public String getPackageName() {
return "package#1";
}
}
and:
public class SharedPreference_package2 extends SharedPreference_light {
private static final String TAG = "SharedPref_package2";
public SharedPreference_package2(Context context) {
super(context);
Log.d(TAG, PREFS_NAME);
}
#Override
public String getPackageName() {
return "package#2";
}
}
Instantiating both of these classes gives you this log:
D/SharedPref_package1: Light_Products_package#1
D/SharedPref_package2: Light_Products_package#2
About the adapter, I think you should specify the shared preference object upon construction:
public class LocalAdapter extends RecyclerView.Adapter<LocalAdapter.MyViewHolder>{
private SharedPreference_light sharedPrefs;
public LocalAdapter(Activity activity, List<ProductLocal> dataList, RelativeLayout snackLayout, SharedPreference_light sharedPrefs) {
this.snackLayout=snackLayout;
this.activity = activity;
this.dataList = dataList ;
this.dataListFilter = dataList ;
this.sharedPrefs = sharedPrefs;
methods = new Methods(activity);
}
So you can initialise your adapter like this in package #1:
SharedPreference_package1 sharedPrefs = new SharedPreference_package1();
LocalAdapter adapter = new LocalAdapter(activity, dataList, snackLayout, sharedPrefs);
And you can adapt with SharedPreference_package2 in the second package.
Hope this will help you.
Make your all methods takes shared preferences key as parameter like:
public SharedPreference_light(Context context, String name);
private void saveFavorites(List<ProductLocal> favorites, String name);
public void addFavorite(ProductLocal product, String name);
public void removeFavorite(ProductLocal product, String name);
public ArrayList <ProductLocal> getFavorites(String name);

sharedpreference return whole list not the one seleected in card

I have two activities one is "products" and the other is "cart", I used sharedpreferences to save the selected product and display it in the cart activity, the problem is when I press on add to cart the whole list of products is displayed not just the selected product
my products Adapter
public class productsAdapter extends RecyclerView.Adapter<productsAdapter.MyViewHolder> {
private Context mContext;
private List<products> productList;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title, count;
public ImageView thumbnail, cart;
private Context context;
public MyViewHolder(View view) {
super(view);
context = itemView.getContext();
title = (TextView) view.findViewById(R.id.title);
count = (TextView) view.findViewById(R.id.count);
thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
cart = (ImageView) view.findViewById(R.id.cart);
}
}
public productsAdapter(Context mContext, List<products> productList) {
this.mContext = mContext;
this.productList = productList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.products_card, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
final products p = productList.get(position);
holder.title.setText(p.getName());
holder.count.setText(p.getPrice() + "L.E");
Glide.with(mContext).load(p.getThumbnail()).into(holder.thumbnail);
holder.thumbnail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), product_details.class);
Bundle bundle = new Bundle();
bundle.putString("img", p.getThumbnail());
bundle.putString("name", p.getName());
bundle.putInt("price", p.getPrice());
intent.putExtras(bundle);
v.getContext().startActivity(intent);
}
});
holder.cart.setImageResource(R.drawable.ic_shopping_cart_black_24dp);
holder.cart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.cart.setImageResource(R.drawable.ic_add_cart);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mContext);
SharedPreferences.Editor editor = preferences.edit();
Gson gson = new Gson();
String jsonFavorites = gson.toJson(productList);
editor.putString(FAVORITES, jsonFavorites);
editor.commit();
}
});
}
public int getItemCount() {
return productList.size();
}
}
my cart activity
public class CartActivity extends AppCompatActivity {
Button l;
ImageView imv;
Toolbar t;
RecyclerView rv;
RecyclerView.LayoutManager layoutmanager;
RecyclerView.Adapter adapter;
List<products> cartitems;
ArrayList<products> selected_items_list = new ArrayList<>();
SharedPreference sharedPreference;
public static final String MyPREFERENCES = "MyPrefs";
int countt = 0;
boolean edit_mode = false;
TextView counterr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
rv = (RecyclerView) findViewById(R.id.mycartrecycler);
layoutmanager = new LinearLayoutManager(this);
rv.setLayoutManager(layoutmanager);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String jsonFavorites = preferences.getString(FAVORITES, null);
Gson gson = new Gson();
products[] favoriteItems = gson.fromJson(jsonFavorites,
products[].class);
cartitems = Arrays.asList(favoriteItems);
cartitems = new ArrayList<products>(cartitems);
adapter = new CartAdapter(cartitems, CartActivity.this);
rv.setAdapter(adapter);
}
}
Because you add the whole list in sharedpreferences.. look at below
you did this...
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mContext);
SharedPreferences.Editor editor = preferences.edit();
Gson gson = new Gson();
String jsonFavorites = gson.toJson(productList);
1) if you want the specific selected result then you have to make a pojo class of product with the contain details like
public TextView title, count;
public ImageView thumbnail, cart;
private Context context;
and make getter and setter method of all fields.
in onclick method of cart,you have to pass that pojo class and get that class in your cart activity. that's how you can get your desire output.
2) the second way to add all details as a field of sharedpreferences like
editor.putString("title",title.getText().toString());
and set all count and thumbnail as an value.
I hope it will help you...
You are saving productList in SharedPreference.
Try like this
final Product product = productList.get(position);
// Some other code
holder.cart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.cart.setImageResource(R.drawable.ic_add_cart);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mContext);
SharedPreferences.Editor editor = preferences.edit();
Gson gson = new Gson();
String jsonFavorites = gson.toJson(product);
editor.putString(FAVORITES, jsonFavorites);
editor.commit();
}
});
In CartActivity
Gson gson = new Gson();
Product product = gson.fromJson(jsonFavorites,
Product.class);

Maintain Drag & Dropped items position when restarting

I have a RecyclerView - Grid, with drag & drop, using this code I've manage to achieve that, And made a lot of changes, only one problem, i can't save the dragged items position on restarting ( the app not the phone ).
What i thought about is adding " int position " to my item.java constructor, but what i can't do is getting the changed position .
I'm using the same drag & drop codes provided in the link.
ItemTouchHelper.Callback _ithCallback = new ItemTouchHelper.Callback() {
//and in your imlpementaion of
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
// get the viewHolder's and target's positions in your adapter data, swap them
Collections.swap(AllItems, viewHolder.getAdapterPosition(), target.getAdapterPosition());
// and notify the adapter that its dataset has changed
rcAdapter.notifyItemMoved(viewHolder.getAdapterPosition(), target.getAdapterPosition());
return true;
}
#Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
//TODO
}
//defines the enabled move directions in each state (idle, swiping, dragging).
#Override
public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
return makeFlag(ItemTouchHelper.ACTION_STATE_DRAG,
ItemTouchHelper.DOWN | ItemTouchHelper.UP | ItemTouchHelper.START | ItemTouchHelper.END);
}
};
Here's the code in onCreate :
ItemTouchHelper ith = new ItemTouchHelper(_ithCallback);
ith.attachToRecyclerView(RcView);
Getting Duplicated items after position changing, Code :
#Override
public void onStop()
{
super.onStop();
SharedPreferencesTools.setOrderedItems(this, AllItems);
}
getAllItemList :
private List<Item> getAllItemList(){
AllItems = SharedPreferencesTools.getOrderedItems(this);
//Add item .. etc
//return items
}
Just keep your modified collection AllItems in SharedPreferences and load it on the app start & store it back, once you get out of the app.
To do this, you need to serialize your collection to json by Gson and store as a String. And then deserialize it afterwards:
public final class SharedPreferencesTools {
private static final String USER_SETTINGS_PREFERENCES_NAME = "UserSettings";
private static final String ALL_ITEMS_LIST = "AllItemsList";
private static Gson gson = new GsonBuilder().create();
public static List<Item> getOrderedItems(Context context) {
String stringValue = getUserSettings(context).getString(ALL_ITEMS_LIST, "");
Type collectionType = new TypeToken<List<Item>>() {
}.getType();
List<Item> result = gson.fromJson(stringValue, collectionType);
return (result == null) ? new ArrayList<Item>() : result;
}
public static void setOrderedItems(Context context, List<Item> items) {
String stringValue = gson.toJson(items);
SharedPreferences sharedPreferences = getUserSettings(context);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(ALL_ITEMS_LIST, stringValue);
editor.apply();
}
static SharedPreferences getUserSettings(Context context) {
return context.getSharedPreferences(USER_SETTINGS_PREFERENCES_NAME, Context.MODE_PRIVATE);
}
}
The usage of these two methods:
SharedPreferencesTools.setOrderedItems(getActivity(), AllItems);
...
List<Item> AllItems = SharedPreferencesTools.getOrderedItems(getActivity());

Checkbox SharedPreference Not working in Recyclerview Checkbox

I was trying to implement SharedPreference for storing checkbox checked list in my RecyclerView adapter.
I am able to Log checked list arrays correctly. but I am not able to save it to shared preference and restore it when app reopens every time.
Here is my RecyclerView adapter code.
public class HomeManager extends RecyclerView.Adapter<HomeManager.RecyclerViewHolder> {
private static DisplayImageOptions displayOptions;
static View v1;
private SparseBooleanArray mCheckedItems = new SparseBooleanArray();
static {
displayOptions = DisplayImageOptions.createSimple();
}
public static class RecyclerViewHolder extends RecyclerView.ViewHolder {
CheckBox mCheck;
RecyclerViewHolder(final View itemView) {
super(itemView);
mCheck = (CheckBox) itemView.findViewById(R.id.PROJECT_fav);
SharedPreferences update = v1.getContext().getSharedPreferences("my_prefs", 0);
String Check = update.getString("Check", "");
Log.e("Checked Array = ", Check);
}
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
v1 = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recyclerview_item, viewGroup, false);
return new RecyclerViewHolder(v1);
}
#Override
public void onBindViewHolder(final RecyclerViewHolder viewHolder, int i) {
// viewHolder.mCheck.setChecked(mCheckedItems);
viewHolder.mCheck.setChecked(mCheckedItems.get(i));
viewHolder.mCheck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
Snackbar snackbar = Snackbar.make(viewHolder.itemView, "Item Favorited", Snackbar.LENGTH_SHORT);
snackbar.show();
} else {
Snackbar snackbar = Snackbar.make(viewHolder.itemView, "Item Unfavorited", Snackbar.LENGTH_SHORT);
snackbar.show();
}
int position = viewHolder.getAdapterPosition();
mCheckedItems.put(position, isChecked);
List<Integer> selected = new ArrayList<>();
for (int i = 0; i < mCheckedItems.size(); i++) {
final boolean checked = mCheckedItems.valueAt(i);
if (checked) {
selected.add(mCheckedItems.keyAt(i));
}
}
Log.e("Checked Array = ", String.valueOf(selected));
SharedPreferences prefs = v1.getContext().getSharedPreferences("my_prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor edit = prefs.edit();
edit.putString("Checkbox", String.valueOf(selected));
edit.commit();
Log.e("Shared Preference = ", String.valueOf(edit));
}
});
}
The problem is simple - you have to store and access with the same key.
You are currently trying to access your stored data with the key "Check":
SharedPreferences update = v1.getContext().getSharedPreferences("my_prefs", 0);
String Check = update.getString("Check", "");
But you're storing it with the key "Checkbox":
SharedPreferences prefs = v1.getContext().getSharedPreferences("my_prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor edit = prefs.edit();
edit.putString("Checkbox", String.valueOf(selected));
edit.commit();
Either use "Check" or "Checkbox" for both! You can't mix and match.
You have put trh string in shared preferences as Checkbox
edit.putString("Checkbox", String.valueOf(selected));
But you are getting the string called Check
SharedPreferences update = v1.getContext().getSharedPreferences("my_prefs",0);
String Check = update.getString("Check", "");
Change it to
String Check = update.getString("Checkbox", "");

Categories

Resources