android - 使用共享首选项存储和检索 ListView 数据

标签 android mysql database listview sharedpreferences

我有一个铃声 ListView ..我通过 mysql 数据库提供列表..(例如歌曲名称、歌曲网址...)。 我通过在我的数据库中添加新项目在我的 ListView 中动态添加产品(铃声),所以除了行图标之外,我的应用程序中没有这些数据。

这是 View

This is the view

如你所见,我有一个书签边框图标,当用户点击它时,它会变成选中状态...这就是它的工作原理:

    holder.favImage=(ImageView)v.findViewById(R.id.favImage); 
    holder.favImage.setImageResource(product.getFavId());
    holder.favImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Product product = (Product) mDataItems.get(position);
            if(product.faved){
                product.setFavId(R.mipmap.bookmarked);
                sharedPreference.addFavorite(mContext,product);
                product.faved=false;
                }
            else {
                sharedPreference.removeFavorite(mContext,product);
                product.setFavId(R.mipmap.bookmark_border);
                product.faved = true;
                }
             notifyDataSetChanged();
        }
    }); 

但是在我的“收藏夹”选项卡中什么也不会发生。即使书签图标被选中时的状态也不会被保存。

自定义适配器

    public class FunDapter<T> extends BaseAdapter {


    protected List<T> mDataItems;
    protected List<T> mOrigDataItems;
    protected final Context mContext;
    private final int mLayoutResource;
    private final BindDictionary<T> mBindDictionary;

    SharedPreference sharedPreference;

    public FunDapter(Context context, List<T> dataItems, int layoutResource,
                     BindDictionary<T> dictionary) {
      this(context, dataItems, layoutResource, null, dictionary);
    }


    public FunDapter(Context context, List<T> dataItems, int layoutResource,
                     LongExtractor<T> idExtractor, BindDictionary<T> dictionary) {
        this.mContext = context;
        this.mDataItems = dataItems;
        this.mOrigDataItems = dataItems;
        this.mLayoutResource = layoutResource;
        this.mBindDictionary = dictionary;
        sharedPreference = new SharedPreference();
    }



    public void updateData(List<T> dataItems) {
        this.mDataItems = dataItems;
        this.mOrigDataItems = dataItems;
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        if (mDataItems == null || mBindDictionary == null) return 0;

        return mDataItems.size();
    }

    @Override
    public T getItem(int position) {
        return mDataItems.get(position);
    }

    @Override
    public long getItemId(int position) {
        if(idExtractor == null) return position;
        else return idExtractor.getLongValue(getItem(position), position);
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        View v = convertView;
        final GenericViewHolder holder;
        if (null == v) {
            LayoutInflater vi =
                    (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = vi.inflate(mLayoutResource, null);
            holder = new GenericViewHolder();
            holder.root = v;


            //init the sub views and put them in a holder instance
            FunDapterUtils.initViews(v, holder, mBindDictionary);
            v.setTag(holder);
            }else {
            holder = (GenericViewHolder) v.getTag();
            }

        final T item = getItem(position);
        showData(item, holder, position);

    final Product product = (Product) mDataItems.get(position);        
    holder.favImage=(ImageView)v.findViewById(R.id.favImage); 
    holder.favImage.setImageResource(product.getFavId());
    holder.favImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {   
            if(product.faved){
                product.setFavId(R.mipmap.bookmarked);
                sharedPreference.addFavorite(mContext,product);
                product.faved=false;
                }
            else {
                sharedPreference.removeFavorite(mContext,product);
                product.setFavId(R.mipmap.bookmark_border);
                product.faved = true;
                }
             notifyDataSetChanged();
        }
    }); 


        return v;
    }

}

产品模型类

    @SuppressWarnings("serial")
public class Product implements Serializable {
    @SerializedName("pid")
    public int pid;

    @SerializedName("name")
    public String name;

    @SerializedName("qty")
    public int qty;

    @SerializedName("price")
    public String description;

    @SerializedName("song_url")
    public String song_url;

    @SerializedName("date")
    public String date;


    public boolean paused = true;
    public boolean faved = true;

     private int favId;
    public int getFavId() {
        return favId;}
    public void setFavId(int favId) {
        this.favId = favId;} 
}

SharedPreferences 类

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

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

我被困在这里几天了,你能帮帮我吗!

最佳答案

实际上,对于收藏夹,您的实现更复杂,我只是将一列放入您的数据库中,例如 name isFavorite,默认情况下,当您按下按钮时,将零添加到该列中,然后将值零更改为一,但每次我们都没有连接互联网所以使用 SQLite 数据库的原因是 SQLite 数据库的大小和速度与 SharedPreferences 相比更多。

但是在这里你不想使用 SQLite 数据库所以首先从你的网络服务下载 json 并且只有当用户点击喜欢的按钮时才进行更改

点击前的Json格式:

{unieq_id:”1”, isFavorite:”0”

点击后的Json格式:

{unieq_id:”1”, isFavorite:”1”

如果 isFavourite 0 则显示您不喜欢的图标,否则显示您喜欢的图标。

关于android - 使用共享首选项存储和检索 ListView 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42671720/

相关文章:

SQL 选择对单个表的多个引用

c# - 命令执行期间遇到 fatal error

android - 未授予 Android 应用程序中的互联网权限

php - joomla virtuemart 网站加载问题

mysql - 更新 MySQL 表并忽略重复条目

php - 我如何从下表中选择不同的行

ruby-on-rails - Ruby on Rails 中的自定义字段/表单

android - 更新列表中的对象

java - 如何更改 DatePicker 对话框在 EditText 中输入的格式

java - 反序列化来自服务器的错误响应时的 NPE