如何修复BootReciever java.lang.NullPointerException?

时间:2014-09-18 10:10:38

标签: java android eclipse nullpointerexception broadcastreceiver

我收到此错误,但我不知道如何修复它:

09-18 10:14:34.482: E/Trace(787): error opening trace file: No such file or directory (2)
09-18 10:14:34.542: W/ResourceType(787): No package identifier when getting value for resource number 0x00000000
09-18 10:14:34.683: E/BootReceiver(787): java.lang.NullPointerException

有人可以告诉我如何修复此错误,

BroadcastReceiver java:

public class BootReceiver extends BroadcastReceiver {

    private static final String TAG="BootReceiver";

    @Override 
    public void onReceive(Context context,Intent intent) {
        try {
            DisplayMetrics metrics = new DisplayMetrics(); 
            WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            windowManager.getDefaultDisplay().getMetrics(metrics);
            int height = metrics.heightPixels; 
            int width = metrics.widthPixels;
            Bitmap tempbitMap = BitmapFactory.decodeResource(context.getResources(), MainActivity.tophone);
            WallpaperManager wallpaperManager = WallpaperManager.getInstance(context); 
            wallpaperManager.setWallpaperOffsetSteps(1, 1);
            wallpaperManager.suggestDesiredDimensions(width, height);
            try {
                wallpaperManager.setBitmap(tempbitMap);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch(Exception e){
            Log.e(TAG,e.toString());
        }
    }
}

1 个答案:

答案 0 :(得分:2)

应用程序无法找到MainActivity.tophone,因为您的设备刚刚启动,而您的应用程序尚未打开,这意味着tophone变量尚未初始化。所以它正在触发NullPointerException因为No package identifier它意味着它无法找到具有实际为空的给定名称的资源。

解决:

  • 在广播中声明自己的价值
  • 在活动中的SharedPreference中存储值并在BroadcastReceiver
  • 中获取它