Arraylist is showing only 1 value in android? - 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();
}
}
});

Related

Add item in ArrayListAdapter from another activity Using SharedPreferences

I want to add some elements from MainActivity to another activity, where I have an arrayList but my problem is that, When I insert something the deal is done, but is added only 1 element. I want to add multiple elements to the arrayList. In MainActivity i have 2 EditText and 2 buttons(Save and GoToNextActivity where i put an intent for a transition from the MainActivity to the list.class) What can i do to adding more elements to the list when i press the save button?
public class items {
private String username;
private String password;
items(String user,String parola){
username=user;
password=parola;
}
public String getPassword() {
return password;
}
public String getUsername() {
return username;
}
}
public class itemsAdapter extends ArrayAdapter<items> {
private static final String LOG_TAG = itemsAdapter.class.getSimpleName();
public itemsAdapter(Activity context, ArrayList<items> item) {
super(context, 0,item);
}
public View getView(int position, View convertView, ViewGroup parent){
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(R.layout.list_items, parent, false);
}
items curentItems=getItem(position);
TextView user=(TextView)listItemView.findViewById(R.id.list_user);
TextView password=(TextView)listItemView.findViewById(R.id.list_password);
user.setText(curentItems.getUsername());
password.setText(curentItems.getPassword());
return listItemView;
}
}
public class list extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
SharedPreferences sharedPreferences= getSharedPreferences("user", Context.MODE_PRIVATE);
String name=sharedPreferences.getString("username","");
String password=sharedPreferences.getString("password","");
final ArrayList<items> login = new ArrayList<items>();
login.add(new items(name,password));
itemsAdapter itemsAdapter=new itemsAdapter(this,login);
ListView listView = (ListView) findViewById(R.id.list_activity_container);
listView.setAdapter(itemsAdapter);
}
}
public class MainActivity extends AppCompatActivity {
EditText username;
EditText password;
TextView show;
Button save;
Button display;
Button go;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username=(EditText)findViewById(R.id.username);
password=(EditText)findViewById(R.id.password);
show=(TextView)findViewById(R.id.show);
save=(Button)findViewById(R.id.save);
display=(Button)findViewById(R.id.displayInfo);
go=(Button)findViewById(R.id.goToList);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences sharedPreferences= getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString("username",username.getText().toString());
editor.putString("password",password.getText().toString());
editor.apply();
// Toast.makeText(this,"Saved",Toast.LENGTH_LONG).show();
}
});
display.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences sharedPreferences= getSharedPreferences("user", Context.MODE_PRIVATE);
String name=sharedPreferences.getString("username","");
String password=sharedPreferences.getString("password","");
show.setText(name+" "+password);
}
});
go.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(MainActivity.this,list.class);
startActivity(intent);
}
});
}
}
Shared Preferences save a key-value pair. To save multiple elements in SharedPreferences you need to assign a unique key for each element. Let's name our key as "userID".
int userID = 0;
and save user details to shared preferences like this
SharedPreferences sharedPreferences= getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString("username_"+userID,username.getText().toString());
editor.putString("password_"+userID,password.getText().toString());
editor.apply();
When you add another user object, increment userID
++userID;
So now your shared preferences will contain two elements having keys <username_0> and <username_1>.
Also while getting data from preferences, don't forget to use correct key.
String name=sharedPreferences.getString("username_"+userID,"");
For loops : Suppose you have 5 elements and you want to add them to your List
in onCreate of MainActivity.
final ArrayList<items> login = new ArrayList<items>(itemCount);
for (int i = 0; i < 5; i++) {
// command below will be executed 5 times, and i will range from 0 to 4(both inclusive)
login.add(new items("name" + i, "password" + i));
}
// now our login list has 5 elements(namely name0,name1...name4)
In click listener of save button, save entire list to shared preferences
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences sharedPreferences = getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
for (int i = 0; i < 5; i++) {
// save entire list using loop.
editor.putString("username" + i, login.get(i).getUsername());
editor.putString("password" + i, login.get(i).getPassword());
}
editor.apply();
// Toast.makeText(this,"Saved",Toast.LENGTH_LONG).show();
}
});
in List activity , read data from preferences.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
final ArrayList<items> login = new ArrayList<items>();
SharedPreferences sharedPreferences = getSharedPreferences("user", Context.MODE_PRIVATE);
for (int i = 0; i < 5; i++) {
String name = sharedPreferences.getString("username" + i, "");
String password = sharedPreferences.getString("password" + i, "");
login.add(new items(name, password));
}
itemsAdapter itemsAdapter = new itemsAdapter(this, login);
ListView listView = (ListView) findViewById(R.id.list_activity_container);
listView.setAdapter(itemsAdapter);
}
However in ListActivity you don't need to read data from shared preferences, you can bundle data in the Intent used to start ListActivity, and in ListActivity get data from Intent.

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.

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

How to use shared preferences in RecyclerView.Adapter?

How to use shared preferences in RecyclerView.Adapter..? i have used shared preference value in RecyclerView.Adapter..but nothing is saving in shared preference..where exactly i have to use shared preference ..?in RecyclerView.Adapter or activity..?
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> {
private ImageLoader imageLoader;
private Context context;
private String gd;
public static final String SHARED_PREF_NAME = "myloginapp";
//We will use this to store the boolean in sharedpreference to track user is loggedin or not
public static final String LOGGEDIN_SHARED_PREF = "loggedin";
public static final String GROUPSNAME_SHARED_PREF = "groupname";
public CardAdapter(Context context) {
this.context = context;
}
//List of superHeroes
List<Group> groups;
public CardAdapter(List < Group > groups, Context context) {
super();
//Getting all the superheroes
this.groups = groups;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder (ViewGroup parent,int viewType){
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.groups_list, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder (ViewHolder holder,int position){
Group group1 = groups.get(position);
imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
imageLoader.get(group1.getPic(), ImageLoader.getImageListener(holder.imageView, R.drawable.ic_launcher, android.R.drawable.ic_dialog_alert));
holder.imageView.setImageUrl(group1.getPic(), imageLoader);
holder.groupname.setText(group1.getGname());//i want to store this value in shared preference..
holder.groupinfo.setText(group1.getGinfo());
gd = holder.groupname.getText().toString();//variable gd is storing any value.
holder.add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, Viewgroup1.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount () {
return groups.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
public NetworkImageView imageView;
public TextView groupname;
public TextView groupinfo;
public Button add;
public ViewHolder(View itemView) {
super(itemView);
imageView = (NetworkImageView) itemView.findViewById(R.id.imageViewHero);
groupname = (TextView) itemView.findViewById(R.id.textViewName);
groupinfo = (TextView) itemView.findViewById(R.id.textViewRank);
add = (Button) itemView.findViewById(R.id.button7);
//String gd = holder.groupname.getText().toString();
SharedPreferences sharedPreferences1 = context.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
//Creating editor to store values to shared preferences
SharedPreferences.Editor editor = sharedPreferences1.edit();
//Adding values to editor
editor.putBoolean(LOGGEDIN_SHARED_PREF, true);
editor.putString(GROUPSNAME_SHARED_PREF, gd);
}
}
}
Viewgroup.java
public class Viewgroup extends AppCompatActivity {
//Creating a List of superheroes
private List<Group> listSuperHeroes;
private String vault;
//Creating Views
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recycle);
//Initializing Views
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
//Initializing our superheroes list
listSuperHeroes = new ArrayList<>();
SharedPreferences sharedPreferences = getSharedPreferences(ProfileLogin.SHARED_PREF_NAME, MODE_PRIVATE);
vault = sharedPreferences.getString(ProfileLogin.EMAIL_SHARED_PREF,"Not Available");
//Calling method to get data
getData();
}
//This method will get data from the web api
private void getData(){
//Showing a progress dialog
final ProgressDialog loading = ProgressDialog.show(this,"Loading Data", "Please wait...",false,false);
//Creating a json array request
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Config.DATA_URL+vault,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Dismissing progress dialog
loading.dismiss();
//calling method to parse json array
parseData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(jsonArrayRequest);
}
//This method will parse json data
private void parseData(JSONArray array){
for(int i = 0; i<array.length(); i++) {
Group group1 = new Group();
JSONObject json = null;
try {
json = array.getJSONObject(i);
group1.setPic(json.getString(Config.TAG_IMAGE_URL));
group1.setGname(json.getString(Config.TAG_NAME));
group1.setGinfo(json.getString(Config.TAG_INFO));
} catch (JSONException e) {
e.printStackTrace();
}
listSuperHeroes.add(group1);
}
//Finally initializing our adapter
adapter = new CardAdapter(listSuperHeroes, this);
//Adding adapter to recyclerview
recyclerView.setAdapter(adapter);
/* recyclerView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
final Button add = (Button) v.findViewById(R.id.button7);
final TextView txtStatusChange = (TextView) v.findViewById(R.id.textViewName);
//final TextView txtStatusChange1 = (TextView) v.findViewById(R.id.textView33);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Viewgroup.this, Viewgroup1.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
// Log.e(TAG_IMAGE_URL, "hello text " + txtStatusChange.getText().toString() + " TAG " + txtStatusChange.getTag().toString());
Toast.makeText(Viewgroup.this, txtStatusChange.getText().toString(), Toast.LENGTH_SHORT).show();
}
});
return false;
}
});*/
}
}
You should add editor.commit() or editor.apply() in order to save your data to Sharedpreferences . Add this below your code
//Adding values to editor
editor.putBoolean(LOGGEDIN_SHARED_PREF, true);
editor.putString(GROUPSNAME_SHARED_PREF, gd);
editor.apply();
why the shared preference is not updating..?
Use onClick method of Button before starting Activity to save value in Sharedpreferences like:
...
gd = holder.groupname.getText().toString();
holder.add.setTag(gd);
...
#Override
public void onClick(View view) {
String strValue=view.getTag().toString();
... save strValue in Sharedpreferences
...
editor.putString(GROUPSNAME_SHARED_PREF, strValue);
editor.apply();
// start new Activity..
}
...
This is what I did. (If you cant access class "context" inside SharedPreferences)
Create a context of the adapter class by Context mConext; or private WeakReference<Context> mContext;
Instead giving mContext use this.mContext.get() wherever you need to use context inside the SharedPrefernce. like
SharedPreferences preferences = this.mContext.get().getSharedPreferences(MY_PREFERENCE_NAME, Context.MODE_PRIVATE);
I tried so many other solutions, but couldn't find the thing.
it works just add this.mcontext.getContext instead of this.mContext.get().
just use itemView.getContext() if you using this in side onCreateViewHolder view holder
GET DATA
just use itemView.getContext() before use getSharedPreferences
save is allso the same
Sharedpreferences prefs =
holder.itemView.getContext().getSharedPreferences("SHARED_PREFS", holder.itemView.getContext().MODE_PRIVATE);
String Variable= holder.prefs.getString("yourkey", null);

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