Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/201.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 尝试以编程方式获取drawables资源时出错_Java_Android - Fatal编程技术网

Java 尝试以编程方式获取drawables资源时出错

Java 尝试以编程方式获取drawables资源时出错,java,android,Java,Android,我不熟悉android和java。我正在尝试从我的drawables文件夹中获取图像,以编程方式显示在应用程序中。但是,getIdentifier()始终是空对象引用 当我运行此代码时 int imageResource = getResources().getIdentifier("image", "drawable", getPackageName()); //error here System.out.println(imageResource);

我不熟悉android和java。我正在尝试从我的drawables文件夹中获取图像,以编程方式显示在应用程序中。但是,
getIdentifier()
始终是空对象引用

当我运行此代码时

int imageResource = getResources().getIdentifier("image", "drawable", getPackageName()); //error here
System.out.println(imageResource); //doesn't get to this
整个应用程序崩溃,我出现以下错误:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: net.mobiledevelopment.app, PID: 6663
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{net.mobiledevelopment.app/net.mobiledevelopment.app.Shop}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
非常感谢您的帮助。

代码现在可以运行了


我没有在onCreate()方法中调用getResources()。这显然很重要。

如果您试图从drawable中获取图像并在代码下方的imageview中显示drawable


getResources().getDrawable(R.drawable.your_image)

您的图像是否在
res\drawables
中?你想用它做什么?将其设置为
ImageView
?何时调用此方法?