1. Are you ready for the Galaxy S20? Here is everything we know so far!

ViewPager Filter Items / Do Not Show All Items

Discussion in 'Android Development' started by chackbusch, Jun 9, 2017.

  1. chackbusch

    chackbusch Lurker
    Thread Starter

    I'm currently developping my first Android Application. Now I'm at the point where I really don't know how to handle the problem on my own. Please don't be too strict with me, I don't have much experience and I'm here to learn something. My Main Layout implements a ViewPager:

    Code (Text):
    1. <android.support.v4.view.ViewPager
    2.    android:id="@+id/image_swipe"
    3.    android:layout_width="match_parent"
    4.    android:layout_height="590dp"
    5.    android:layout_marginTop="130dp" />
    The Main Layout also implements a toolbar which owns this menu item:

    Code (Text):
    1.  
    2. <item
    3.      android:id="@+id/show_favorites"
    4.      android:orderInCategory="100"
    5.      android:icon="@drawable/heart_red"
    6.      android:title="@string/show_favorites" />
    What I basically want to do, is: when the user clicks the menu item with id @show_favorites, the Adapter for the ViewPager should be filtered. Every item presented in the ViewPager has an ImageButton (favouriteButton). The button can be grey or red. The button state is stored as SharedPreferences, means: every item has its own key fav1 - fav10 (10 items) and this key has value 0 (grey) or value 1 (red). So when someone clicks the menu item, I only want to show items in the ViewPager which are marked as favorite (so in SharedPreferences it is stored 1). All items with a 0 have to be hidden.

    My Adapter Class looks like you can see below:

    Code (Text):
    1.  
    2. public class SwipeAdapter extends PagerAdapter  {
    3.  
    4. /*
    5.    Define the image resources for our image fragment
    6.  */
    7. private int[] image_resources = {
    8.        R.drawable.img1,
    9.        R.drawable.img2,
    10.        R.drawable.img3,
    11.        R.drawable.img4,
    12.        R.drawable.img5,
    13.        R.drawable.img6,
    14.        R.drawable.img7,
    15.        R.drawable.img8,
    16.        R.drawable.img9,
    17.        R.drawable.img10
    18. };
    19.  
    20. private Context context;
    21. private LayoutInflater layoutInflater;
    22.  
    23. public SwipeAdapter(Context context) {
    24.    this.context = context;
    25. }
    26.  
    27. /*
    28.    Count the images in image_resources array
    29.   */
    30. @Override
    31. public int getCount() {
    32.    return image_resources.length;
    33. }
    34.  
    35. @Override
    36. public boolean isViewFromObject(View view, Object object) {
    37.    return (view == (LinearLayout) object);
    38. }
    39.  
    40. /*
    41.    Create the page for the given position
    42.    Set image resources and text about current position
    43.  */
    44. @Override
    45. public Object instantiateItem(ViewGroup container, int position) {
    46.    layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    47.    View item_view = layoutInflater.inflate(R.layout.swipe_layout,container,false);
    48.    ImageView imageView = (ImageView) item_view.findViewById(R.id.swipe_image);
    49.    TextView textView = (TextView) item_view.findViewById(R.id.image_count);
    50.    ImageButton imageButton = (ImageButton) item_view.findViewById(R.id.favourite_button);
    51.  
    52.    imageView.setImageResource(image_resources[position]);
    53.  
    54.    // set tag for details
    55.    imageView.setTag(position);
    56.  
    57.    textView.setText("["+(position+1)+"/10]");
    58.  
    59.    SharedPreferences prefs = context.getSharedPreferences("favInfo", Context.MODE_PRIVATE);
    60.  
    61.    // get the unique key consisting of fav and the current item position
    62.    String key = "fav" + (position+1);
    63.    imageButton.setTag(position+1);
    64.  
    65.    String value = prefs.getString(key, "0");
    66.  
    67.    // check if value of favorite key is 0
    68.    // set image resource dependent on what value is set
    69.    if (value.equals("1")) {
    70.        imageButton.setImageResource(R.drawable.heart_red);
    71.    } else {
    72.        imageButton.setImageResource(R.drawable.heart);
    73.    }
    74.  
    75.    container.addView(item_view);
    76.  
    77.    return item_view;
    78. }
    79.  
    80. /*
    81.    Remove a page for the given position
    82.  */
    83. @Override
    84. public void destroyItem(ViewGroup container, int position, Object object) {
    85.    container.removeView((LinearLayout) object);
    86. }
    87. }
    And my Main Activity is organized this way:

    Code (Text):
    1.  
    2. public class SuggestionActivity extends AppCompatActivity {
    3.  
    4. ViewPager viewPager;
    5. SwipeAdapter adapter;
    6.  
    7. private final AppCompatActivity activity = SuggestionActivity.this;
    8.  
    9. @Override
    10. protected void onCreate(Bundle savedInstanceState) {
    11.    super.onCreate(savedInstanceState);
    12.    setContentView(R.layout.activity_suggestion);
    13.  
    14.    viewPager = (ViewPager) findViewById(R.id.image_swipe);
    15.    adapter = new SwipeAdapter(this);
    16.  
    17.    viewPager.setAdapter(adapter);
    18.  
    19.    // set the toolbar for the suggestion page
    20.    Toolbar sToolbar = (Toolbar) findViewById(R.id.suggestion_toolbar);
    21.    setSupportActionBar(sToolbar);
    22. };
    23.  
    24. /*
    25.    Add options menu at view start
    26.  */
    27. @Override
    28. public boolean onCreateOptionsMenu(Menu menu) {
    29.    getMenuInflater().inflate(R.menu.suggestion_menu, menu);
    30.  
    31.    return super.onCreateOptionsMenu(menu);
    32. }
    33.  
    34. /*
    35.    Declare what happens when user clicks an item of the options menu
    36.    @go_home start the CategoryActivity
    37.    @filter TO DO
    38.  */
    39. @Override
    40. public boolean onOptionsItemSelected(MenuItem item) {
    41.    switch (item.getItemId()) {
    42.        case R.id.go_home:
    43.            Intent homeIntent = new Intent(activity, CategoryActivity.class);
    44.            startActivity(homeIntent);
    45.            return true;
    46.        case R.id.show_favorites:
    47.            Intent favIntent = new Intent(activity, SuggestionActivity.class);
    48.  
    49.            //
    50.            // HERE IS WHERE I DON'T KNOW WHAT TO DO
    51.            //
    52.  
    53.            startActivity(favIntent);
    54.  
    55.            return true;
    56.        default:
    57.            // If we got here, the user's action was not recognized.
    58.            // Invoke the superclass to handle it.
    59.            return super.onOptionsItemSelected(item);
    60.    }
    61. }
    62.  
    63. /*
    64.    Method for click actions on the favorite button
    65.    @heart grey heart symbolizes no favorite (flag 0)
    66.    @heart_red red heart symbolizes marked as favorite (flag 1)
    67. */
    68. public void onClickFav(View v) {
    69.    ImageButton favouriteButton = (ImageButton) v;
    70.  
    71.    SharedPreferences prefs = getSharedPreferences("favInfo", MODE_PRIVATE);
    72.    SharedPreferences.Editor editor = prefs.edit();
    73.  
    74.    // get the unique key by getting the tag of the image button
    75.    String c = v.getTag().toString();
    76.    String key = "fav"+c;
    77.  
    78.    // get value stored with that key, default: if no value exists take 0
    79.    String value = prefs.getString(key, "0");
    80.  
    81.    // check if value of favorite key is 0,
    82.    // set image resource dependent on what value is stored behind the key
    83.    if (value.equals("0")) {
    84.        favouriteButton.setImageResource(R.drawable.heart_red);
    85.    } else {
    86.        favouriteButton.setImageResource(R.drawable.heart);
    87.    }
    88.  
    89.    // do some magic text dependent on what value is set
    90.    if (value.equals("1")) {
    91.        Toast.makeText(SuggestionActivity.this, "No favourite anymore...",
    92.                Toast.LENGTH_SHORT).show();
    93.    } else {
    94.        Toast.makeText(SuggestionActivity.this, "Woah, new favourite!",
    95.                Toast.LENGTH_SHORT).show();
    96.    }
    97.  
    98.    String isFav;
    99.  
    100.    // switch value to opposite
    101.    if (value.equals("0")) {
    102.        isFav = "1";
    103.    } else {
    104.        isFav = "0";
    105.    }
    106.  
    107.    // store shared preferences
    108.    editor.putString(key, isFav);
    109.    editor.commit();
    110. }
    111. }
    In sum: The ImageButton state of each item in the ViewPager is already stored as SharedPreferenecs in form of tags 0/1. After clicking the menu item with id @show_favorites, I only want to show the items with 1 as stored value.

    How can I do this? Thank you for your advice!
     



    1. Download the Forums for Android™ app!


      Download

       
  2. Deleted User

    Deleted User Guest

    Hi and welcome to Android Forums. Firstly, thanks for including enough code to illustrate your issue. Not many people do that initially.
    I would implement a solution something like this -

    - Add a boolean flag variable called favourites into your SwipeAdapter class
    - Add a setter method on the same class, which will set the value of this variable

    Code (Text):
    1.  
    2. public class SwipeAdapter extends PagerAdapter  {
    3.   ...
    4.   private boolean favourites;
    5.  
    6.   ...
    7.   public void setFavourites(boolean value) {
    8.     this.favourites = value;
    9.   }
    10.  
    So in your MainActivity class, you can set the value when the favourite menu item is selected:

    Code (Text):
    1.  
    2. case R.id.show_favorites:
    3.            Intent favIntent = new Intent(activity, SuggestionActivity.class);
    4.            
    5.            adapter.setFavourites(true);
    6.            ...
    7.  
    Now the instantiateItem() method of your SwipeAdapter class must check the value of the 'favourites' variable, and do the correct thing. So if it has a value of 'true', then you'll want to skip over the items which aren't marked as favourites. I'll leave you to have a think about how to do that :)
     
  3. chackbusch

    chackbusch Lurker
    Thread Starter

    Thank you for your feedback! That sounds good. I'll give it a try today and tell you if it works or if there is a problem. :)
     
  4. chackbusch

    chackbusch Lurker
    Thread Starter

    What happens when menu item is clicked:

    Code (Text):
    1. @Override
    2. public boolean onOptionsItemSelected(MenuItem item) {
    3.     switch (item.getItemId()) {
    4.         case R.id.go_home:
    5.             Intent homeIntent = new Intent(activity, CategoryActivity.class);
    6.  
    7.             startActivity(homeIntent);
    8.             return true;
    9.         case R.id.show_favorites:
    10.             Intent favIntent = new Intent(activity, SuggestionActivity.class);
    11.  
    12.             adapter.setFavorites("showFav");
    13.  
    14.             startActivity(favIntent);
    15.             return true;
    16.         case R.id.show_all:
    17.             Intent sugIntent = new Intent(activity, SuggestionActivity.class);
    18.  
    19.             adapter.setFavorites("showAll");
    20.  
    21.             startActivity(sugIntent);
    22.             return true;
    23.         default:
    24.             // If we got here, the user's action was not recognized.
    25.             // Invoke the superclass to handle it.
    26.             return super.onOptionsItemSelected(item);
    27.     }
    28. }
    I added
    Code (Text):
    1. adapter.setFavorites("showAll");
    to the onCreate function in the Main Activity in order to avoid NullPointerException.

    In my adapter class I added your code and tried to upgrade the instantiateItem method:

    Code (Text):
    1. @Override
    2. public Object instantiateItem(ViewGroup container, int position) {
    3.     layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    4.     View item_view = layoutInflater.inflate(R.layout.swipe_layout,container,false);
    5.     ImageView imageView = (ImageView) item_view.findViewById(R.id.swipe_image);
    6.     TextView textView = (TextView) item_view.findViewById(R.id.image_count);
    7.     ImageButton imageButton = (ImageButton) item_view.findViewById(R.id.favourite_button);
    8.  
    9.     SharedPreferences prefs = context.getSharedPreferences("favInfo", Context.MODE_PRIVATE);
    10.  
    11.     imageView.setImageResource(image_resources[position]);
    12.  
    13.     // set tag for details
    14.     imageView.setTag(position);
    15.  
    16.     textView.setText("[" + (position + 1) + "/" + image_resources.length + "]");
    17.  
    18.     // get the unique key consisting of fav and the current item position
    19.     String key = "fav" + (position + 1);
    20.     imageButton.setTag(position + 1);
    21.  
    22.     String value = prefs.getString(key, "0");
    23.  
    24.     // check if value of favorite key is 0
    25.     // set image resource dependent on what value is set
    26.     if (value.equals("1")) {
    27.         imageButton.setImageResource(R.drawable.heart_red);
    28.     } else {
    29.         imageButton.setImageResource(R.drawable.heart);
    30.     }
    31.  
    32.     // do that if only favorites should appear
    33.     if (favorites.equals("showFav")) {
    34.         // get the unique key consisting of fav and the current item position
    35.         String fav_key = "fav" + (position + 1);
    36.  
    37.         String fav_value = prefs.getString(fav_key, "0");
    38.  
    39.         // remove view if no favorite
    40.         if (fav_value.equals("0")) {
    41.             destroyItem(container, position, item_view);
    42.             // container.removeView(item_view);
    43.         } else {
    44.             container.addView(item_view);
    45.         }
    46.     } else {
    47.         // add view if no filter for favorites
    48.         container.addView(item_view);
    49.     }
    50.  
    51.     return item_view;
    52. }
    However: no matter what I click, it always shows every item. None of the item gets skipped after I click the "Only favorites" menu item. What do I do wrong and would this even be the right way what I'm trying?

    Looking forward to your advice...
     
  5. Deleted User

    Deleted User Guest

Loading...

Share This Page

Loading...