0

I have a cardView that has a textView and a Like button. Whenever the like button is pressed it will display that cardView in another fragment, just like favourites.

How can I do this using shared preference or any other method? I've done this to change the color of like button but don't know how to add that cardView to another fragment:

  likeImageView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

      int id = (int)likeImageView.getTag();
      if( id == R.drawable.ic_like){

          likeImageView.setTag(R.drawable.ic_liked);
          likeImageView.setImageResource(R.drawable.ic_liked);

          Toast.makeText(getActivity(),titleTextView.getText()+" added to favourites",Toast.LENGTH_SHORT).show();

      } else {

          likeImageView.setTag(R.drawable.ic_like);
          likeImageView.setImageResource(R.drawable.ic_like);
          Toast.makeText(getActivity(),titleTextView.getText()+" removed from favourites",Toast.LENGTH_SHORT).show();

      }

    }
  });
Shersh
  • 8,807
  • 3
  • 30
  • 58

3 Answers3

0
  1. Create an instance of SharedPreferences in your onclick method

    SharedPreferences prefs = getActivity().getSharedPreferences( "Preference_reference", Context.MODE_PRIVATE);

  2. Use the name of the 'Liked' item as the key and a boolean as the type Alternately you could use a Boolean array as the type if the items never change order.

  3. Save whether or not an item is liked to the shared pref in the onclick.

    if( id == R.drawable.ic_like){

        likeImageView.setTag(R.drawable.ic_liked);
        likeImageView.setImageResource(R.drawable.ic_liked);
    
        prefs.edit().putBoolean("Unique id", true).commit();   
    
        Toast.makeText(getActivity(),titleTextView.getText()+" added to 
        favourites",Toast.LENGTH_SHORT).show();
    
    }else{
    
        likeImageView.setTag(R.drawable.ic_like);
        likeImageView.setImageResource(R.drawable.ic_like);
    
        prefs.edit().putBoolean("Unique id", false).commit();
    
        Toast.makeText(getActivity(),titleTextView.getText()+" removed from favourites",Toast.LENGTH_SHORT).show();
    }
    
  4. In the fragment you want to show items if the are liked, Create another SharedPreferences variable and use it to initialize the fragment so that it shows any item whose key value is set to true.

    if(prefs.getBoolean("Unique Id",false)){Show card}

You can find plenty of resources on how to use SharedPreferences so I kept the code to the bare minimum

Tony
  • 1
  • 4
0

1-) Store the data

As far as I understand from the question, you want to keep the likes locally. Let's explore the Android Storage Options.

Android provides several options for you to save persistent application data. The solution you choose depends on your specific needs, such as whether the data should be private to your application or accessible to other applications (and the user) and how much space your data requires.

Your data storage options are the following:

  • Shared Preferences : Store private primitive data in key-value pairs.
  • Internal Storage : Store private data on the device memory. Externa
  • Storage : Store public data on the shared external storage.
  • SQLite Databases : Store structured data in a private database.
  • Network Connection : Store data on the web with your own network server

Other options do not seem to fit in your case so i'm continuing with SharedPreferences vs SQLite.

SQLite

Large amounts of same structured data should be stored in a SQLite database as databases are designed for this kind of data. As the data is structured and managed by the database, it can be queried to get a sub set of the data which matches certain criteria using a query language like SQL. This makes it possible to search in the data. Of course managing and searching large sets of data influences the performance so reading data from a database can be slower than reading data from SharedPreferences.

SharedPreferences

SharedPreferences is a key/value store where you can save a data under certain key. To read the data from the store you have to know the key of the data. This makes reading the data very easy. But as easy as it is to store a small amount of data as difficult it is to store and read large structured data as you need to define key for every single data, furthermore you cannot really search within the data except you have a certain concept for naming the keys.

For more about SQLite and SharedPreferences.

So you should use SQLite rather than SharedPreferences because you will store more than one like. Here is the great tutorial on how to use SQLite.

Also i suggest you use these libraries(LikeButton and LikeAnimation) to make your likes more beautiful.

2-) Read and display the data

I imagine that you have prepared your SQLite database and that you have successfully registered the data there. It'll be a lot easier later on. Read the data from the database and display it in the relevant fragment.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_like,
            container, false);

    //accessing database
    MySQLiteOpenHelper db = new MySQLiteOpenHelper(getActivity());

    //get all likes from database.
    //getAllLikes is a method that returns the likes you have stored in the database, as list.
    //You must write methods to write likes into the database and read from the database.
    List<MyLikeObject> likeList = new ArrayList<MyLikeObject>();
    likeList = db.getAllLikes();

    //find RecyclerView
    RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.rvLike);

    //set layoutManger
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

    //create an adapter
    MyAdapter mAdapter = new MyAdapter(likeList);

    //set adapter
     recyclerView.setAdapter(mAdapter);

    return view;
}
Burak Cakir
  • 953
  • 12
  • 20
0
Like_btn.setOnClickListener(new OnClickListener()
{
    **private boolean fun = true;**

    public void onClick(View v)
    {
        if(fun)
        {
            Like_btn.setImageResource(R.drawable.unlike);
            fun=false;
        }
        else
        {
            fun=true;
            Like_btn.setImageResource(R.drawable.like);
            Toast.makeText(getApplicationContext(), "Changed", Toast.LENGTH_LONG).show();
        }
    }
});
JHobern
  • 856
  • 1
  • 13
  • 19