Java 尝试在android中使用getResources对空对象调用虚拟方法

Java 尝试在android中使用getResources对空对象调用虚拟方法,java,android,android-studio,Java,Android,Android Studio,我正在使用getResources()获取strings.xml文件中的字符串值。我在类中创建了一个类似的变量: public class Example extends Activity { String okhttp_tp = getResources().getString(R.string.okhttp_tp); // The rest of my script. } 当我想像这样将其与OKhttp请求一起使用时,.addHeader(“X-Client-Type”,OKh

我正在使用
getResources()
获取
strings.xml
文件中的字符串值。我在类中创建了一个类似的变量:

public class Example extends Activity {
   String okhttp_tp = getResources().getString(R.string.okhttp_tp);
   // The rest of my script.
}
当我想像这样将其与OKhttp请求一起使用时,
.addHeader(“X-Client-Type”,OKhttp\u-tp)
当我想启动我的应用程序时,它会直接给我这个错误:

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();
}
但这些都不起作用,应用程序在启动后崩溃。我错过什么了吗?我忘了什么


谢谢你的帮助

您只能在活动生命周期的
onCreate()
或更高版本中访问资源。实例初始化阶段太早

有一种更好、更有效的方法可以做到这一点。 您可以创建一个静态全局常量变量,而不是将其保存在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();
}

确保在任何方法中调用
getResources
,而不是在类级别调用。谢谢,我会尝试的。谢谢,我会尝试的。(请注意,您有一个语法错误,它必须是
@Override
我尝试了您的解决方案,但现在我想访问
onCreate()之外的变量)
函数,你能告诉我怎么做吗?谢谢!但它为我返回了
null
值,而不是初始化后你需要使用的值。我这样做了,但它仍然为我返回null。