set SharedPreferences name dynamically - android

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

Related

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

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.

How to view RecyclerView items sorted by ID?

In my app i have something like a menu that load data stored in SharedPreferences to a Constructor and build from it 2 RecyclerView's.
Now i want to make that if i press an button from the bottom recyclerView like "CICCIO" that has in it constructor item like ID set by 1 i would that in the other recyclerView where there are a lot of colored buttons to be visualized just button's that have also ID set by 1 in their constructor but i'm not very in to android and i can't get how can i make a "sort method" like that.
I have yet the onClick method set on bottom RecyclerView and i have yet method's getID from the bottom recyclerView constructor and getID from the top RecyclerView.
ACTIVITY SCREENSHOT HERE
And here is the code from my activity:
// Builder del BOTTOM recyclerView
public void buildRecyclerViewMenu(){
RecyclerView mRecyclerView = findViewById(R.id.recyclerViewMenu);
mRecyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL, false);
RecyclerViewMenu recyclerViewMenu = new RecyclerViewMenu(menuConstructors);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(recyclerViewMenu);
recyclerViewMenu.setOnItemClickListener(new RecyclerViewMenu.OnItemClickListener() {
#Override
public void onItemClick(int position) {
}
});
}
// Builder del TOP recyclerView
public void buildRecyclerView(){
mRecyclerViewBOT = findViewById(R.id.recyclerView);
mRecyclerViewBOT.setHasFixedSize(true);
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(this, 4);
Adapter mAdapter = new Adapter(items);
mRecyclerViewBOT.setLayoutManager(mLayoutManager);
mRecyclerViewBOT.setAdapter(mAdapter);
mAdapter.setOnItemClickListener(new Adapter.OnItemClickListener() {
#SuppressLint("SetTextI18n")
#Override
public void onItemClick(final int position) {
}
});
}
While here are the method's where i load data to Bottom and top RecyclerView
private void loadDataMenu(){
new ArrayList<MenuConstructor>();
SharedPreferences sharedPreferences = getSharedPreferences("MENU_SAVE", MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("menu list",null);
Type type = new TypeToken<ArrayList<MenuConstructor>>() {}.getType();
menuConstructors = gson.fromJson(json, type );
if(menuConstructors == null){
menuConstructors = new ArrayList<>();
Toast.makeText(cassa.this,"NESSUN TASTO DA VISUALIZZARE" ,Toast.LENGTH_SHORT).show();
}
}
private void loadDataTasti(){
new ArrayList<Item>();
SharedPreferences sharedPreferences = getSharedPreferences("TASTI_SAVE", MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("tasti list",null);
Type type = new TypeToken<ArrayList<Item>>() {}.getType();
items = gson.fromJson(json, type );
if(items == null){
items = new ArrayList<>();
Toast.makeText(cassa.this,"NESSUN TASTO DA VISUALIZZARE" ,Toast.LENGTH_SHORT).show();
}
}
While here is my Item.java that is the model class of TOP recycler View:
public class Item {
private int menu;
private String tipo;
private String codice;
private String deskT;
private String deskS;
private String sfondo;
private String font;
private String qta;
private double pre;
Item(int id, String typo, String codice_t, String desk_T,String desk_S,String sfondo_c,String font_c,String quant,double prezzo){
menu = id;
tipo = typo;
codice = codice_t;
deskT = desk_T;
deskS = desk_S;
sfondo = sfondo_c;
font = font_c;
qta = quant;
pre = prezzo;
}
public int getMenu(){return menu;}
public String getTipo(){return tipo;}
public String getCodice(){return codice;}
public String getDeskT(){return deskT;}
public String getDeskS(){return deskS;}
public String getSfondo(){return sfondo;}
public String getFont(){return font;}
public String getQuant(){return qta;}
public double getPrice(){return pre;}
}
And here is the model of MenuConstructor (bottom recyclerView)
public class MenuConstructor {
int id;
private String deskT;
private String sfondo;
private String font;
MenuConstructor(int idID,String Desk,String Sfondo,String Font){
id = idID;
deskT = Desk;
sfondo = Sfondo;
font = Font;
}
public int getBtnID(){
return id;
}
public String getDesk(){
return deskT;
}
public String getSfondoColor(){
return sfondo;
}
public String getFontColor(){
return font;
}
}
so i want to compare the id from MenuConstructor with menu (id) from the Item.java and show just item with a certain ID.
You can using Collections.sort()
private List<Item> getSortedItems(List<Item> items) {
Collections.sort(items, new Comparator<Item>() {
#Override
public int compare(Item item, Item nextItem) {
return ComparisonChain.start()
.compare(item.getMenu(), nextItem.getMenu())
.result();
}
});
return items;
}
this method will return the item list sort by menu
hope this helps
Solved by creating a new ArrayList and comparing the item.getMenu() with menuConstructors.getBtnID() in a for cycle which scrolls for the same lenght of the ArrayList.
recyclerViewMenu.setOnItemClickListener(new RecyclerViewMenu.OnItemClickListener() {
#Override
public void onItemClick(int position) {
Toast.makeText(cassa.this,String.valueOf(menuConstructors.get(position).getBtnID()),Toast.LENGTH_SHORT).show();
ArrayList<Item> filteredList = new ArrayList<>();
for(Item item : items) {
if(item.getMenu() == menuConstructors.get(position).getBtnID() ) {
filteredList.add(item);
}
}
mAdapter.filterList(filteredList);
}
});

Get the sharedpreference data in an adapter

Googled and tried my whole day about getting the sharedpreference data in my adapter. I have an SharedPreferenceManager class
public class SharedPrefManager {
static SharedPreferences sharedPreferences;
static Context mContext;
static int PRIVATE_MODE = 0;
private static final String PREF_NAME = "sessionPref";
static SharedPreferences.Editor editor;
public SharedPrefManager (Context context) {
mContext = context;
sharedPreferences = mContext.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = sharedPreferences.edit();
}
public void saveUID(Context context,String uid){
mContext = context;
sharedPreferences = mContext.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("UID", uid);
editor.commit();
}
public String getUID(){
sharedPreferences = mContext.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
return sharedPreferences.getString("UID", "");
}
public void clear(){
editor.clear();
editor.apply();
}
}
I call the SharedPrefManager in any activity like this
public SharedPrefManager sharedPrefManager;
public String uid
and in onCreate()
sharedPrefManager = new SharedPrefManager(mContext);
uid = sharedPrefManager.getUID();
now, how to get the same data in an adapter since the below code gives error in any adapter
SharedPrefManager sharedPrefManager = new SharedPrefManager(context);
public String uid = sharedPrefManager.getUID();
Here is my Adapter Class
public class MyCommentAdapter extends RecyclerView.Adapter<MyCommentAdapter.MyCommentHolder> {
Context context;
private List<MyComment> commentList;
//Here I get the null pointer error
SharedPrefManager sharedPrefManager = new SharedPrefManager(context);
public String uid = sharedPrefManager.getUID();
private DatabaseReference mDatabaseReference1=FirebaseDatabase.getInstance().getReference().child("User").child(uid).child("Comment");
int the Last line of code I want to access the database with the uid, that is why I need the uid value from shared preference
public MyCommentAdapter(Context context, List<MyComment> commentList) {
this.context = context;
this.commentList = commentList;
}
Your context is null. Try after assigning it
SharedPrefManager sharedPrefManager ;
public String uid ;
private DatabaseReference mDatabaseReference1;
public MyCommentAdapter(Context context, List<MyComment> commentList) {
this.context = context;
sharedPrefManager = new SharedPrefManager(context);
this.commentList = commentList;
uid = sharedPrefManager.getUID();
mDatabaseReference1=FirebaseDatabase.getInstance().getReference().child("User").child(uid).child("Comment");
}
First of all it's not a right thing to this kind of things inside of your RecyclerView adapter, it slows down you scrolling performance and it's violating SRP.
BUT
you can simply inject you SharedPrefManager into you adapter :
public class MyCommentAdapter extends RecyclerView.Adapter<MyCommentAdapter.MyCommentHolder> {
private Context context;
private List<MyComment> commentList;
private SharedPrefManager sharedPrefManager;
public String uid;
public MyCommentAdapter(Context context, List<MyComment> commentList, SharedPrefManager sharedPrefManager) {
this.context = context;
this.commentList = commentList;
this.sharedPrefManager = sharedPrefManager
this.uid = sharedPrefManager.getUID();
}
}
and then in your activity when you are creating the adapter you can inject sharedPrefManager in it's constructor.
you need to initialize your sharedPreferancne class in the constructor of the adpater. Something like this:
private CustomSharedPreferences customSharedPreferences;
and then in your constructor:
public MyCommentAdapter(Context context, List<MyComment> commentList)
{
this.context = context;
this.customSharedPrefernces = new CustomSharedPreferences(context);
this.commentList = commentList;
}
public class SP {
/**
* #param mContext
* #param key
* #param value
*/
public static void savePreferences(Context mContext, String key, String value) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value).apply();
}
/**
* #param context
* #param keyValue
* #return
*/
public static String getPreferences(Context context, String keyValue) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
return sharedPreferences.getString(keyValue, "");
}
/**
* #param mContext
*/
public static void removeAllSharedPreferences(Context mContext) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear().apply();
}
}

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

Fragment's Context gets "lost" while passing it as a parameter

I came across a very awkward behaviour in my fragment.
The output is:
this.userID: 0
and
RoomChatFragment userID: 14
But in this case, this.userID should also be 14. Is my context lost somewhere, while passing it as a parameter? I can't explain myself this behaviour. I don't think getActivity() returns null, otherwise there would be an exception.
// Fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
context = getActivity();
user = new UserHandler(context);
messageDatabase = MessageDatabase.getInstance(context);
Log.i("debug", "RoomChatFragment userID: " + user.getUserID());
}
// UserHandler
public class UserHandler {
private final SharedPreferences sharedPrefs;
private final SharedPreferences sharedPrefsPreferences;
private Context context;
public UserHandler(Context context) {
sharedPrefs = context.getSharedPreferences("USER", 0);
sharedPrefsPreferences = PreferenceManager.getDefaultSharedPreferences(context);
this.context = context;
}
public int getUserID() {
return sharedPrefs.getInt("userID", 0);
}
public void setUserID(int userID) {
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putInt("userID", userID);
editor.apply();
}
}
// Database
public class MessageDatabase extends AbstractDatabase {
private int userID;
protected static MessageDatabase instance;
public MessageDatabase(Context context) {
super(context);
UserHandler user = new UserHandler(context);
userID = user.getUserID();
}
public static MessageDatabase getInstance(Context context) {
if (MessageDatabase.instance == null) {
MessageDatabase.instance = new MessageDatabase(context);
}
return MessageDatabase.instance;
}
// ....
#Override
protected Message cursorToObject(Cursor cursor) {
Log.i("debug", "this.userID: " + this.userID);
}
}
// AbstractDatabase
public abstract class AbstractDatabase {
protected Context context;
protected AbstractDatabase(Context context) {
this.context = context;
}
}
I'm not absolutely sure what's going on here (your code is really messy). But it seems you're using a different key for the preference:
context.getSharedPreferences("USER", 0);
sharedPrefs.getInt("userID", 0);
Stupid me! The problem is the singleton design pattern of my database design. My MessageDatabase.instance is cached and holds an old Context object, where the userID of my SharedPreferences is 0.
I've updated my method like this and it seems to work:
public static MessageDatabase getInstance(Context context) {
if (MessageDatabase.instance == null || userID == 0) {
MessageDatabase.instance = new MessageDatabase(context);
}
return MessageDatabase.instance;
}

Categories

Resources