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();
}
}
Related
My app crashes every time the Splash Screen has slept for 5 seconds and it just won't start my slider.I'd like to add by saying that I've tried using Shared Preferences but the error tends to persist.Any help would be appreciated.The method launchmain2() is basically nothing but calling a blank activity named Main2Activity.I haven't created as many layouts for the slider as I would need but rather just one which gets all its resources accordingly from the Slider class.Here's the full code
MainActivity
public class MainActivity extends AppCompatActivity {
ImageView iv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = findViewById(R.id.welcome_image);
Animation animation = AnimationUtils.loadAnimation(this, R.anim.transition);
iv.setAnimation(animation);
Thread loading = new Thread() {
public void run() {
try {
sleep(5000);
Intent main = new Intent(getApplicationContext(),Slide_Adapter.class);
startActivity(main);
finish();
}
catch (Exception e) {
e.printStackTrace();
}
}
};
loading.start();
}
}
Slide_Adapter
public class Slide_Adapter extends AppCompatActivity {
ViewPager pager;
Slider adapter;
Preferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_slide__adapter);
pager = findViewById(R.id.viewpager);
adapter = new Slider(this);
pager.setAdapter(adapter);
preferences = new Preferences(this);
if(!preferences.First()){
launchmain2();
finish();
}
}
private void launchmain2() {
preferences.FirstTime(false);
Intent intent = new Intent(Slide_Adapter.this, Main2Activity.class);
startActivity(intent);
finish();
}
}
Slider
public class Slider extends PagerAdapter {
private Context context;
public Slider(Slide_Adapter slide_adapter) {
this.context = context;
}
public int images[] = {R.drawable.add, R.drawable.call, R.drawable.message};
public String title[] = {"ADD A CONTACT", "MAKE CALLS", "TEXT"};
public int background[] = {
Color.rgb(255,0,0),
Color.rgb(128,255,0),
Color.rgb(255,0,255)};
#Override
public int getCount() {
return title.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return (view == (RelativeLayout)object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.slides, container, false);
RelativeLayout relativeLayout = view.findViewById(R.id.relative_layout);
ImageView imageView = view.findViewById(R.id.image);
TextView textView = view.findViewById(R.id.description);
relativeLayout.setBackgroundColor(background[position]);
imageView.setImageResource(images[position]);
textView.setText(title[position]);
container.addView(view);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((RelativeLayout)object);
}
}
Preference Class
public class Preferences {
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
Context context;
private static final String FIRST_LAUNCH = "A";
int MODE = 0;
private static final String PREFERENCE = "B";
public Preferences(Context context) {
this.context = context;
sharedPreferences = context.getSharedPreferences(PREFERENCE, MODE);
editor = sharedPreferences.edit();
}
public void FirstTime(boolean first){
editor.putBoolean(FIRST_LAUNCH, first);
editor.commit();
}
public boolean First(){
return sharedPreferences.getBoolean(FIRST_LAUNCH, true);
}
}
This issue arises because of the null context. Update context on Slider Adapter page.
Context update
private Context mContext;
public Slider(Context context) {
this.mContext = context;
}
And then use the mContext for instantiating the item.
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Update: For opening another activity for second time opening, change your MainActivity like this.
public class MainActivity extends AppCompatActivity {
ImageView iv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Preferences.init(getApplicationContext());// Also add this
iv = findViewById(R.id.welcome_image);
Animation animation = AnimationUtils.loadAnimation(this, R.anim.transition);
iv.setAnimation(animation);
Thread loading = new Thread() {
public void run() {
try {
sleep(5000);
if(Preferences.getIsFirst() == false){
Preferences.writeFirstTimeOpen(true);
Intent main = new Intent(getApplicationContext(),Slide_Adapter.class);
startActivity(main);
finish();
}else{
Intent main = new Intent(getApplicationContext(), Main2Activity.class);
startActivity(main);
finish();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
};
loading.start();
}
}
And Preference Class:
public class Preferences {
private static SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
Context context;
private static final String FIRST_LAUNCH = "A";
int MODE = 0;
private static final String PREFERENCE = "B";
public static void init(Context context) {
if (sharedPreferences == null) {
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
}
}
public static boolean writeFirstTimeOpen(boolean value) {
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(FIRST_LAUNCH, value);
return editor.commit();
}
public boolean getIsFirst(){
return sharedPreferences.getBoolean(FIRST_LAUNCH, true);
}
}
Please check this, as this will also fix another first time opening issue.
You need to modify like this your constructor
public Slider(Context context) {//Add Context in parameter
this.context = context;
}
And please go though this link how to set and get value from shared-preferences
Hope this helps you
I noticed that parameter in constructor of Slider class not define as needed
What you do
public Slider(Slide_Adapter slide_adapter) {//There is not Context in parameter
this.context = context;//context will be still null
}
What need to do
public Slider(Context context) {//Add Context in parameter
this.context = context;
}
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);
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..? 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);
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;
}