1

在我的应用程序中,A 是一个将首先启动的活动。代码如下:

    public class A extends Activity {

    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //Here I'm checking if the user has already got registered, using shared preference. If yes, I want to fetch the version of this application and start Activity B. Other wise perform some other operation.

  if(Registered) {

    //Here, I'm trying to fetch the version of my own application.

    PackageManager manager = getApplicationContext()
                            .getPackageManager();
                    PackageInfo info;
                    try {
                        info = manager.getPackageInfo(getApplicationContext()
                                .getPackageName(), 0);
                        String version = info.versionName;

    } catch(NameNotFoundException e) {
    e.printStackTrace();
    }
    }  
    }
    }

因此,一旦我的应用程序安装完毕,就会执行此代码。在这里,我得到了 NameNotFoundException。它被抓住了,但仍然给我带来了一些问题。

上述代码中的 getApplicationContext 不能为空。如果是,那么“manager”将为空,导致空指针异常。导致 NameNotfoundException 的真正原因可能是什么?请帮忙。

4

2 回答 2

0

Use

 PackageManager manager = A.this.getPackageManager();
于 2013-08-30T10:25:35.370 回答
0

这里Context应该使用的是thisActivity Context。

注意:

Application Cotext : Return the context of the single, global Application object of the current process. This generally should only be used if you need a Context whose lifecycle is separate from the current context, that is tied to the lifetime of the process rather than the current component.

于 2013-08-30T10:31:22.187 回答