2013-08-30 27 views
1

在我的申請中,A是一項將首先推出的活動。代碼如下:何時getApplicationContext將被分配?

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。如果是這樣,那麼「經理」將爲空,導致空指針異常。真的發生了什麼可能導致NameNotfoundException?請幫忙。

+1

顯示您的堆棧跟蹤 –

+0

當您使用getApplicationContext()意味着它是整個應用程序上下文,當您使用Activity.this則用於特定的上下文爲那個活動... – Piyush

+0

@PiyushGupta:我知道。但是如何出現崩潰?它是一個角落案例。對於許多用戶來說,這些代碼的功能就像一個魅力。但是我從大約400個用戶面對這個問題。我實際上是使用當前獲取的版本更新我的數據庫。如果拋出異常,我就抓住它,從而跳過更新代碼。我是在這裏丟失數據。請幫忙。 – madhu

回答

0

使用

PackageManager manager = A.this.getPackageManager(); 
+0

我的方法錯了嗎?請讓我知道如何。我真的需要知道這裏的原因。 – madhu

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.

+0

雖然這種方法已經在很多用戶身上起作用了。但對於其餘的,它沒有。如果getApplication上下文有問題,我會得到空指針異常?因爲我使用它來獲取包管理器。 – madhu

相關問題