空值的未知原因

时间:2018-09-27 13:11:16

标签: java android nullpointerexception

我在下面的代码行中出现错误

String appName = (String) packageManager.getApplicationLabel(applicationInfo);

但是,标签定义明确且正确,并且页面之前运行良好。不确定为什么抛出空指针异常?任何人都可以提供帮助,而不仅仅是将我重定向到另一个问题?

    Java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.content.pm.ApplicationInfo.loadLabel(android.content.pm.PackageManager)' on a null object reference at android.app.ApplicationPackageManager.getApplicationLabel(ApplicationPackageManager.java:1550)

代码:

    @Override
public int onStartCommand(Intent intent, int flags, int startId){
    Context context = getApplicationContext();
    ApplicationInfo applicationInfo = null;

    HashSet<String> app = new HashSet<String>(); 

    SharedPreferences setting = getSharedPreferences("Preferences", 0);

    //Stores apps that are blocked//
    HashSet<String> blockedApplications = (HashSet<String>) setting.getStringSet("HashSet", app);

    String appsInForeground = printForegroundTask();


    PackageManager packageManager = getPackageManager();


    try {
        applicationInfo = packageManager.getApplicationInfo(appsInForeground, 0);
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    String appName = (String) packageManager.getApplicationLabel(applicationInfo);

    if (blockedApplications.contains(appName)) {
        showHomeScreen();
        //Show my dialog instead of just homescreen //
        Intent dialogIntent = new Intent(this, MyDialog.class);
        dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(dialogIntent);
    }else{
        //Toast.makeText(this, "App in foreground: " + appsInForeground, Toast.LENGTH_LONG).show();
    }
    return Service.START_REDELIVER_INTENT;

0 个答案:

没有答案