I am trying when press favorite button saving Object to SharedPreferences I have done it but When I press again favorite button to Remove Object to SharedPreferences I can't do this, I got old Objects without removed Objects I shared below used code for this process.How can I do this?
Saving and Removing to Favorite Object
String tag = holder.order.getTag().toString();
if (tag.equalsIgnoreCase("deactive")) {
//order_models.add(new RetroPhoto(1,dataList.get(position).getSurname(),dataList.get(position).getName()));
sharedPreference.addFavorite(context, dataList.get(position));
//dataList.get(position).getName();
holder.order.setTag("active");
holder.order.setImageResource(R.drawable.ic_favorite);
} else {
sharedPreference.removeFavorite(context, dataList.get(position));
//dataList.get(position).getName();
//dataList.remove(dataList.get(position));
holder.order.setTag("deactive");
holder.order.setImageResource(R.drawable.ic_favorite_outline);
}
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<RetroPhoto> 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<RetroPhoto> loadFavorites(Context context) {
SharedPreferences settings;
List<RetroPhoto> favorites;
settings =
context.getSharedPreferences(PREFS_NAME,Context.MODE_PRIVATE);
if (settings.contains(FAVORITES)) {
String jsonFavorites = settings.getString(FAVORITES, null);
Gson gson = new Gson();
RetroPhoto[] favoriteItems =
gson.fromJson(jsonFavorites,RetroPhoto[].class);
favorites = Arrays.asList(favoriteItems);
favorites = new ArrayList<RetroPhoto>(favorites);
} else
return null;
return (ArrayList<RetroPhoto>) favorites;
}
public void addFavorite(Context context, RetroPhoto beanSampleList) {
List<RetroPhoto> favorites = loadFavorites(context);
if (favorites == null){
favorites = new ArrayList<RetroPhoto>();
}
favorites.add(beanSampleList);
storeFavorites(context, favorites);
}
public void removeFavorite(Context context, RetroPhoto beanSampleList) {
ArrayList<RetroPhoto> favorites = loadFavorites(context);
if (favorites != null) {
favorites.remove(beanSampleList);
storeFavorites(context, favorites);
}
}
}
Getting Update LoadSharedPreferences
#Override
protected void onResume() {
super.onResume();
Log.e("onResume", "onResume Called");
if(order_models != null ) {
try {order_models = sharedPreference.loadFavorites(getApplicationContext());
order_adapter = new OrderAdapter(getApplicationContext(), order_models);
recycle.setAdapter(order_adapter);
} catch (NullPointerException e) {
e.printStackTrace();
}
order_adapter.notifyDataSetChanged();
}
}
you actually just add item in SharedPreference and remove item just from your array.
for removing item from SharedPreference you should use this code
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
preferences.edit().remove("key").apply();
Related
I want to save this array list data in sharedpreferences and access that data in another fragment .Please Give me suggestion
Array list content given bellow
public String productname;
public String productunit;
public String productquantity;
public String productprice;
public String productdiscount;
Here is solution,
Step 1: Create a class like
SharedPreference
public static final String FAVORITES = "PRODUCTS";
private SharedPreferences settings;
private Editor editor;
public SharedPreference() {
super();
}
Now code to save ArrayList
public void saveArrayList(Context context, List<String> unread_ids) {
settings = context.getSharedPreferences(AppConfig.KEY_PREFS_NAME,
Context.MODE_PRIVATE);
editor = settings.edit();
Gson gson = new Gson();
String jsonFavorites = gson.toJson(unread_ids);
editor.putString(FAVORITES, jsonFavorites);
editor.apply();
}
Now code to get saved Arraylist
public ArrayList<String> getSavedList(Context context) {
// SharedPreferences settings;
List<String> unReadId;
settings = context.getSharedPreferences(AppConfig.KEY_PREFS_NAME,
Context.MODE_PRIVATE);
if (settings.contains(FAVORITES)) {
String jsonFavorites = settings.getString(FAVORITES, "");
Gson gson = new Gson();
String[] favoriteItems = gson.fromJson(jsonFavorites,
String[].class);
unReadId = Arrays.asList(favoriteItems);
unReadId = new ArrayList<>(unReadId);
} else {
return new ArrayList<String>();
}
return (ArrayList<String>) unReadId;
}
Code to save list:
sharedPreferences.saveArrayList(context, <YOUR LIST NAME>);
Now code to get your Arraylist in other Fragment
<LIST NAME> = sharedPreference.getSavedList(getActivity());
Before get and save array list you have to declare "sharedPreference" and create its object.
Hope this will help you.
I did something similar to this before Please check this code
private List<String> list; /// adding checked items to list
inside your OnCreate() add this line
list = new ArrayList<>(); /// checked items list
and to get array from model and store it local please use next.
int searchListLength = items.size();
for (int i = 0; i < searchListLength; i++) {
if (items.get(i).isChecked()) {
items.get(i).getId();
Log.d("listitem", String.valueOf("id=" + items.get(i).getId()));
list.add("id=" + items.get(i).getId());
}
}
StringBuilder stringBuilder = new StringBuilder();
for (String s : list) {
stringBuilder.append(s);
stringBuilder.append("&");
}
SharedPreferences notif_array = getSharedPreferences("items_array", Context.MODE_PRIVATE);
SharedPreferences.Editor editor_notaif = notif_array.edit();
editor_notaif.putString("id", stringBuilder.toString());
editor_notaif.apply();
Intent intent = new Intent(MainActivity.this, Filtered_Activity.class);
startActivity(intent);
Inside your another activity / fragment
private String new_result;
SharedPreferences notif_array = getSharedPreferences("items_array", Context.MODE_PRIVATE);
new_result = notif_array.getString("id", null);
/// i have tried to make an weather app, its fully functional, however, i have implemented the code and the data does save as there are no errors in the logcat, however, when i look in the bookmarked activity the saved weather location is not there. is there that any can help me
public class SaveData {
private static final String TAG ="SaveData";
SharedPreferences preferences;
SharedPreferences.Editor editor;
Context context;
private static String prefName = "Pref";
public static ArrayList<HistoryObj> weatherHistoryList = new ArrayList<>();
//KEYS to store
public static String WEATHER_LIST_KEY= "WeatherIds";
public SaveData(Context context){
int PRIVATE_MODE = 0;
this.context = context;
preferences = context.getSharedPreferences(prefName,PRIVATE_MODE);
editor = preferences.edit();
// TinyDb is class to simplify storage of ArrayList in Shared Preferences
// getting book marked list from storage
weatherHistoryList = getWeatherList();
}
public ArrayList<HistoryObj> getWeatherList(){
Gson gson = new Gson();
ArrayList<String> objStrings = getListString(WEATHER_LIST_KEY);
ArrayList<HistoryObj> objects = new ArrayList<HistoryObj>();
for(String jObjString : objStrings){
HistoryObj value = gson.fromJson(jObjString, HistoryObj.class);
objects.add(value);
}
return objects;
}
public void saveWeatherList(ArrayList<HistoryObj> objArray){
checkForNullKey(WEATHER_LIST_KEY);
Gson gson = new Gson();
ArrayList<String> objStrings = new ArrayList<String>();
for(HistoryObj obj : objArray){
objStrings.add(gson.toJson(obj));
}
putListString(WEATHER_LIST_KEY, objStrings);
}
public ArrayList<String> getListString(String key) {
return new ArrayList<String>(Arrays.asList(TextUtils.split(preferences.getString(key, ""), "‚‗‚")));
}
public void putListString(String key, ArrayList<String> stringList) {
checkForNullKey(key);
String[] myStringList = stringList.toArray(new String[stringList.size()]);
preferences.edit().putString(key, TextUtils.join("‚‗‚", myStringList)).apply();
}
public void checkForNullKey(String key){
if (key == null){
throw new NullPointerException();
}
}
}
I'm saving my playlists as json file, but oncreate I want to load every playlist already saved.
This is my save function;
void Kaydet(PLAYLIST liste_mp3)
{
SharedPreferences appSharedPrefs = PreferenceManager
.getDefaultSharedPreferences(this.getApplicationContext());
SharedPreferences.Editor prefsEditor = appSharedPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(liste_mp3);
prefsEditor.putString(liste_mp3.ad, json);
prefsEditor.commit();
}
And this is PLAYLIST class,
public class PLAYLIST
{
public String ad;
public ArrayList<MP3> liste;
public PLAYLIST(String ad1,ArrayList<MP3> liste1)
{
ad = ad1;
liste = liste1;
}
public String toString()
{
return ad;
}
public ArrayList<MP3> LISTE()
{
return liste;
}
}
This where I load specific one;
if(Yukle("A liste") != null) {
playlist.add(Yukle("A liste"));
} else { playlist.add(new PLAYLIST("A liste",a_liste)); }
and this is Load function,
PLAYLIST Yukle(String playlist_name)
{
SharedPreferences appSharedPrefs = PreferenceManager
.getDefaultSharedPreferences(this.getApplicationContext());
Gson gson = new Gson();
String json = appSharedPrefs.getString(playlist_name, "");
PLAYLIST p = gson.fromJson(json, PLAYLIST.class);
return p;
}
I fixed my problem with that idea, I created a new function that saves names of all playlists as string arraylist, and load string arraylist of playlists' names then make a for-loop and load per playlist with name.
This is in onCreate()
ArrayList<String> yukleniyor = YukleHepsi();
if(yukleniyor != null) {
for (String isimler : yukleniyor) {
playlist.add(Yukle(isimler));
}
}
This function loads names:
ArrayList<String> YukleHepsi()
{
SharedPreferences appSharedPrefs = PreferenceManager
.getDefaultSharedPreferences(this.getApplicationContext());
Gson gson = new Gson();
String json = appSharedPrefs.getString("isimler", "");
ArrayList<String> p = gson.fromJson(json, ArrayList.class);
return p;
}
And this function saves the names of all playlits,
void KaydetHepsi()
{
ArrayList<String> isimler = new ArrayList<String>();
for(PLAYLIST p: playlist)
{
if(p.ad != "None") {
isimler.add(p.ad);
}
}
SharedPreferences appSharedPrefs = PreferenceManager
.getDefaultSharedPreferences(this.getApplicationContext());
SharedPreferences.Editor prefsEditor = appSharedPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(isimler);
prefsEditor.putString("isimler", json);
prefsEditor.commit();
}
I know that this question has been asked many times but I couldn't find any solution for my problem.
I have a listview with a bookmark Icon in every row, that will save my selected item into shared preferences onClick. I have no problem with scrolling my listview till I click on a single item to save into shared preferences, Then I have a glitch on scrolling and event if I remove that item from my shared preferences I'll still have that glitch. till I uninstall and reinstall the application or clear app's cache.
Adapter
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.android_hive_list_row, null);
holder.title = (TextView) convertView.findViewById(R.id.title);
holder.rating = (TextView) convertView.findViewById(R.id.rating);
holder.genre = (TextView) convertView.findViewById(R.id.genre);
holder.year = (TextView) convertView.findViewById(R.id.releaseYear);
holder.playPauseHive=(ImageView)convertView.findViewById(R.id.playPauseHive);
holder.favoriteImgHive = (ImageView) convertView.findViewById(R.id.favImageHive);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
Product m = movieItems.get(position);
holder.title.setText(m.getTitle());
holder.rating.setText("Rating: " + String.valueOf(m.getRating()));
String genreStr = "";
for (String str : m.getGenre()) {
genreStr += str + ", ";
}
genreStr = genreStr.length() > 0 ? genreStr.substring(0,genreStr.length() - 2) : genreStr;
holder.genre.setText(genreStr);
holder.year.setText(String.valueOf(m.getYear()));
holder.favoriteImgHive.setImageResource(m.getFavId());
holder.favoriteImgHive.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (callback != null) {
callback.favOnClick(position,v);;
}
}
});
if (checkFavoriteItem(m)) {
holder.favoriteImgHive.setImageResource(R.mipmap.bookmarked);
holder.favoriteImgHive.setTag("red");
notifyDataSetChanged();
} else {
holder.favoriteImgHive.setImageResource(R.mipmap.bookmark_border);
holder.favoriteImgHive.setTag("grey");
notifyDataSetChanged();
}
return convertView;
}
/*Checks whether a particular product exists in SharedPreferences*/
public boolean checkFavoriteItem(Product checkProduct) {
boolean check = false;
List<Product> favorites = sharedPreference.getFavorites(activity);
if (favorites != null) {
for (Product product: favorites) {
if (product.equals(checkProduct)) {
check = true;
notifyDataSetChanged();
break;
}
}
notifyDataSetChanged();
}
return check;
}
Shared Pref
public class SharedPreference {
public static final String PREFS_NAME = "PRODUCT_APP";
public static final String FAVORITES = "Favorite_Tones";
public SharedPreference() {
super();
}
// This four methods are used for maintaining favorites.
public void saveFavorites(Context context, List<Product> favorites) {
SharedPreferences settings;
Editor editor;
settings = context.getSharedPreferences(PREFS_NAME,Context.MODE_PRIVATE);
editor = settings.edit();
Gson gson = new Gson();
String jsonFavorites = gson.toJson(favorites);
editor.putString(FAVORITES, jsonFavorites);
editor.commit();
}
public void addFavorite(Context context, Product product) {
List<Product> favorites = getFavorites(context);
if (favorites == null)
favorites = new ArrayList<Product>();
favorites.add(product);
saveFavorites(context, favorites);
Log.w("addPrefLog", favorites.toString());
}
public void removeFavorite(Context context, Product product) {
ArrayList<Product> favorites = getFavorites(context);
if (favorites != null) {
favorites.remove(product);
saveFavorites(context, favorites);
}
}
public ArrayList<Product> getFavorites(Context context) {
SharedPreferences settings;
List<Product> favorites;
settings = context.getSharedPreferences(PREFS_NAME,Context.MODE_PRIVATE);
if (settings.contains(FAVORITES)) {
String jsonFavorites = settings.getString(FAVORITES, null);
Gson gson = new Gson();
Product[] favoriteItems = gson.fromJson(jsonFavorites,Product[].class);
favorites = Arrays.asList(favoriteItems);
favorites = new ArrayList<Product>(favorites);
} else
return null;
return (ArrayList<Product>) favorites;
}
}
I just fix your SharedPreference class.. avoid using commit() and avoid to initialize repeatly your sharedPreferences
public class SharedPreference {
public static final String PREFS_NAME = "PRODUCT_APP";
public static final String FAVORITES = "Favorite_Tones";
SharedPreferences settings;
SharedPreferences.Editor editor;
Gson gson = new Gson();
#SuppressLint("CommitPrefEdits")
public SharedPreference(Context context) {
settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
editor = settings.edit();
}
// This four methods are used for maintaining favorites.
public void saveFavorites(List< Product > favorites) {
String jsonFavorites = gson.toJson(favorites);
editor.putString(FAVORITES, jsonFavorites);
editor.apply();
}
public void addFavorite(Product product) {
List < Product > favorites = getFavorites();
if (favorites == null)
favorites = new ArrayList < Product > ();
favorites.add(product);
saveFavorites(favorites);
Log.w("addPrefLog", favorites.toString());
}
public void removeFavorite(Product product) {
ArrayList < Product > favorites = getFavorites();
if (favorites != null) {
favorites.remove(product);
saveFavorites(favorites);
}
}
public ArrayList < Product > getFavorites() {
if (settings.contains(FAVORITES)) {
String jsonFavorites = settings.getString(FAVORITES, null);
Product[] favoriteItems = gson.fromJson(jsonFavorites, Product[].class);
favorites = Arrays.asList(favoriteItems);
favorites = new ArrayList < Product > (favorites);
} else
return null;
return (ArrayList < Product > ) favorites;
}
}
I have an app that shows notification in a listview. I want these notifications to be saved so that if I open the app and see notification I can see these notifications again when I close the app and then open it. I tried this
but nothing was saved.
Another major question is how can I run this app in background? So if notification is received the app lists that notification in the listview without being opened?
My Code
public class MainActivity extends Activity {
ListView list;
CustomListAdapter adapter;
ArrayList<Model> modelList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
modelList = new ArrayList<Model>();
adapter = new CustomListAdapter(getApplicationContext(), modelList);
list=(ListView)findViewById(R.id.list);
list.setAdapter(adapter);
LocalBroadcastManager.getInstance(this).registerReceiver(onNotice, new IntentFilter("Msg"));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);//Menu Resource, Menu
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Intent intent = new Intent(
"android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private BroadcastReceiver onNotice= new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String pack = intent.getStringExtra("package");
String title = intent.getStringExtra("title");
String text = intent.getStringExtra("text");
//int id = intent.getIntExtra("icon",0);
Context remotePackageContext = null;
if (pack.contains("fake")){
try {
// remotePackageContext = getApplicationContext().createPackageContext(pack, 0);
// Drawable icon = remotePackageContext.getResources().getDrawable(id);
// if(icon !=null) {
// ((ImageView) findViewById(R.id.imageView)).setBackground(icon);
// }
byte[] byteArray = intent.getByteArrayExtra("icon");
Bitmap bmp = null;
if (byteArray != null) {
bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
}
Model model = new Model();
if(text.contains("") && !text.contains(" messages")) {
model.setName(title + ": " + text);
model.setImage(bmp);
if (modelList != null) {
modelList.add(model);
adapter.notifyDataSetChanged();
} else {
modelList = new ArrayList<Model>();
modelList.add(model);
adapter = new CustomListAdapter(getApplicationContext(), modelList);
list = (ListView) findViewById(R.id.list);
list.setAdapter(adapter);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
};
}
Make a class Cache which has the capabilities to serialize and deserialize data.
public class Cache {
private static Cache CACHE;
public static Cache get() {
if (!SharedPreferencesHelper.isCacheAvailable()) {
CACHE = new Cache();
SharedPreferencesHelper.saveCache(CACHE);
} else {
CACHE = SharedPreferencesHelper.getCache();
}
return CACHE;
}
ArrayList<Taxonomy> cachedTaxonomies;
public Cache() {
cachedTaxonomies = new ArrayList<Taxonomy>();
}
public ArrayList<Taxonomy> getCachedTaxonomies() {
return cachedTaxonomies;
}
public static String serialize(Cache cache) {
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.enableComplexMapKeySerialization().setPrettyPrinting().create();
return gson.toJson(cache);
}
public static Cache deserialize(String json) {
Type type = new TypeToken<Cache>() {
}.getType();
return new Gson().fromJson(json, type);
}
public void update() {
SharedPreferencesHelper.saveCache(this);
}
}
Here Taxonomy is a model.
Below is the class which helps you save in SharedPrefs
public class SharedPreferencesHelper {
private static final String PREFS_CACHE = "prefs_cache";
public static SharedPreferences getSharedPreferences() {
return SpreeApplication.getSharedPreferences();
}
// Cache -------------------------------------
public static boolean isCacheAvailable() {
SharedPreferences sharedPreferences = getSharedPreferences();
String json = sharedPreferences.getString(PREFS_CACHE, "");
if(json.equals("")) {
return false;
} else {
return true;
}
}
public static Cache getCache() {
SharedPreferences sharedPreferences = getSharedPreferences();
String json = sharedPreferences.getString(PREFS_CACHE, "");
if(json.equals("")) {
return null;
} else {
return Cache.deserialize(json);
}
}
public static void saveCache(Cache cache) {
saveString(PREFS_CACHE, Cache.serialize(cache));
}
// -----------------------------------------------------
private static void saveString(String prefKey, String value) {
SharedPreferences sharedPreferences = getSharedPreferences();
SharedPreferences.Editor prefEditor = sharedPreferences.edit();
prefEditor.putString(prefKey, value);
prefEditor.commit();
}
private static void saveBoolean(String prefKey, boolean value) {
SharedPreferences sharedPreferences = getSharedPreferences();
SharedPreferences.Editor prefEditor = sharedPreferences.edit();
prefEditor.putBoolean(prefKey, value);
prefEditor.commit();
}
}
To save write this :
List<Taxonomy> taxonomies = new ArrayList<Taxonomy>();
Cache cache = Cache.get();
cache.getCachedTaxonomies().clear();
cache.getCachedTaxonomies().addAll(taxonomies);
SharedPreferencesHelper.saveCache(cache);
this is my spreeapplication class which is a custom application class
Remember you have to mention in manifest if you create a custom application class
public class SpreeApplication extends Application{
private final static String DEFAULT_PREFERENCES = "spree";
private static SharedPreferences sharedPreferences;
private static Context applicationContext;
#Override
public void onCreate() {
super.onCreate();
applicationContext = this;
sharedPreferences = getSharedPreferences(DEFAULT_PREFERENCES, Context.MODE_PRIVATE);
}
public static SharedPreferences getSharedPreferences() {
return sharedPreferences;
}
public static SharedPreferences.Editor getSharedPreferencesEditor() {
return sharedPreferences.edit();
}
public static Context getContext() {
return applicationContext;
}
}