资源 $NotFoundException:资源 ID #0x0

Resources $NotFoundException: Resource ID #0x0

我在 sqlite 示例中存储带有扩展名的图像名称("food.xml")。

当我获取图像名称并尝试将其设置为 ImageView 时出现此错误。

我的适配器Class

String uri = "@drawable/" + expenseCategory.getCategory_image();
int imageResource = context.getResources().getIdentifier(uri, null, context.getPackageName());
Drawable res = context.getResources().getDrawable(imageResource);
cat_img.setImageDrawable(res);

XML 文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/item_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:padding="5dp">

<LinearLayout
    android:id="@+id/image_layout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    >

    <ImageView
        android:id="@+id/item_img"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:background="@drawable/circleyellow"
        android:padding="5dp"
        android:layout_gravity="center_horizontal"
        android:src="@drawable/food" />
</LinearLayout>


<TextView
    android:id="@+id/item_cat_text"
    android:layout_width="50dp"
    android:gravity="center"
    android:layout_height="wrap_content"
    android:layout_below="@+id/image_layout"
    android:text="Food"
    android:textColor="#000"
    android:textSize="12sp" />
</RelativeLayout>

您不应包含 @drawable/,因此假设 expenseCatetory.getCategory_image(); 将 return 文件名存在于您的可绘制对象中,那么这应该有效:

//String uri = "@drawable/" + expenseCategory.getCategory_image();
String fileName = expenseCategory.getCategory_image();
//int imageResource = context.getResources().getIdentifier(uri, null, context.getPackageName());
int imageResource = resources.getIdentifier(fileName, "drawable", context.getPackageName());
Drawable res = context.getResources().getDrawable(imageResource);
cat_img.setImageDrawable(res);

你做错了..

试试这个方法

int resourceId = context.getResources().getIdentifier(imageName, "drawable", context.getPackageName());
if (resourceId != 0)
    cat_img.setImageDrawable(context.getResources().getDrawable(resourceId));
else
    cat_img.setImageDrawable(context.getResources().getDrawable(R.drawable.some_icon));

从 URI 变量中删除扩展名。你应该uri应该看起来像@drawable/food

context.getResources().getIdentifier("@drawable/food", null, context.getPackageName());

相同
context.getResources().getIdentifier("food", "drawable", context.getPackageName());

还要确保检查您的 resId 不是 0