Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

   }
like image 490
user5524159 Avatar asked Oct 31 '22 12:10

user5524159


1 Answers

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.

like image 165
settaratici Avatar answered Nov 11 '22 07:11

settaratici