在我的申請中,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?請幫忙。
顯示您的堆棧跟蹤 –
當您使用getApplicationContext()意味着它是整個應用程序上下文,當您使用Activity.this則用於特定的上下文爲那個活動... – Piyush
@PiyushGupta:我知道。但是如何出現崩潰?它是一個角落案例。對於許多用戶來說,這些代碼的功能就像一個魅力。但是我從大約400個用戶面對這個問題。我實際上是使用當前獲取的版本更新我的數據庫。如果拋出異常,我就抓住它,從而跳過更新代碼。我是在這裏丟失數據。請幫忙。 – madhu