Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resource ID through getIdentifier returns 0

Tags:

java

android

xml

private String isChecked(String id) {
    id = "R.id." + id;
    int ID = getResources().getIdentifier(id, "id", "com.example.android.justjava");
    CheckBox checkBox = (CheckBox) findViewById(ID);
    return String.valueOf(checkBox.isChecked());
}

I pass in a value of check_whipped_cream(A check box's id in a xml document) into the function above, but when I debug the app, the variable ID always becomes equal to 0. What is wrong with it?

NOTE: The isChecked() called in the last line method is from the CheckBox class.

like image 826
Siddharth Venu Avatar asked Nov 16 '25 12:11

Siddharth Venu


1 Answers

the big issue is

 id = "R.id." + id;

you are asking android to look for R.id.id into id since you are providing already "id" as second argument. It should be just id. To avoid issues with misspelled words you should rely on the return value of .getPackageName() instead of hard coding it on your own.

Use

get rid of id = "R.id." + id;

getResources().getIdentifier(id, "id", getPackageName());
like image 95
Blackbelt Avatar answered Nov 19 '25 01:11

Blackbelt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!