PackageManager.NameNotFoundException [英] PackageManager.NameNotFoundException

查看:550
本文介绍了PackageManager.NameNotFoundException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 .java 文件:

 ....

 import android.content.pm.ApplicationInfo;
 import android.content.pm.PackageInfo;
 import android.content.pm.PackageManager;

 ....

   /* PackageInfo packageInfo = 
   getPackageManager().getPackageInfo(getPackageName(),0);
   curVersionCode = packageInfo.versionCode;*/

   PackageManager pm = getPackageManager();
   String pn = getPackageName();
   PackageInfo pi = pm.getPackageInfo(pn,0);
   curVersionCode = pi.versionCode;

   ....

要理解我写的代码中的错误四行。如您所见,这两行代码在注释中。现在,当我尝试构建时,此代码不起作用并且在此处出现 PackageManager.NameNotFoundException 的错误。为清楚起见,我在不同的文件中使用了这段代码,并没有造成任何错误;所以不必担心包名。现在这个错误背后的原因是什么?还附加图像以清除错误。

To understand the error i wrote the code in four lines. The two line code is in the comment as you see. Now that, this code doesn't work and gives an error of PackageManager.NameNotFoundException here when i try to build. For clarity, I used this code in a different file and it caused no error there; so there is no need to worry about the package name. Now what is the cause behind this error? An image is also attached to make clear the error.

为了解决这个问题,我也尝试过这些: this.getPackageManager() getBaseContext()。getPackageManager() getApplicationContext( ).getPackageManager();但都是徒劳的。

To solve this issue i also tried like these: this.getPackageManager(), getBaseContext().getPackageManager() and getApplicationContext().getPackageManager(); But all in vain.

推荐答案

pm.getPackageInfo 抛出 PackageManager。 NameNotFoundException 需要处理。只需用try catch包装它,如下所示:

pm.getPackageInfo throws PackageManager.NameNotFoundException which needs to be handled. Just wrap it with try catch as follows:

    final PackageManager pm = getPackageManager();
    final String pn = getPackageName();
    PackageInfo pi = null;
    try {
        pi = pm.getPackageInfo(pn, 0);
    } catch (NameNotFoundException e) {
        //LOG the exception
    }
    curVersionCode = pi!=null ? pi.versionCode:-1;

这篇关于PackageManager.NameNotFoundException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆