基于设备密度切换图像时出现NullPointerException

时间:2014-11-11 07:05:14

标签: android

我有一个徽标图片,我在我的应用程序的启动/欢迎屏幕上显示。当我最近使应用程序符合xxx-hdpi屏幕尺寸时,我遇到了一个奇怪的问题:

  1. 我创建了一个更大的徽标图像,并在名称中添加了“_large”。我把那个和另一个图像放在drawable文件夹中。
  2. 在活动的onCreate功能中,我正在检查设备的密度并打开相应的图像:

  3. float MAX_XX_SCALE = 3.0F; //Maximum scale of xx-hdpi screens.
    ImageView img = (ImageView) findViewById(R.id.myImg); // ImageView containing the image.
    if (getResources().getDisplayMetrics().density > MAX_XX_SCALE) 
        img.setImageDrawable(getResources().getDrawable(R.drawable.logo_large));
    else 
        img.setImageDrawable(getResources().getDrawable(R.drawable.logo));`
    

    但是我在执行应用程序时遇到NullPointerException

    这是我的logcat

    11-11 11:53:46.625: E/AndroidRuntime(919):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1955)
    11-11 11:53:46.625: E/AndroidRuntime(919):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980)
    11-11 11:53:46.625: E/AndroidRuntime(919):  at android.app.ActivityThread.access$600(ActivityThread.java:122)
    11-11 11:53:46.625: E/AndroidRuntime(919):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146)
    11-11 11:53:46.625: E/AndroidRuntime(919):  at android.os.Handler.dispatchMessage(Handler.java:99)
    11-11 11:53:46.625: E/AndroidRuntime(919):  at android.os.Looper.loop(Looper.java:137)
    11-11 11:53:46.625: E/AndroidRuntime(919):  at android.app.ActivityThread.main(ActivityThread.java:4340)
    11-11 11:53:46.625: E/AndroidRuntime(919):  at java.lang.reflect.Method.invokeNative(Native Method)
    11-11 11:53:46.625: E/AndroidRuntime(919):  at java.lang.reflect.Method.invoke(Method.java:511)
    11-11 11:53:46.625: E/AndroidRuntime(919):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
    11-11 11:53:46.625: E/AndroidRuntime(919):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
    11-11 11:53:46.625: E/AndroidRuntime(919):  at dalvik.system.NativeStart.main(Native Method)
    11-11 11:53:46.625: E/AndroidRuntime(919): Caused by: java.lang.NullPointerException
    11-11 11:53:46.625: E/AndroidRuntime(919):  at com.project.android.WelcomeActivity.onCreate(WelcomeActivity.java:42)
    11-11 11:53:46.625: E/AndroidRuntime(919):  at android.app.Activity.performCreate(Activity.java:4465)
    11-11 11:53:46.625: E/AndroidRuntime(919):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
    11-11 11:53:46.625: E/AndroidRuntime(919):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1919) 
    

    这就是我在第42行:img.setImageDrawable(getResources().getDrawable(R.drawable.logo));

1 个答案:

答案 0 :(得分:0)

正如你所说的

  

而且,该死的!我把它放在setContentView()

之前

因此,您的ImageView img为空,因为您在设置内容视图之前尝试findViewById,因此请

ImageView img = (ImageView) findViewById(R.id.myImg); 

在onCreate方法中的setContentView之后因为R.id.myImg是内容视图的一部分。