Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android find resource by id during the runtime

If I get the error "android.content.res.Resources$NotFoundException: Resource ID #0x7f050007 type #0x12 is not valid" can I find some what this resource is if I know its ID?

        ListView list = (ListView)findViewById(R.id.messages_list_view);
        list.setAdapter(new ArrayAdapter<String>(context,
        R.layout.messages_list, headers));

messages_list.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/messages_list_layout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <ListView android:id="@+id/messages_list_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>
like image 687
Sergey Avatar asked Oct 11 '11 07:10

Sergey


People also ask

How do I find my resource ID Android?

int resourceId = this. getResources(). getIdentifier("nameOfResource", "id", this.

What is the use of getResources () in Android?

The Android resource system keeps track of all non-code assets associated with an application. You can use this class to access your application's resources. You can generally acquire the Resources instance associated with your application with getResources() .


2 Answers

I Got this error when using ListView in a Fragment.

Resolved by moving the setAdapter lines to the onViewCreated function of the Fragment. (makes sense that before the view is created the ListView is invalid).

so you get :

public void onViewCreated(View view,Bundle savedInstanceState){
    ListView list = (ListView) getView().findViewById(R.id.thelist);
    list.setAdapter(mAdapter);
}
like image 154
Oren Avatar answered Nov 30 '22 23:11

Oren


For those whom other mentioned solutions don't work.

I did this silly mistake:-

setContentView(R.id.something);

Instead of

setContentView(R.layout.something);

Corrected that, and error was gone :D

like image 37
Shishir Gupta Avatar answered Nov 30 '22 23:11

Shishir Gupta