【问题标题】:Store and retrive Listview data using Shared Preferences使用共享首选项存储和检索 Listview 数据
【发布时间】:2017-07-29 01:03:00
【问题描述】:

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

这是视图

如您所见,我有一个书签边框图标,当用户单击它时,它将变为选中状态...这是它的工作原理:

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

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

【问题讨论】:

  • 你能把你的代码贴在github上并分享链接吗。我会努力解决的。
  • 你能给我解释一下'当我在我的数据库中插入新列时,新行将添加到列表中',因为我不明白你在说什么。
  • @RajaJawahar 正在上传,谢谢

标签: android mysql database listview sharedpreferences


【解决方案1】:

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

但是在这里您不想使用 SQLite 数据库,因此首先从您的 Web 服务下载 json,并且只有在用户点击喜欢的按钮时才进行更改,例如

点击前的 Json 格式:

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

点击后的Json格式:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-18
    • 1970-01-01
    • 2019-06-27
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 2011-07-22
    • 1970-01-01
    相关资源
    最近更新 更多