Skip to content

Instantly share code, notes, and snippets.

@AhmedBadrSayed
Created April 4, 2016 12:03
Show Gist options
  • Save AhmedBadrSayed/5e9f39e4948418b7c53f4a5971a1bdbf to your computer and use it in GitHub Desktop.
Save AhmedBadrSayed/5e9f39e4948418b7c53f4a5971a1bdbf to your computer and use it in GitHub Desktop.
Favorites Shared Prefrence
package com.projects.ahmedbadr.moviesapp.DataStore;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import java.util.Comparator;
/**
* Created by Ahmed Badr for MoviesApp on 28/3/2016.
*/
public class Favorites {
public static final String MyPREFERENCES = "MyPrefs";
public SharedPreferences sharedPreferences;
public Favorites(Context ctx ){
sharedPreferences = ctx.getSharedPreferences(MyPREFERENCES,ctx.MODE_PRIVATE);
}
public boolean AddFavoriteMovie(String favoriteItem){
//Get previous favorite items
String favoriteList = getStringFromPreferences("","favorites");
// Append new Favorite item
if(favoriteList!=null){
favoriteList = favoriteList+"&"+favoriteItem;
}else{
favoriteList = favoriteItem;
}
// Save in Shared Preferences
return putStringInPreferences(favoriteList,"favorites");
}
public String[] getFavoriteList(){
String favoriteList = getStringFromPreferences("","favorites");
return convertStringToArray(favoriteList);
}
public boolean checkInPrefrence(String Details){
String[] Favorites = getFavoriteList();
for(int i=0 ; i<Favorites.length ; i++){
if(Favorites[i].equals(Details) )
return true;
}
return false;
}
public void clearPreferences(){
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.commit();
}
public boolean checkIsClear(){
if (getStringFromPreferences(null,"favorites")==null)
return true;
else return false;
}
private boolean putStringInPreferences(String value,String key){
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
return true;
}
public String getStringFromPreferences(String defaultValue,String key){
String temp = sharedPreferences.getString(key, defaultValue);
return temp;
}
private String[] convertStringToArray(String str){
String[] arr = str.split("&");
return arr;
}
}
@sz32
Copy link

sz32 commented Jun 5, 2019

Im getting length 1 from convertStringToArray and it is inflating a null item in my listview how to solve it

Capture

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment