android - 在 ListView 中添加收藏夹按钮

标签 android android-listview sharedpreferences baseadapter

我有一个 listview,它有一个用于每个列表项的收藏夹按钮,单击该按钮时应该将列表项添加到另一个名为 my fav9rites 的 Activity 中。我正在为 listview 使用 Baseadapter,为添加收藏夹使用 Sharedpreference。 当我单击收藏夹按钮时, ListView 项目被添加到我的收藏夹 Activity 中,但我面临以下问题:

1) 单击时收藏夹按钮应变暗,表示列表项已添加到收藏夹。发生这种情况但是当我关闭 Activity 并再次返回时按钮恢复而不是变暗

2) 在我的收藏夹 Activity 中长按列表项,该列表项应该从收藏夹中删除,但这并没有发生。

希望大家明白我的问题

我的代码

我的基础适配器

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

}

我最喜欢的..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;
                        }
                    });
            }
        }
        }

   }

最佳答案

实际上你的 saveFavorites() 方法工作正常,因为你只是调用 gson.toJson() (将所有内容转换为 json 格式)

您想使用 SharedPreferences 获取保存的数据,并且您已使用此行来检索您的数据

 gson.fromJson(jsonFavorites, CodeList[].class);

你永远不会用这一行得到你保存的数据,因为你保存了一个列表并且你想要检索一个数组 (!)

如果您保存了一个列表,您必须使用列表标记检索您的数据。你需要这一行

 gson.fromJson(jsonFavorites,new TypeToken<ArrayList<CodeList>>() {}.getType());

我认为这将解决您的问题。祝你好运。

关于android - 在 ListView 中添加收藏夹按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34470120/

相关文章:

android - 单击通知时恢复 Activity

android - 自动完成 TextView 不起作用

android - 如何为 Android ListView 项目创建滑出选项菜单?

android - 如何更改 android 中填充的 ListView 项目的字体

android - 使用 TextInputLayout.OutlinedBox 样式的 Material 设计 Spinner

android - 获取android sendevent坐标比例因子

android - 可以在Worker中使用WebView吗?

android - 具有重复的基本适配器列表项的自定义适配器

android - 对数组使用共享首选项

java - 我的项目使用 SharedPreferences 保存 ArrayList<T> 时出现问题