2016-06-15 26 views
-2

我使用getResources()獲取strings.xml文件中的字符串值。我創建了我的課類似這樣的變量:嘗試使用getResources在null對象上調用虛擬方法android

public class Example extends Activity { 
    String okhttp_tp = getResources().getString(R.string.okhttp_tp); 
    // The rest of my script. 
} 

而當我想以這樣的.addHeader("X-Client-Type", okhttp_tp)的OKhttp要求使用它,它直接給了我這個錯誤,當我想要啓動我的應用程序:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference 
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference 

我曾嘗試以下規則:

1. String okhttp_tp = getResources().getString(R.string.okhttp_tp); 
2. String okhttp_tp = (String) getResources().getString(R.string.okhttp_tp); 
3. String okhttp_tp = getResources().getString(R.string.okhttp_tp).toString(); 
4. String okhttp_tp = (String) getResources().getString(R.string.okhttp_tp).toString(); 
5. String okhttp_tp = Example.this.getResources().getString(R.string.okhttp_tp); 

我也試着這樣做:

String doPostRequest(String url, String json[]) throws IOException { 
    Request request = new Request.Builder() 
     .addHeader("X-Client-Type", getResources().getString(R.string.okhttp_tp).toString()) 
     .url(okhttp_login_url) 
     .url(url) 
     .post(body) 
     .build(); 
} 

但是這些工作都不起作用,應用程序在啓動後崩潰。我想念什麼?我忘了什麼?

感謝您的幫助!

+1

確保調用''getResources任何方法內,而不是在一流水平 –

回答

0

有一個更好的和有效的方法來做到這一點。 您可以創建一個靜態全局常量變量,而不是將其保存在strings.xml中並進行檢索。

AppConstants.java

class AppConstants{ 
public static final String ok_http = "value here"; 
} 

使用

String doPostRequest(String url, String json[]) throws IOException { 
    Request request = new Request.Builder() 
     .addHeader("X-Client-Type",AppConstants.ok_http) 
     .url(okhttp_login_url) 
     .url(url) 
     .post(body) 
     .build(); 
} 
+0

謝謝,我會盡力的。 (注意,你有一個語法錯誤,它必須是'@ Override',這個錯誤必須是'@ Override' – Jer

+0

哈哈,打字缺乏IDE效果。希望它的工作 –

+0

我試過你的解決方案,但現在我想訪問'onCreate()'函數之外的變量,你可以告訴我怎樣才能做到這一點嗎? – Jer

0

只能在活動生命週期中的onCreate()或更高版本中訪問資源。實例初始化階段爲時尚早。

+0

謝謝,我會盡力的。 – Jer

相關問題