Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java android getResources().getIdentifier()

Tags:

java

android

How do I get the int id value from R. for an id? When I use getIdentifier its just returns 0.

 int i = getArguments().getInt(SELECTION_NUMBER);
 String drawerSelection = getResources().getStringArray(R.array.drawerSelection_array)[i];

int panelId = this.getResources().getIdentifier(drawerSelection.toLowerCase(),"id",getActivity().getPackageName());

Edit

Xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<ListView
    android:id="@+id/Bus_Schedules"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >
</ListView>

</LinearLayout>

log

06-10 21:24:30.372: I/System.out(3572): Selection = Bus_Schedules
06-10 21:24:30.372: I/System.out(3572): panelId = 0

R.java

    public static final class id {
    public static final int Bus_Schedules=0x7f090004;
    public static final int basemenu=0x7f090005;
    public static final int content_frame=0x7f090001;
    public static final int drawer_layout=0x7f090000;
    public static final int left_drawer=0x7f090002;
like image 862
Spik330 Avatar asked May 31 '13 16:05

Spik330


People also ask

What is getIdentifier Android?

getIdentifier, is to obtain resources dynamically. The are many use cases, for example if you have several resources with the same name ending with a numeric index, then you could make a for loop and autogenerate the name dynamically, so "my_red_box_1", "my_red_box_2", etc.

What is resource reference syntax in Android?

Regardless of the type of resource, all Android resources are identified by their IDs in Java source code. The syntax for ID in the XML file is called resource-reference syntax.

What is resource value in Android Studio?

Resources are the additional files and static content that your code uses, such as bitmaps, layout definitions, user interface strings, animation instructions, and more.


2 Answers

Just checked back in a project I'm writing right now:

int id = getResources().getIdentifier("resourcename", "drawable", getPackageName());

getResources returns int.

UPDATE: Check R.array.drawerSelection_array to include only ID's of existing elements.

like image 159
David Jashi Avatar answered Oct 04 '22 19:10

David Jashi


The problem appears to be that you are converting drawerSelection to lower case. As is clear in the R.java file, the case of the identifier is preserved. Try calling:

int panelId = this.getResources().getIdentifier(drawerSelection,"id",getActivity().getPackageName());
like image 34
Ted Hopp Avatar answered Oct 04 '22 17:10

Ted Hopp