简体   繁体   中英

How to save like button state in android?

I am using jd-alexander/LikeButton https://github.com/jd-alexander/LikeButton instead of normal buttons in the android app. The code works fine while enabling and disabling switches. But I want to save the state of the like button. Suppose I enable the like button and swap the list the background code will run fine but the like button state will change to unliked.

Every time when I swap the list the like button state becomes unliked. Is there any way to save the like button State??

Activity codes:

public class CollectorListAdapter extends ArrayAdapter<Collector> {

    private static final String TAG = "CollectorListAdapter";
    private Context mContext;
    private int mResource;

    public CollectorListAdapter(Context context, int resource, ArrayList<Collector> objects) {

        super(context, resource, objects);
        mContext = context;
        mResource = resource;
    }

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


        //Get the Shop information
        String Shopname = getItem(position).getName();
        String Specialoffers = getItem(position).getSpecialoffers();
        int Price = getItem(position).getPrice();
        final Double startLatitude = getItem(position).getLatitude();
        final Double startLongitude = getItem(position).getLongitude();
        final String user_id = String.valueOf(getItem(position).getUserid());
        final String shop_id = String.valueOf(getItem(position).getShopid());
        final String product_id = String.valueOf(getItem(position).getProductid());

        //create the view result for showing the animation
        LayoutInflater inflater = LayoutInflater.from(mContext);
        convertView = inflater.inflate(mResource, parent, false);
        TextView sname = (TextView) convertView.findViewById(R.id.textView);
        TextView tvname = (TextView) convertView.findViewById(R.id.textView7);
        TextView Location = (TextView) convertView.findViewById(R.id.textView9);
        TextView tvdescription = (TextView) convertView.findViewById(R.id.textView10);

        sname.setText(Shopname);
        tvdescription.setText(Specialoffers);
        tvname.setText(CurrencyFormatting(Integer.toString(Price)) + " EGP");
        Location.setText(format(results[0]) + " km");

        LikeButton heart;

        heart = convertView.findViewById(R.id.favBtn);

        heart.setOnLikeListener(new OnLikeListener() {

            // Add Data to the Saved Shop Table by like
            @Override
            public void liked(LikeButton likeButton) {

                StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.URL_SAVED_SHOPS, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.d(TAG, "Register Response: " + response.toString());
                        try {
                            JSONObject jObj = new JSONObject(response);
                            boolean error = jObj.getBoolean("error");
                            if (!error) {
                            } else {
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e(TAG, "Registration Error: " + error.getMessage());
                    }
                }) {
                    @Override
                    protected Map<String, String> getParams() {
                        // Posting params to register url
                        Map<String, String> params = new HashMap<String, String>();
                        params.put("user_id", user_id);
                        params.put("shop_id", shop_id);
                        params.put("product_id", product_id);
                        return params;
                    }
                };
                Volley.newRequestQueue(getContext()).add(strReq);
                Toast.makeText(getContext(),
                        "Shop Saved Successfully", Toast.LENGTH_LONG).show();
            }

            // Delete Data to the Saved Shop Table by Unlike
            @Override
            public void unLiked(LikeButton likeButton) {

                StringRequest strReq10 = new StringRequest(Request.Method.POST, AppConfig.URL_Delete_SAVED_SHOPS, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.d(TAG, "Register Response: " + response.toString());
                        try {
                            JSONObject jObj = new JSONObject(response);
                            boolean error = jObj.getBoolean("error");
                            if (!error) {
                            } else {
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e(TAG, "Registration Error: " + error.getMessage());
                    }
                }) {
                    @Override
                    protected Map<String, String> getParams() {
                        // Posting params to register url
                        Map<String, String> params = new HashMap<String, String>();
                        params.put("user_id", user_id);
                        params.put("shop_id", shop_id);
                        params.put("product_id", product_id);
                        return params;
                    }
                };
                Volley.newRequestQueue(getContext()).add(strReq10);
                Toast.makeText(getContext(),
                        "Shop Saved Deleted Successfully", Toast.LENGTH_LONG).show();
            }
        });

        return convertView;
    }
}

Collector Class:

public class Collector implements java.io.Serializable {
    private String specialoffers, name;
    private Double latitude, longitude;
    private int price,userid,shopid,productid;

    public Collector() {

    }

    //Sorting by Price method
    public static Comparator<Collector> PriceSort = new Comparator<Collector>() {

        public int compare(Collector s1, Collector s2) {

            int rollno1 = s1.getPrice();
            int rollno2 = s2.getPrice();

            /*For ascending order*/
            return rollno1 - rollno2;

            /*For descending order*/
            //rollno2-rollno1;
        }
    };

    //Sorting by Distance method
    public static Comparator<Collector> DistanceSort = new Comparator<Collector>() {

        public int compare(Collector s1, Collector s2) {

            float[] results1 = new float[3];
            Location.distanceBetween(
                    LocationActivity.currentLocation.getLatitude(),
                    LocationActivity.currentLocation.getLongitude(),s1.getLatitude(),
                    s1.getLongitude(),
                    results1);

            float[] results2 = new float[3];
            Location.distanceBetween(
                    LocationActivity.currentLocation.getLatitude(),
                    LocationActivity.currentLocation.getLongitude(),s2.getLatitude(),
                    s2.getLongitude(),
                    results2);

            /*For ascending order*/
            return Float.compare(results1[0], results2[0]);

            /*For descending order*/
            //rollno2-rollno1;
        }
    };


    public int getUserid() {
        return userid;
    }

    public void setUserid(int userid) {
        this.userid = userid;
    }

    public int getShopid() {
        return shopid;
    }

    public void setShopid(int shopid) {
        this.shopid = shopid;
    }

    public int getProductid() {
        return productid;
    }

    public void setProductid(int productid) {
        this.productid = productid;
    }

    public String toString() {
        return ("Shop Name:" + getName() +
                " Price : " + getPrice() +
                " SpecialOffers : " + getSpecialoffers() +
                " latitude : " + getLatitude()) +
                " longitude : " + getLongitude();
    }

    public String getSpecialoffers() {
        return specialoffers;
    }

    public void setSpecialoffers(String specialoffers) {
        this.specialoffers = specialoffers;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Double getLatitude() {
        return latitude;
    }

    public void setLatitude(Double latitude) {
        this.latitude = latitude;
    }

    public Double getLongitude() {
        return longitude;
    }

    public void setLongitude(Double longitude) {
        this.longitude = longitude;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

}

This is the normal behaviour in ArrayAdapter , the whole list gets recreated again so you lose the state of the button. You should save the boolean of the button in the local list variable. Add a field like isLiked = true/false in the Collector class and update the value at the particular position every time user click like/unlike buttons.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM