user5866501 user5866501 -5 years ago 149
Android Question

Android RecyclerView pass and display Item data depending on condition

I have a RecyclerViewActivity and data for RecyclerView:

// get a reference to recyclerView
RecyclerView recyclerView = (RecyclerView) findViewById(;

// this is data for recyclerview

CardData cardData[] = {
new CardData("Bread", R.drawable.bread),
new CardData("Dairy", R.drawable.dairy),
new CardData("Meat", R.drawable.meat) ...}

Each CardData connected to different Activity with simple ListView.

Now I used Shared Preferences and boolean variable to check if there are some items in every ListView. After check completes - pass true/ false value to the RecyclerViewActivity:

SharedPreferences pref = getSharedPreferences("filename", MODE_PRIVATE);
Boolean a = pref.getBoolean("key1", false);
Boolean b = pref.getBoolean("key2", false);
Boolean c = pref.getBoolean("key3", false);

Now what I need to do - is to display CardData depending on a/b/c values. If I receive a: true - need to display some additional image indicator in my data set. Something like this:

CardData cardData[] = {
if (!a) {
new CardData("Bread", R.drawable.bread, R.drawable.indicator)
else {
new CardData("Bread", R.drawable.bread) };

if (!b) {
new CardData("Dairy", R.drawable.dairy, R.drawable.indicator)
else {
new CardData("Dairy", R.drawable.dairy};


The problem is that I don't now where and how exactly can I set this condition. Inside CardData like above it does'n work - gives me a syntax error..

Any help will be appreciate!

Answer Source

The problem is that you aren't breaking it into smaller, more manageable steps.

You can do it in this way:

// initialise the array with size 3
CardData cardData[] = new CardData[3];

// start adding elements now
// insert first object by checking flag "a"
if (a) {
    cardData[0] = new CardData("Bread", R.drawable.bread);
else {
    cardData[0] = new CardData("Bread", R.drawable.bread, R.drawable.indicator);

// insert second object by checking flag "b"
if (b) {
    cardData[1] = new CardData("Dairy", R.drawable.dairy);
else {
    cardData[1] = new CardData("Dairy", R.drawable.dairy, R.drawable.indicator);

// and so on...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download