我使用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();
}
但是這些工作都不起作用,應用程序在啓動後崩潰。我想念什麼?我忘了什麼?
感謝您的幫助!
確保調用''getResources任何方法內,而不是在一流水平 –