Manidev
Manidev

Reputation: 41

add to favorites to a new activity

I'm working on a quotes app.. which contains famous quotes and person names in card view(recycler view).. each cardview contain a checkbox.. what i want to do is.. when ever the user click on a checkbox of a particular quotes card.. i need to display a toast.. saved to favorites..and change the checkbox background to another image(newimg).. when user again clicks on the checkbox the toast is to be displayed.. as removed form favorites ... and the checkbox background image should be default.. thus how to display all the favorites quotes marked by user in a separate activity.. i'm new to android .. I didn't found any references for my purpose..

MainActivity.java

public class MainActivity extends AppCompatActivity {

    //recyclerview objects
    private RecyclerView recyclerView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String[] AuthorNames = new String[]{"Navagio Beach", "Anse Source d'Argent Beach", "As Catedrais Beach",
                "La Concha Beach", "Bondi Beach", "Nissi Beach"};

        String[] QuotesGuide = new String[]{"https://www.tripadvisor.com.my/Attraction_Review-g7777607-" +
                "d671779-Reviews-Navagio_Beach_Shipwreck_Beach-Anafonitria_Zakynthos_Ionian_Islands.html",
                "https://www.tripadvisor.com.my/Attraction_Review-g477968-d637885-Reviews-Anse_Source_D_Argent" +
                        "-La_Digue_Island.html",
                "https://www.tripadvisor.com.my/Attraction_Review-g609028-d1547522-Reviews-As_Catedrais_Beach-Ribadeo_" +
                        "Province_of_Lugo_Galicia.html",
                "https://www.tripadvisor.com.my/Attraction_Review-g187457-d675885-Reviews-La_Concha_Beach-San_Sebastian" +
                        "_Donostia_Province_of_Guipuzcoa_Basque_Country.html",
                "https://www.tripadvisor.com.my/Attraction_Review-g255060-d257354-Reviews-Bondi_Beach-Sydney_" +
                        "New_South_Wales.html",
                "https://www.tripadvisor.com.my/Attraction_Review-g262055-d1519581-Reviews-Nissi_Beach-Ayia_" +
                        "Napa_Famagusta_District.html"};

        RecyclerView myrv = findViewById(R.id.recyclerView);
        MyRecycleViewAdapter myAdapter = new MyRecycleViewAdapter( AuthorNames , QuotesGuide , MainActivity.this);
        myrv.setLayoutManager(new LinearLayoutManager(this));
        myrv.setAdapter(myAdapter);

        }}

MyQuote.java

public class MyQuote {
private String author;
private String quotedesc;
private int isLiked = 0;
//constructor initializing values
public MyQuote(String author, String quotedesc) {
    this.quotedesc = quotedesc;
    this.author = author;
}
//getters
public String getAuthor() {
    return author;
}
public int getIsLiked(){return isLiked;}
public String getQuotedesc() {
    return quotedesc;
}

public void setIsLiked(int isLiked) {
    this.isLiked = isLiked;
}

}

MyReclerViewadapter.java

public class MyRecycleViewAdapter extends RecyclerView.Adapter<MyRecycleViewAdapter.ViewHolder>{
private MyQuote myQuote;
    private String[] AuthorNames;
    private String[] QuotesGuide;
    private Context mCtx;

    public MyRecycleViewAdapter(String[] authorNames, String[] quotesGuide, Context mCtx) {
        AuthorNames = authorNames;
        QuotesGuide = quotesGuide;
        this.mCtx = mCtx;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.sample_quotecards, parent, false);


        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(final MyRecycleViewAdapter.ViewHolder myholder, final int position) {
        myholder.tv_author.setText(AuthorNames[position]);
        myholder.tv_quote.setText(QuotesGuide[position]);

            myholder.im_favlike.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    //Show "Saved to favourite" toast
                    Toast.makeText(mCtx, " quote saved to favorites",
                            Toast.LENGTH_LONG).show();
                } else {
                    //Show "Removed from favourite"

                    Toast.makeText(mCtx, " quote removed from favorites",
                            Toast.LENGTH_LONG).show();
                }


            }


        });


        // share button of a recycler cardview
        myholder.buttonViewOption.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {


                Intent intent = new Intent(Intent.ACTION_SEND);
                intent.putExtra(Intent.EXTRA_TEXT, "share this quote"
                        + AuthorNames[myholder.getAdapterPosition()] +
                        "\nHere is the link to the full review: " + QuotesGuide[myholder.
                        getAdapterPosition()]);
                intent.setType("text/plain");
                mCtx.startActivity(Intent.createChooser(intent, "share this quote"));


            }
        });
    }


    @Override
    public int getItemCount() {
        return AuthorNames.length;
    }


    public class ViewHolder extends RecyclerView.ViewHolder {

        public TextView tv_author;
        public  CheckBox im_favlike;
        public TextView tv_quote;
        public ImageButton buttonViewOption;

        public ViewHolder(View itemView) {
            super(itemView);

            im_favlike = itemView.findViewById(R.id.likeimg);
            tv_author= itemView.findViewById(R.id.author_title);
            tv_quote= itemView.findViewById(R.id.quote_text);
            buttonViewOption = itemView.findViewById(R.id.imageViewOptions);
        }
    }
}

what i want to do is :

  1. whenever i click the (chekbox)favorite..the checkbox image is changing..and on back click it comes to default(unchecked)..and it works fine.. but the problem..is i dont understand how to save these checkbox values...when the user exits the app and open the app again i need to maintain the favorites..checkbox values..

  2. how to store all the favorites(quotes cards)... marked(checked) by the user in a separate activity..

i am new to android.. i dont know about shared preferences..can anyone explain in detail step wise ..what should i do.. it helps me lot..

enter image description here

Upvotes: 1

Views: 11279

Answers (2)

Ajay Chauhan
Ajay Chauhan

Reputation: 1551

As far as I can understand, you want to save the data in shared preferences if favorite is checked. In order to do that you should have knowledge of SharedPrefernces.

Follow this link for saving data in shared preferences. Android Shared preferences example

Now, as per your requirement, you want to save the List of your model class ie List of MyQuote if favorite button is checked

Follow this for saving lists in SharedPreferences. Save ArrayList to SharedPreferences

Coming back to the problem now, we need to save and fetch list from shared preferences. For ease, I will create three methods ,one for initiating MyQuote list in preferences , second one for fetching the list of saved MyQuote and the last one for updating the list of saved MyQuote

Gson gson = new Gson();


// create an empty list of MyQuote
public void initializeMyQuoteList(){
List<MyQuote> quoteList = new ArrayList<MyQuote>();
String jsonText = gson.toJson(quoteList);
prefsEditor.putString("MYQUOTE_LIST", jsonText);
prefsEditor.apply();
}


//getting quote list
public List<MyQuote> getQuoteList(){
 Type type = new TypeToken<List<MyQuote>>() {
    }.getType();
    return gson.fromJson(preferenceManager.getString("MYQUOTE_LIST",
            null), type);
}


//updating saved quote list
public void updateQuoteList(MyQuote quote){
 List<MyQuote> quoteList = getQuoteList();
quoteList.add(quote);
 String jsonText = gson.toJson(quoteList);
 prefsEditor.putString("MYQUOTE_LIST", jsonText);
 prefsEditor.apply();
}

As soon as the activity is created, initialize the empty list by calling initializeMyQuoteList(), whenever the favorite button is clicked update the list by adding MyQuote to the saved list ie by calling updateQuoteList(quote), here pass the MyQuote object when the item is clicked.

Now, we have all the saved Quotes, just call the getQuoteList() in the new activity to get the list of saved MyQuote list.

Upvotes: 1

Sandeep Insan
Sandeep Insan

Reputation: 348

Check out this Sample project

https://github.com/saini2sandeep/Favourite.git

For the showing of toast "Saved to favourite" and "Removed from favourites" You can do like this:

// Assume likeButtonCB is your check box and you have to set a listener on it as shown below in code:

 likeButtonCB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        if (isChecked) {
                           //Show "Saved to favourite" toast
                        } else {
                           //Show "Removed from favourite" toast
                        }
            }
        });

Now to change the like button image on clicking it, you have to make a drawable file like this: You can name it according to you i am naming it "like_button_background" here "ic_like_heart_button_color" is the drawable liked button image and "ic_like_heart_button_empty" is the unlike image.

  <?xml version="1.0" encoding="utf-8"?>
   <selector xmlns:android="http://schemas.android.com/apk/res/android">
   <item android:drawable="@drawable/ic_like_heart_button_color" 
   android:state_checked="true" />
   <item android:drawable="@drawable/ic_like_heart_button_empty" />

Add this file in your checkbox background in xml code like this:

<CheckBox
        android:id="@+id/like_button_cb"
        android:layout_width="32dp"
        android:layout_height="32dp"
        android:layout_marginStart="@dimen/margin_left_gen_16"
        android:background="@drawable/like_button_background"
        android:button="@null"
        android:gravity="center"
        android:padding="@dimen/padding_gen_4"
        android:textSize="@dimen/tv_gen_16"
        android:theme="@style/checkBoxStyle"
        android:visibility="visible" />

This will solve your first two problems. To save the like for the individual Cards you have to maintain one more field in model class "int isLiked = 0;" in model class and according to that you can update the state of like button while populating the UI.

You can do it like this: For example story is your model here then do this code in your adapter while populating the card data.

 if (story.getIsLiked() == 1) {
            likeButtonCB.setChecked(true);
        } else {
            likeButtonCB.setChecked(false);
        }

Upvotes: 2

Related Questions