I'm trying to get different ID with for
. What I have is a CardView with diferent IDs for each card and I would like to get data when clicked.
I have done this:
public void setToggleEvent(final GridLayout mainGrid) {
for ( int i = 0; i < mainGrid.getChildCount(); i++){
count = i;
final CardView cardView = (CardView)mainGrid.getChildAt(i);
cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(cardView.getCardBackgroundColor().getDefaultColor() == -1) {
for (int f = 0; f < mainGrid.getChildCount(); f++){
if (f == count) {
int index = f;
String idFood = "food" + index;
int resID = getResources().getIdentifier(idFood, "id", getPackageName());
foodName = findViewById(resID);
foodName.getText();
}
}
//canvi color de fons
cardView.setCardBackgroundColor(Color.parseColor("#FF6F00"));
foodData = foodName.toString();
selectedVegetables.add(foodData);
} else {
cardView.setBackgroundColor(Color.parseColor("#FFFFFF"));
Toast.makeText(VegetablesActivity.this, "Food Selected", Toast.LENGTH_SHORT).show();
}
}
});
}
}
Each card has a ID called: food0, food1, food2....
As you can see in the code I did this to get the IDs:
String idFood = "food" + index;
int resID = getResources().getIdentifier(idFood, "id", getPackageName());
foodName = findViewById(resID);
foodName.getText();
and then:
foodData = foodName.toString();
selectedVegetables.add(foodData);
But when I run it says that foodName
is null ( java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.TextView.getText()' on a null object reference
)
and is in this line where the error shows up
foodName.getText();
Any idea? Sorry for my bad english, it's not my native lenguage, hope everyone could understand this.
I surprised! this is not actually logical!
int resID
not provide you like this: "R.id.exampleId" type of id.resID Only provide you a integer value.