• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps ViewPager Filter Items / Do Not Show All Items

chackbusch

Lurker
Jun 9, 2017
3
0
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:
<android.support.v4.view.ViewPager
   android:id="@+id/image_swipe"
   android:layout_width="match_parent"
   android:layout_height="590dp"
   android:layout_marginTop="130dp" />

The Main Layout also implements a toolbar which owns this menu item:

Code:
<item
     android:id="@+id/show_favorites"
     android:orderInCategory="100"
     android:icon="@drawable/heart_red"
     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:
public class SwipeAdapter extends PagerAdapter  {

/*
   Define the image resources for our image fragment
 */
private int[] image_resources = {
       R.drawable.img1,
       R.drawable.img2,
       R.drawable.img3,
       R.drawable.img4,
       R.drawable.img5,
       R.drawable.img6,
       R.drawable.img7,
       R.drawable.img8,
       R.drawable.img9,
       R.drawable.img10
};

private Context context;
private LayoutInflater layoutInflater;

public SwipeAdapter(Context context) {
   this.context = context;
}

/*
   Count the images in image_resources array
  */
@Override
public int getCount() {
   return image_resources.length;
}

@Override
public boolean isViewFromObject(View view, Object object) {
   return (view == (LinearLayout) object);
}

/*
   Create the page for the given position
   Set image resources and text about current position
 */
@Override
public Object instantiateItem(ViewGroup container, int position) {
   layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
   View item_view = layoutInflater.inflate(R.layout.swipe_layout,container,false);
   ImageView imageView = (ImageView) item_view.findViewById(R.id.swipe_image);
   TextView textView = (TextView) item_view.findViewById(R.id.image_count);
   ImageButton imageButton = (ImageButton) item_view.findViewById(R.id.favourite_button);

   imageView.setImageResource(image_resources[position]);

   // set tag for details
   imageView.setTag(position);

   textView.setText("["+(position+1)+"/10]");

   SharedPreferences prefs = context.getSharedPreferences("favInfo", Context.MODE_PRIVATE);

   // get the unique key consisting of fav and the current item position
   String key = "fav" + (position+1);
   imageButton.setTag(position+1);

   String value = prefs.getString(key, "0");

   // check if value of favorite key is 0
   // set image resource dependent on what value is set
   if (value.equals("1")) {
       imageButton.setImageResource(R.drawable.heart_red);
   } else {
       imageButton.setImageResource(R.drawable.heart);
   }

   container.addView(item_view);

   return item_view;
}

/*
   Remove a page for the given position
 */
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
   container.removeView((LinearLayout) object);
}
}

And my Main Activity is organized this way:

Code:
public class SuggestionActivity extends AppCompatActivity {

ViewPager viewPager;
SwipeAdapter adapter;

private final AppCompatActivity activity = SuggestionActivity.this;

@Override
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_suggestion);

   viewPager = (ViewPager) findViewById(R.id.image_swipe);
   adapter = new SwipeAdapter(this);

   viewPager.setAdapter(adapter);

   // set the toolbar for the suggestion page
   Toolbar sToolbar = (Toolbar) findViewById(R.id.suggestion_toolbar);
   setSupportActionBar(sToolbar);
};

/*
   Add options menu at view start
 */
@Override
public boolean onCreateOptionsMenu(Menu menu) {
   getMenuInflater().inflate(R.menu.suggestion_menu, menu);

   return super.onCreateOptionsMenu(menu);
}

/*
   Declare what happens when user clicks an item of the options menu
   @go_home start the CategoryActivity
   @filter TO DO
 */
@Override
public boolean onOptionsItemSelected(MenuItem item) {
   switch (item.getItemId()) {
       case R.id.go_home:
           Intent homeIntent = new Intent(activity, CategoryActivity.class);
           startActivity(homeIntent);
           return true;
       case R.id.show_favorites:
           Intent favIntent = new Intent(activity, SuggestionActivity.class);

           //
           // HERE IS WHERE I DON'T KNOW WHAT TO DO
           //

           startActivity(favIntent);

           return true;
       default:
           // If we got here, the user's action was not recognized.
           // Invoke the superclass to handle it.
           return super.onOptionsItemSelected(item);
   }
}

/*
   Method for click actions on the favorite button
   @heart grey heart symbolizes no favorite (flag 0)
   @heart_red red heart symbolizes marked as favorite (flag 1)
*/
public void onClickFav(View v) {
   ImageButton favouriteButton = (ImageButton) v;

   SharedPreferences prefs = getSharedPreferences("favInfo", MODE_PRIVATE);
   SharedPreferences.Editor editor = prefs.edit();

   // get the unique key by getting the tag of the image button
   String c = v.getTag().toString();
   String key = "fav"+c;

   // get value stored with that key, default: if no value exists take 0
   String value = prefs.getString(key, "0");

   // check if value of favorite key is 0,
   // set image resource dependent on what value is stored behind the key
   if (value.equals("0")) {
       favouriteButton.setImageResource(R.drawable.heart_red);
   } else {
       favouriteButton.setImageResource(R.drawable.heart);
   }

   // do some magic text dependent on what value is set
   if (value.equals("1")) {
       Toast.makeText(SuggestionActivity.this, "No favourite anymore...",
               Toast.LENGTH_SHORT).show();
   } else {
       Toast.makeText(SuggestionActivity.this, "Woah, new favourite!",
               Toast.LENGTH_SHORT).show();
   }

   String isFav;

   // switch value to opposite
   if (value.equals("0")) {
       isFav = "1";
   } else {
       isFav = "0";
   }

   // store shared preferences
   editor.putString(key, isFav);
   editor.commit();
}
}

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!
 
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:
public class SwipeAdapter extends PagerAdapter  {
  ...
  private boolean favourites;

  ...
  public void setFavourites(boolean value) {
    this.favourites = value;
  }

So in your MainActivity class, you can set the value when the favourite menu item is selected:

Code:
case R.id.show_favorites:
           Intent favIntent = new Intent(activity, SuggestionActivity.class);
           
           adapter.setFavourites(true);
           ...

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 :)
 
Upvote 0
- 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
- set the value when the favourite menu item is selected

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 :)

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. :)
 
Upvote 0
What happens when menu item is clicked:

Code:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.go_home:
            Intent homeIntent = new Intent(activity, CategoryActivity.class);

            startActivity(homeIntent);
            return true;
        case R.id.show_favorites:
            Intent favIntent = new Intent(activity, SuggestionActivity.class);

            adapter.setFavorites("showFav");

            startActivity(favIntent);
            return true;
        case R.id.show_all:
            Intent sugIntent = new Intent(activity, SuggestionActivity.class);

            adapter.setFavorites("showAll");

            startActivity(sugIntent);
            return true;
        default:
            // If we got here, the user's action was not recognized.
            // Invoke the superclass to handle it.
            return super.onOptionsItemSelected(item);
    }
}

I added
Code:
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:
@Override
public Object instantiateItem(ViewGroup container, int position) {
    layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View item_view = layoutInflater.inflate(R.layout.swipe_layout,container,false);
    ImageView imageView = (ImageView) item_view.findViewById(R.id.swipe_image);
    TextView textView = (TextView) item_view.findViewById(R.id.image_count);
    ImageButton imageButton = (ImageButton) item_view.findViewById(R.id.favourite_button);

    SharedPreferences prefs = context.getSharedPreferences("favInfo", Context.MODE_PRIVATE);

    imageView.setImageResource(image_resources[position]);

    // set tag for details
    imageView.setTag(position);

    textView.setText("[" + (position + 1) + "/" + image_resources.length + "]");

    // get the unique key consisting of fav and the current item position
    String key = "fav" + (position + 1);
    imageButton.setTag(position + 1);

    String value = prefs.getString(key, "0");

    // check if value of favorite key is 0
    // set image resource dependent on what value is set
    if (value.equals("1")) {
        imageButton.setImageResource(R.drawable.heart_red);
    } else {
        imageButton.setImageResource(R.drawable.heart);
    }

    // do that if only favorites should appear
    if (favorites.equals("showFav")) {
        // get the unique key consisting of fav and the current item position
        String fav_key = "fav" + (position + 1);

        String fav_value = prefs.getString(fav_key, "0");

        // remove view if no favorite
        if (fav_value.equals("0")) {
            destroyItem(container, position, item_view);
            // container.removeView(item_view);
        } else {
            container.addView(item_view);
        }
    } else {
        // add view if no filter for favorites
        container.addView(item_view);
    }

    return item_view;
}

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...
 
Upvote 0

BEST TECH IN 2023

We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.

Smartphones