How to save checkbox items to SharedPreferences? - android

I need to save values from the checkbox to shared preferences so that even after exiting, the checked boxes are still checked. Could anyone please show me how to solve this issue?
public class MainActivity extends Activity implements AdapterView.OnItemClickListener {
ListView listView;
ArrayAdapter<Model> adapter;
List<Model> list = new ArrayList<Model>();
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.my_list);
adapter = new MyAdapter(this,getModel());
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
TextView label = (TextView) v.getTag(R.id.label);
CheckBox checkbox = (CheckBox) v.getTag(R.id.check);
Toast.makeText(v.getContext(), label.getText().toString() + " " + isCheckedOrNot(checkbox), Toast.LENGTH_LONG).show();
}
private String isCheckedOrNot(CheckBox checkbox) {
if(checkbox.isChecked())
return "is checked";
else
return "is not checked";
}
private List<Model> getModel() {
list.add(new Model("1"));
list.add(new Model("2"));
list.add(new Model("3"));
return list;
}
}

I made this class, use it:
public class SavePreferences {
private final static String MYAPP_PREFERENCES = "MyAppPreferences";
public void savePreferencesData(View view, String KEY, String TEXT) {
SharedPreferences prefs = view.getContext().getSharedPreferences(MYAPP_PREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
if (TEXT != null && KEY != null) {
editor.putString(KEY, TEXT);
editor.commit();
}
}
private String loadPreferencesData(View view, String KEY){
SharedPreferences prefs = view.getContext().getSharedPreferences(MYAPP_PREFERENCES, Context.MODE_PRIVATE);
String data = prefs.getString(KEY, "No Data!");
return data;
}
}
And then:
savePreferencesData(View, "CheckBox1", "true");

Related

How to save and display items from Shared Preferences

DESCRIPTION:
I have used the concept of Shared preferences GSON concept to save/un save using "heart-icon" in list view.
My Design(fig.1)
. I can display only the titles as in Retrieved titles in a listview (fig.2) but cannot retrieve the icon of heart with titles like this figure 3.
The desired output (figure 3)
PROBLEM: I have a problem while displaying image from shared preferences in listview.
Following block of code is from CustomListAdapter::
public class CustomListAdapter extends ArrayAdapter {
private final Activity context;
private final String[] infoArray;
List<Object> selectlist = new ArrayList<Object>();
public static final String PREFERENCE_NAME = "favourite";
private final SharedPreferences sharedpreferences;
List<Object> favourites;
int[] image;
public CustomListAdapter(Activity context, String[] infoArrayParam, int[] imageIds){
super(context,R.layout.listview_row , infoArrayParam);
this.context=context;
this.infoArray = infoArrayParam;
this.image = imageIds;
sharedpreferences = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
}
public View getView(final int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
final View rowView = inflater.inflate(R.layout.listview_row, parent, false);
TextView nameTextField = (TextView) rowView.findViewById(R.id.textView2);
final ImageView imageView = (ImageView) rowView.findViewById(R.id.imageView4);
imageView.setOnClickListener(new View.OnClickListener(){
#SuppressLint({"NewApi", "ResourceType"})
#Override
public void onClick(View view) {
view.setSelected(!view.isSelected());
boolean favSelected = view.isSelected();
if (favSelected) {
imageView.setImageResource(R.drawable.ic_baseline_favorite1_24);
imageView.setTag(position);
imageView.setId(R.drawable.ic_baseline_favorite1_24);
Object chk = infoArray[position];
selectlist.add(chk);
view.setSelected(true);
saveData(context, selectlist);
}
else{
imageView.setImageResource(R.drawable.ic_baseline_favorite_border_24 );
imageView.setTag(position);
imageView.setId(R.drawable.ic_baseline_favorite_border_24);
view.setSelected(false);
removeFavorite(context,selectlist);
}
}
private boolean saveData(Context context, List<Object> selectlist){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
SharedPreferences.Editor aSharedPreferencesEdit = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(selectlist);
aSharedPreferencesEdit.putString("task list",json);
aSharedPreferencesEdit.apply();
return false;
}
private ArrayList<Object> loadData(Context context){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
Gson gson = new Gson();
String json = sharedPreferences.getString("task list", null);
System.out.println("The value of jsonnnnnnnn is " + json);
Type type = new TypeToken<List<Object>>(){}.getType();
System.out.println("The value of typpppppppppe is " + type);
return gson.fromJson(json, type);
}
public void removeFavorite(Context context, List<Object> selectlist) {
ArrayList<Object> favourites = loadData(context);
if (favourites != null) {
favourites.remove(selectlist);
saveData(context, favourites);
}
}
private boolean favOnClick(int position,View v, List<Object> selectlist){
ImageView button = (ImageView) v.findViewById(R.id.imageView4);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase(valueOf(position))){
saveData(context, selectlist);
button.setTag(position);
button.setImageResource(R.drawable.ic_baseline_favorite1_24);
}
else {
removeFavorite(context,selectlist);
button.setTag(position);
button.setImageResource(R.drawable.ic_baseline_favorite_border_24);
}
return true;
}
});
nameTextField.setText(infoArray[position]);
imageView.setImageResource(image[position]);
return rowView;
}
}
Following block of code is for DashBoard:
public class DashBoard extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener {
ListView listView;
Toolbar mActionBarToolBar;
Context context;
List<Object> selectlist ;
private ArrayAdapter<Object> adapter;
int[] drawableIds = new int[]{R.drawable.ic_baseline_favorite1_24, R.drawable.ic_baseline_favorite_border_24};
String[] infoArray = {
//Listed
};
protected void onCreate(Bundle savedInstanceState) {
SharedPreferences sharedPreferences = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
CustomListAdapter listItems = new CustomListAdapter(this, infoArray,drawableIds);
listView = (ListView) findViewById(R.id.listviewId);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
//To do
}
});
listView.setAdapter(listItems);
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.navigation_notifications:
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
Gson gson = new Gson();
String json = sharedPreferences.getString("task list", null);
System.out.println("The value of jsonnnnnnnn is " + json);
Type type = new TypeToken<List<Object>>(){}.getType();
System.out.println("The value of typpppppppppe is " + type);
selectlist = gson.fromJson(json, type);
if (selectlist == null){
selectlist= new ArrayList<>();
}
adapter = new ArrayAdapter<Object>(DashBoard.this,
android.R.layout.simple_list_item_1, (selectlist));
listView.setAdapter(adapter);
}
return false;
}
}
REFERENCES:How to save dynamically added items in Listview with sharedpreferences?
AnyHelp will be appreciated.
Thank You.

How to save background with sharedPreferences

hello friends I change the background with a spinner but I can't save the background with shared preferences can you help me? But if I delete the .setBackgroundColor() in position, the instant background won't change, I really don't understand.
the code is all. I cannot save the color code for this SharedPrence. By the way, I'm new to ANDROID.
public class MainActivity extends AppCompatActivity {
ConstraintLayout tasarım;
private SharedPreferences sharedPreferences;
private Spinner spinner;
private ArrayList<String> renkler = new ArrayList<>();
private ArrayAdapter<String> veriAdaptoru;
String color;
tasarım=(ConstraintLayout)findViewById(R.id.tasarım);
spinner = findViewById(R.id.spinner);
renkler.add("beyaz");
renkler.add("mavi");
renkler.add("kırmızı");
renkler.add("yeşil");
veriAdaptoru = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, android.R.id.text1, renkler);
spinner.setAdapter(veriAdaptoru);
sharedPreferences = this.getSharedPreferences("com.example.sondev", MODE_PRIVATE);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
SharedPreferences prefs=getSharedPreferences("color",MODE_PRIVATE);
SharedPreferences.Editor editor=prefs.edit();
String colorSec="";
if (position==0){
tasarım.setBackgroundColor(Color.WHITE);
colorSec="WHITE";
editor.putString("colour",colorSec);
editor.commit();
}
else if (position==1){
tasarım.setBackgroundColor(Color.BLUE);
colorSec="BLUE";
editor.putString("colour",colorSec);
editor.commit();
}
else if(position==2){
tasarım.setBackgroundColor(Color.RED);
colorSec="RED";
editor.putString("colour",colorSec);
editor.commit();
}else if (position==3){
colorSec="GREEN";
editor.putString("colour",colorSec);
editor.commit();
tasarım.setBackgroundColor(Color.GREEN);
}
else {
colorSec="GREEN";
editor.putString("colour",colorSec);
editor.commit();
tasarım.setBackgroundColor(Color.GREEN);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
SharedPreferences prefs=getSharedPreferences("color",MODE_PRIVATE);
color=prefs.getString("colour","WHITE");
if (color.equals("BLUE")){
tasarım.setBackgroundColor(Color.BLUE);
}
else if(color.equals("RED")){
tasarım.setBackgroundColor(Color.RED);
}else{
tasarım.setBackgroundColor(Color.GREEN);
}

Adding favorite button in list view

I have a listview which has a favorite button for every list item which when clicked should add the list item to another activity called my fav9rites. I am using a Baseadapter for the listview and Sharedpreference for adding favorites.
When I click the favorite button, the list view item is getting added in the my favorites activity but I am facing the following problems:
1)the favorite button when clicked should turn dark indicating that the list item is added to favorites. This happens but when I close the activity and come back again the button reverts back instead of being dark
2)on long press on list item in my favorites activity , the list item should be removed from the favorites but this is not happening.
Hope everyone understand my question
My code
my base adapter
public View getView(final int position, View view, ViewGroup parent)
{
final ViewHolder holder;
if(view == null){
holder = new ViewHolder();
view = inflater.inflate(R.layout.beg_list_item,null);
holder.listHeading = (TextView) view.findViewById(R.id.beg_list_itemTextView);
// holder.listHash = (TextView) view.findViewById(R.id.listview_hashtags);
holder.alphabetList = (ImageView) view.findViewById(R.id.beg_list_itemImageView);
holder.favoriteImg = (ImageView) view.findViewById(R.id.favbtn);
view.setTag(holder);
}else{
holder = (ViewHolder) view.getTag();
}
CodeList code = (CodeList) getItem(position);
holder.listHeading.setText(codeList.get(position).getListHeading());
imageLoader.DisplayImage(codeList.get(position).getAlphabetimg(),
holder.alphabetList);
// holder.listHash.setText(codeList.get(position).getListHashTags());
if (checkFavoriteItem(code)) {
holder.favoriteImg.setImageResource(R.drawable.favorite);
holder.favoriteImg.setTag("yes");
} else {
holder.favoriteImg.setImageResource(R.drawable.unfavorite);
holder.favoriteImg.setTag("no");
}
view.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0){
Intent intent = new Intent(context, SingleItemView.class);
//intent.putExtra("listheading",
// (codeList.get(position).getListHeading()));
//intent.putExtra("alphabetimg",
// (codeList.get(position).getAlphabetimg()));
intent.putExtra("demovideo",
(codeList.get(position).getDailogdemovideo()));
intent.putExtra("download",
(codeList.get(position).getDownloadCode()));
// Start SingleItemView Class
context.startActivity(intent);
}
});
final ImageView favoritesbutton = (ImageView) view.findViewById(R.id.favbtn);
favoritesbutton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
String tag = favoritesbutton.getTag().toString();
if(tag.equalsIgnoreCase("no")){
shrdPrefence.addFavorite(context, codeList.get(position));
Toast.makeText(context, R.string.fav_added, Toast.LENGTH_SHORT).show();
favoritesbutton.setTag("yes");
favoritesbutton.setImageResource(R.drawable.favorite);
}else{
shrdPrefence.removeFavorite(context, codeList.get(position));
favoritesbutton.setTag("no");
favoritesbutton.setImageResource(R.drawable.unfavorite);
Toast.makeText(context, R.string.fav_removed, Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
//Checks whether a particular product exists in SharedPreferences*/
public boolean checkFavoriteItem(CodeList checkCode) {
boolean check = false;
List<CodeList> favorites = shrdPrefence.getFavorites(context);
if (favorites != null) {
for (CodeList code : favorites) {
if (code.equals(checkCode)) {
check = true;
break;
}
}
}
return check;
}
public void add(CodeList code) {
codeList.add(code);
notifyDataSetChanged();
}
public void remove(CodeList code) {
codeList.remove(code);
notifyDataSetChanged();
}
sharedpreference.java
public class SharedPreference
{
public static final String PREFS_NAME = "MY_APP";
public static final String FAVORITES = "code_Favorite";
public SharedPreference(){
super();
}
public void saveFavorites(Context context, List<CodeList> 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, CodeList code){
List<CodeList> favorites = getFavorites(context);
if(favorites == null)
favorites = new ArrayList<CodeList>();
favorites.add(code);
saveFavorites(context,favorites);
}
public void removeFavorite(Context context, CodeList code) {
ArrayList<CodeList> favorites = getFavorites(context);
if (favorites != null) {
favorites.remove(code);
saveFavorites(context, favorites);
}
}
public ArrayList<CodeList> getFavorites(Context context) {
SharedPreferences settings;
List<CodeList> favorites;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
if (settings.contains(FAVORITES)) {
String jsonFavorites = settings.getString(FAVORITES, null);
Gson gson = new Gson();
CodeList[] favoriteItems = gson.fromJson(jsonFavorites,
CodeList[].class);
favorites = Arrays.asList(favoriteItems);
favorites = new ArrayList<CodeList>(favorites);
} else
return null;
return (ArrayList<CodeList>) favorites;
}
}
my favorite..java
public class MyFavActivity extends Activity
{
SharedPreference shrdPrfence;
List<CodeList> favorites;
FinalAdapter fnlAdpter;
Context context = this.context;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fav_layout);
shrdPrfence = new SharedPreference();
favorites = shrdPrfence.getFavorites(MyFavActivity.this);
if(favorites == null){
Dialog dialog = new Dialog(MyFavActivity.this);
dialog.setTitle(R.string.nofav_title);
dialog.show();
}else{
if(favorites.size() == 0){
Dialog dialog = new Dialog(MyFavActivity.this);
dialog.setTitle(R.string.nofav_title);
dialog.show();
}
ListView favList = (ListView) findViewById(R.id.fav_layoutListView);
if(favorites != null){
fnlAdpter = new FinalAdapter(MyFavActivity.this, favorites);
favList.setAdapter(fnlAdpter);
favList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View arg1,
int position, long arg3) {
}
});
favList.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
ImageView button = (ImageView) view
.findViewById(R.id.favbtn);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("no")) {
shrdPrfence.addFavorite(MyFavActivity.this,
favorites.get(position));
Toast.makeText(
MyFavActivity.this,
R.string.fav_added,
Toast.LENGTH_SHORT).show();
button.setTag("yes");
button.setImageResource(R.drawable.favorite);
} else {
shrdPrfence.removeFavorite(MyFavActivity.this,
favorites.get(position));
button.setTag("no");
button.setImageResource(R.drawable.unfavorite);
fnlAdpter.remove(favorites.get(position));
Toast.makeText(
MyFavActivity.this,
R.string.fav_removed,
Toast.LENGTH_SHORT).show();
}
return true;
}
});
}
}
}
}
Actually your saveFavorites() method works fine, becuse you just call gson.toJson() ( convert everything in json format)
You want to get saved data with SharedPreferences and you have used this line to retrieve your data
gson.fromJson(jsonFavorites, CodeList[].class);
you never get your saved data with this line, because you save a list and you want to retrieve an array (!)
If you saved a list you must retrive your data with a list token. And you need this line
gson.fromJson(jsonFavorites,new TypeToken<ArrayList<CodeList>>() {}.getType());
I think this will solve your question. Good luck.

Unable to use Shared Preferences for Arraylist

This is my list of songs from the NewList.class: http://postimg.org/image/uieab0wuv/ and i want in another activity to have a favorite list with the songs i get when the star button is long-pressed .
I used this tutorial(http://androidopentutorials.com/android-how-to-store-list-of-values-in-sharedpreferences/) to adapt my project but it doesn't work for an ArrayList
**the activity which generates the list **:
public class NewList extends Activity implements
AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener {
public static final String ARG_ITEM_ID = "product_list";
Activity activity;
ListView productListView;
ArrayList<Track> tracks;
SharedPreference sharedPreference;
private ListView newListView;
private EditText inputSearch;
private int TRACK_POSITION;
private AdapterExploreListView adapterExploreListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_explore_music);
newListView = (ListView) findViewById(R.id.newListView);
Bundle extras = getIntent().getExtras();
int temp = extras.getInt("id");
TextView mTextView = (TextView) findViewById(R.id.title_genre);
mTextView.setText(Consts.genresArray[temp]);
fillListWithStyle(Consts.genresArray[temp]);
newListView.setOnItemClickListener(this);
newListView.setOnItemLongClickListener(this);
Toast.makeText(getApplicationContext(),
"Position :" + temp, Toast.LENGTH_LONG)
.show();
}
private void fillListWithStyle(final String style)
{
new AsyncTask<Void,Void,ArrayList<Track>>()
{
#Override
protected ArrayList<Track> doInBackground(Void... voids) {
JsonParser parser = new JsonParser();
String encodedURL="";
try {
encodedURL = URLEncoder.encode(style, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return parser.getTracksForUrl(Consts.url1 + encodedURL + Consts.url2, "tracks");
}
#Override
protected void onPostExecute(ArrayList<Track> tracks) {
super.onPostExecute(tracks);
DataHolder.getInstance().setTracks(tracks);
adapterExploreListView = new AdapterExploreListView(NewList.this, tracks);
newListView.setAdapter(adapterExploreListView);
}
}.execute();
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(this, PlayerActivity.class);
intent.putExtra(PlayerActivity.TRACK_POSITION, i);
startActivityForResult(intent, 1);
TRACK_POSITION=i;
}
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View view,
int position, long arg3) {
ImageView button = (ImageView) view.findViewById(R.id.favbutton);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(activity, tracks.get(position));
Toast.makeText(activity,
activity.getResources().getString(R.string.add_favr),
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.favoritespic);
} else {
sharedPreference.removeFavorite(activity, tracks.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.favoritespicg);
Toast.makeText(activity,
activity.getResources().getString(R.string.remove_favr),
Toast.LENGTH_SHORT).show();
}
return true;
}
}
the adapter
public class AdapterExploreListView extends ArrayAdapter<Track> {
private Context context;
ArrayList<Track> tracks;
SharedPreference sharedPreference;
public AdapterExploreListView(Context context, ArrayList<Track> tracks) {
super(context, R.layout.row_list_explore, tracks);
this.context = context;
this.tracks = new ArrayList<>();
this.tracks = tracks;
sharedPreference = new SharedPreference();
}
#Override
public int getCount() {
return tracks.size();
}
#Override
public Track getItem(int position) {
return tracks.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
View rowView = view;
// reuse views
if (rowView == null) {
LayoutInflater inflater = LayoutInflater.from(context);
rowView = inflater.inflate(R.layout.row_list_explore, null);
// configure view holder
ViewHolder viewHolder = new ViewHolder();
viewHolder.title = (TextView) rowView.findViewById(R.id.titleTextView);
viewHolder.userName = (TextView) rowView.findViewById(R.id.userNameTextView);
viewHolder.favoriteImg = (ImageView) rowView.findViewById(R.id.favbutton);
rowView.setTag(viewHolder);
}
// fill data
final ViewHolder holder = (ViewHolder) rowView.getTag();
Track track = tracks.get(i);
holder.title.setText(track.getTitle());
holder.userName.setText(track.getUsername());
if (checkFavoriteItem(track)) {
holder.favoriteImg.setImageResource(R.drawable.favoritespic);
holder.favoriteImg.setTag("red");
} else {
holder.favoriteImg.setImageResource(R.drawable.favoritespicg);
holder.favoriteImg.setTag("grey");
}
return rowView;
}
static class ViewHolder {
TextView title;
TextView userName;
ImageView favoriteImg;
}
/*Checks whether a particular product exists in SharedPreferences*/
public boolean checkFavoriteItem(Track checkProduct) {
boolean check = false;
List<Track> favorites = sharedPreference.getFavorites(context);
if (favorites != null) {
for (Track track : favorites) {
if (track.equals(checkProduct)) {
check = true;
break;
}
}
}
return check;
}
#Override
public void add(Track track) {
super.add(track);
tracks.add(track);
notifyDataSetChanged();
}
#Override
public void remove(Track track) {
super.remove(track);
tracks.remove(track);
notifyDataSetChanged();
}
}
**the SharedPreference class **
public class SharedPreference {
public static final String PREFS_NAME = "PRODUCT_APP";
public static final String FAVORITES = "Product_Favorite";
public SharedPreference() {
super();
}
// This four methods are used for maintaining favorites.
public void saveFavorites(Context context, ArrayList<Track> 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, Track track) {
ArrayList<Track> favorites = getFavorites(context);
if (favorites == null)
favorites = new ArrayList<Track>();
favorites.add(track);
saveFavorites(context, favorites);
}
public void removeFavorite(Context context, Track track) {
ArrayList<Track> favorites = getFavorites(context);
if (favorites != null) {
favorites.remove(track);
saveFavorites(context, favorites);
}
}
public ArrayList<Track> getFavorites(Context context) {
SharedPreferences settings;
ArrayList<Track> favorites;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
if (settings.contains(FAVORITES)) {
String jsonFavorites = settings.getString(FAVORITES, null);
Gson gson = new Gson();
Track[] favoriteItems = gson.fromJson(jsonFavorites,
Track[].class);
favorites = (ArrayList<Track>) Arrays.asList(favoriteItems);
favorites = new ArrayList<Track>(favorites);
} else
return null;
return (ArrayList<Track>) favorites;
}
}
and the activity where i want to generate my list of favorites
public class ForthActivity extends Activity {
SharedPreference sharedPreference;
ArrayList<Track> favorites;
ListView favoriteList;
AdapterExploreListView adapterExploreListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.forthact);
// Get favorite items from SharedPreferences.
sharedPreference = new SharedPreference();
favorites = sharedPreference.getFavorites(ForthActivity.this);
if (favorites == null) {
} else {
if (favorites.size() == 0) {
}
favoriteList = (ListView) findViewById(R.id.forthlistview);
if (favorites != null) {
adapterExploreListView = new AdapterExploreListView(ForthActivity.this, favorites);
favoriteList.setAdapter(adapterExploreListView);
favoriteList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View arg1,
int position, long arg3) {
}
});
favoriteList
.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(
AdapterView<?> parent, View view,
int position, long id) {
ImageView button = (ImageView) view
.findViewById(R.id.favbutton);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(ForthActivity.this,
favorites.get(position));
Toast.makeText(
ForthActivity.this,
ForthActivity.this.getResources().getString(
R.string.add_favr),
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.favoritespic);
} else {
sharedPreference.removeFavorite(ForthActivity.this,
favorites.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.favoritespicg);
adapterExploreListView.remove(favorites
.get(position));
Toast.makeText(
ForthActivity.this,
ForthActivity.this.getResources().getString(
R.string.remove_favr),
Toast.LENGTH_SHORT).show();
}
return true;
}
});
}
}
}
}
Please help me .Thank you !
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View view,
int position, long arg3) {
ImageView button = (ImageView) view.findViewById(R.id.favbutton);
sharedPreference = new SharedPreference();
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(NewList.this, tracks.get(position));
Toast.makeText(NewList.this,
NewList.this.getResources().getString(R.string.add_favr),
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.favoritespic);
} else {
sharedPreference.removeFavorite(NewList.this, tracks.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.favoritespicg);
Toast.makeText(NewList.this,
NewList.this.getResources().getString(R.string.remove_favr),
Toast.LENGTH_SHORT).show();
}
return true;
}
and this code
private void fillListWithStyle(final String style)
{
new AsyncTask<Void,Void,ArrayList<Track>>()
{
#Override
protected ArrayList<Track> doInBackground(Void... voids) {
JsonParser parser = new JsonParser();
String encodedURL="";
try {
encodedURL = URLEncoder.encode(style, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return parser.getTracksForUrl(Consts.url1 + encodedURL + Consts.url2, "tracks");
}
#Override
protected void onPostExecute(ArrayList<Track> trackss) {
super.onPostExecute(trackss);
DataHolder.getInstance().setTracks(trackss);
adapterExploreListView = new AdapterExploreListView(NewList.this, trackss);
tracks = trackss;
newListView.setAdapter(adapterExploreListView);
}
}.execute();
}
I solved my problem ,these are the edits .I hope it will help someone else !
on the new list .class
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View view,
int position, long arg3) {
TextView textView4 = (TextView)view.findViewById(R.id.titleTextView);
TextView textView5 = (TextView)view.findViewById(R.id.userNameTextView);
n =textView4.getText().toString();
m=textView5.getText().toString();
MyObject=new CustomObject(n,m);
sharedPreference = new SharedPreference();
sharedPreference.addFavorite(NewList.this, MyObject);
Toast.makeText(NewList.this,
NewList.this.getResources().getString(R.string.add_favr),
Toast.LENGTH_SHORT).show();
return true;
}
}
the favorites activity *
public class FavActivity extends Activity {
ListView lv;
SharedPreference sharedPreference;
List<CustomObject> favorites;
ProductListAdapter productListAdapter;
Activity context = this;
public static final String FAVORITES = "Favorite";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.forthact);
sharedPreference = new SharedPreference();
favorites = sharedPreference.getFavorites(context);
lv = (ListView) findViewById(R.id.forthlistview);
fillFavoriteList();
}
private void fillFavoriteList() {
if (favorites != null) {
productListAdapter = new ProductListAdapter(ForthActivity.this, favorites);
lv.setAdapter(productListAdapter);
productListAdapter.notifyDataSetChanged();
}
}
}
the SharedPreferences class
public class SharedPreference {
public static final String PREFS_NAME = "PRODUCT_APP";
public static final String FAVORITES = "Product_Favorite";
public SharedPreference() {
super();
}
// This four methods are used for maintaining favorites.
public void saveFavorites(Context context, List<CustomObject> 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 void addFavorite(Context context, CustomObject product) {
List<CustomObject> favorites = getFavorites(context);
String s=product.getProp1();
if (favorites == null)
favorites = new ArrayList<CustomObject>();
favorites.add(product);
saveFavorites(context, favorites);
}
public void removeFavorite(Context context, CustomObject product) {
ArrayList<CustomObject> favorites = getFavorites(context);
if (favorites != null) {
favorites.remove(product);
saveFavorites(context, favorites);
}
}
public ArrayList<CustomObject> getFavorites(Context context) {
SharedPreferences settings;
List<CustomObject> favorites;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
if (settings.contains(FAVORITES)) {
String jsonFavorites = settings.getString(FAVORITES, null);
Gson gson = new Gson();
CustomObject[] favoriteItems = gson.fromJson(jsonFavorites,
CustomObject[].class);
favorites = Arrays.asList(favoriteItems);
favorites = new ArrayList<CustomObject>(favorites);
} else
return null;
return (ArrayList<CustomObject>) favorites;
}
}

how to remove list item or clearing listview using shared preferences?

I have following base adapter custom class, creating listview and items. but i want to remove all items from the list when I click reset button.
My code :
public class Scores extends Activity implements OnClickListener {
public static final String MY_PREFS_NAME = "PrefName";
SharedPreferences pref;
static String[] tempTime = new String[10];
static String[] tempScore = new String[10];
private static class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return tempTime.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(
R.layout.mathmatch_score_format, null);
holder = new ViewHolder();
holder.text1 = (TextView) convertView
.findViewById(R.id.time_text);
holder.text2 = (TextView) convertView
.findViewById(R.id.score_text);
/*final ImageView deleteButton = (ImageView)
convertView.findViewById(R.id.score_reset);
deleteButton.setOnClickListener(this);*/
convertView.setTag(holder);
//deleteButton.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text1.setText(tempTime[position]);
holder.text2.setText(tempScore[position]);
return convertView;
}
static class ViewHolder {
TextView text1;
TextView text2;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mathmatch_score);
setUpViews();
pref = getSharedPreferences(MY_PREFS_NAME, 0);
strTime = pref.getString("high_score_times", "");
intScore = pref.getString("high_score_values", "");
tempTime = strTime.split(",");
tempScore = intScore.split(",");
Comparator<String> comparator = new CustomArrayComparator<String, String>(tempScore, tempTime);
Arrays.sort(tempTime, comparator);
Arrays.sort(tempScore, Collections.reverseOrder());
lv.setAdapter(new EfficientAdapter(this));
}
private void setUpViews() {
lv = (ListView) findViewById(R.id.list);
reset = (ImageView) findViewById(R.id.score_reset);
reset.setOnClickListener(this);
}
#Override
protected void onPause() {
super.onPause();
pref = getSharedPreferences(MY_PREFS_NAME, 0);
SharedPreferences.Editor edit = pref.edit();
edit.putString("high_score_times", strTime);
edit.putString("high_score_values", intScore);
edit.commit();
}
#Override
protected void onStop() {
super.onStop();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.score_reset:
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
alertbox.setTitle("Reset");
alertbox.setMessage("Are you sure all time ans score are reset?");
alertbox.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
pref = getSharedPreferences(MY_PREFS_NAME, 0);
SharedPreferences.Editor edit = pref.edit();
/*edit.remove("high_score_times");
edit.remove("high_score_values");*/
/*edit.remove(intScore);
edit.remove(strTime);
*/
//edit.clear();
edit.remove(MY_PREFS_NAME);
edit.commit();
}
});
alertbox.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
Toast.makeText(getApplicationContext(), "'No' button clicked", Toast.LENGTH_SHORT).show();
}
});
alertbox.show();
break;
default:
break;
}}}
My reset button is not including on a list.
I have tried this in yes button click event in above code but could not get any update. So what to do?
Thanks in advance.
using your listview instance get the list adapter like
urlist.setAdapter("pass your updated adapter with empty string array");
OR
you can also call notifyDataSetChanged(); to tell the list view that its data set is changed
For a start, your using your adapter wrong. Your adapter should be a wrapper around your data, not a facade used to expose data contained elsewhere in your code.
In your case your using it to access the two variables (very bad form to make these static):
static String[] tempTime = new String[10];
static String[] tempScore = new String[10];
On create your filling these variables from your shared preferences.
Then on your "Yes" your updating your preferences but no matter how much you press the "update" button on your adapter, it's still looking at those variables which haven't been updated.
If you want your "Yes" button to clear your list then you need to change the data which backs the adapter then tell the adapter that it has changed and to redraw itself.
alertbox.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
pref = getSharedPreferences(MY_PREFS_NAME, 0);
SharedPreferences.Editor edit = pref.edit();
/**/
edit.remove(MY_PREFS_NAME);
edit.commit();
strTime = pref.getString("high_score_times", "");
intScore = pref.getString("high_score_values", "");
tempTime = strTime.split(",");
tempScore = intScore.split(",");
EfficientAdapter adapter = (EfficientAdapter)lv.getAdapter();
adapter.notifyDataSetChanged();
});
To clear List:
set tempTime and tempScore to empty array
tempTime= new String[0];
adapter.notifyDataSetChanged();
To Add/Remove Data :
Alter data source tempTime and tempScore accordingly and call adapter.notifyDataSetChanged();

Categories

Resources