13

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;
Spik330
  • 502
  • 4
  • 6
  • 19
  • When it returns 0, it means that the id was not found. What's the value of `drawerSelection`? Have you confirmed that you have an id resource defined with that name? – Ted Hopp May 31 '13 at 16:41
  • You need to post some more information about the problem to get any better response. Use the debugger (or a log statement) to determine exactly what value `drawerSelection` has. Post the applicable xml that defines the corresponding id as a resource. (By the way, you can leave out the default locale argument in the call to `toLowerCase`; that's what it will use anyway and it just clutters up your code.) – Ted Hopp Jun 11 '13 at 04:16

3 Answers3

25

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());
Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
9

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.

David Jashi
  • 4,490
  • 1
  • 21
  • 26
-1

Try this method.

public static int getResId(String fieldName, Context context, Class<?> c) {

    try {
        Field field= c.getDeclaredField(fieldName);
        return field.getInt(field);
    } catch (Exception e) {
        return 0;
    } 
}

Calling

 //edtUserName is my field id
 getResId("edtUserName", context, id.class);
Adnan
  • 5,025
  • 5
  • 25
  • 44