1

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

Community
  • 1
  • 1
Manidev
  • 41
  • 1
  • 7

2 Answers2

2

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);
        }
Sandeep Insan
  • 338
  • 1
  • 7
  • not static method getisliked cannot be referenced from a static context – Manidev Oct 22 '18 at 15:59
  • which static method you are making ? – Sandeep Insan Oct 22 '18 at 16:05
  • thank you sir , for your time .. solved half of my problem.. i think ..as i am new to android i cant understand some concepts.. but i will try to solve this.. – Manidev Oct 22 '18 at 19:24
  • - Changing the image of checkbox on pressing it. - Showing the Toast on clicking the button. These two problems are solved now only remains is, showing only the liked cards in new Activity. – Sandeep Insan Oct 23 '18 at 04:05
  • yes sir, and another one, is i dont understand how to save the liked state of quotes.. for example when user marked some quotes as favourite..when he closes the app..and open it again.. how to maintain its checkbox state... you explained in your example but.. i'm littel confused..can u see my code..and suggest what should i do.. to solve these two problems.. – Manidev Oct 23 '18 at 04:34
  • Take pull from the project and check now, i am saving the favorite card in the shared preferences and let me know anything else remains. – Sandeep Insan Oct 23 '18 at 07:12
  • sir, your example project is really helpful and solved my problem..but only thing..what i notice is.. whenever i marked checkbox..of a particular card in [card list]..it displays [saved] and it is saved to [favt card list].. and on back click it removed and change the image to default[empty heart]... but...when i close the app and open it again..(or when i go back to [favt card list] and come back to [card list].. the marked cards are in [favt card list]..its fine..but the state of checkbox of cards are not saved in [card list].... – Manidev Oct 23 '18 at 19:16
  • and how to modify setupdata method in homeactivity.. as per my need.. as i want to show quotes in place of storytitles.... and i changed story_comment_button_iv to [share icon] .. i need to share the specific quote(text).....//story title as per your example//....to other apps like whatsapp , fb, email etc.... when clicked on a particular card's.. share icon – Manidev Oct 23 '18 at 20:04
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/182393/discussion-between-sandeep-insan-and-manidev). – Sandeep Insan Oct 24 '18 at 04:37
1

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.

Ajay Chauhan
  • 1,091
  • 2
  • 12
  • 33
  • sir, can you explain in detail (step wise)....i edited my question with present code.. – Manidev Oct 22 '18 at 19:48
  • what is the exact problem you are facing ? – Ajay Chauhan Oct 23 '18 at 05:21
  • 1. save the state of checkbox(favorites).. whenever user opens app again.. 2.store all the favorites quotes in a separate acitvity.. sir, you explained the procedure , but as a beginner i am unable to understand what to do stepwise.. can u explain in detail.. – Manidev Oct 23 '18 at 05:36
  • read the whole answer again to save the list in preferences, first add all these methods which I've mentioned in your SharePreferences class, now when you click your item call setIsLiked(idOfItem) and update the list of saved items using shared preference method updateQuoteList(quote) ,when your activity is created populate the recylcer view using getQuoteList(),thats it – Ajay Chauhan Oct 23 '18 at 05:48
  • one last doubt sir, how to create shared preferences class.. do i need to create as a separate class ?... and also i dont understand the last sentence.. does {activity} in your last sentence means my {new acitvity} where i want to show all favorites...and where to add setIsliked and updatequoteslist(quote) in my code.... – Manidev Oct 23 '18 at 06:27
  • it is not mandatory to create a separate SharedPrefernence class, but it is a good practice to create one, in your case use as it mentioned in previous links,In your model class,isLiked field, make it boolean so whenever user clicks bookmark checkbox call setIsLiked(true) .and call update method to update the Quote in your saved QuoteList.I am talking about the activity where you are going to show the bookmarked Quotes, populate recycler view using getQuoteList() and check the filed getIsLiked() if it is true checBox state to true otherwise make it false. – Ajay Chauhan Oct 23 '18 at 07:22