我在使用asynctask的getPackageManager方法中遇到错误

时间:2018-11-12 08:43:36

标签: android android-asynctask android-package-managers

在这里遇到错误

 try {
           PackageManager pm = MyApplication.getInstance().getPackageManager();
           PackageInfo packageInfo = process.getPackageInfo(MyApplication.getInstance(), 0);
           info.name = packageInfo.applicationInfo.loadLabel(pm).toString();
     } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            continue;
 }

日志错误为:

  Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.PackageManager android.app.Application.getPackageManager()' on a null object reference
    at com.example.bugfreeram.bugfreeanti.external.ProcessScanTask.doInBackground(ProcessScanTask.java:52)
    at com.example.bugfreeram.bugfreeanti.external.ProcessScanTask.doInBackground(ProcessScanTask.java:21)

MyApplcication类是这样的:

public class MyApplication extends Application {

    private static MyApplication sInstance;

    public static Application getInstance() {
       return sInstance;
    }

   @Override
   public void onCreate() {
       super.onCreate();
       sInstance = this;
   }
}

我在StackOverflow上尝试了所有答案,请帮助我。 预先谢谢你

2 个答案:

答案 0 :(得分:0)

使用Context对象获取PackageManager。 像这样:

PackageManager manager = context.getPackageManager();

答案 1 :(得分:0)

更改您的AndroidManifest.xml并将MyApplication类添加到android:name

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.app.packagename">
.
.

<application
    android:name=".MyApplication"
    .
    .

</application>