什么时候准确分配getApplicationContext?

时间:2013-08-30 10:21:12

标签: android

在我的应用程序中,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在上面的代码中不能为null。如果是,则“manager”将为null,从而导致空指针异常。可能真的发生了什么导致NameNotfoundException?请帮忙。

2 个答案:

答案 0 :(得分:0)

使用

 PackageManager manager = A.this.getPackageManager();

答案 1 :(得分:0)

这里应该使用的Contextthis,即活动背景。

请注意:

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.