引用代码中的字符串变量时出现java.lang.NullPointerException [英] java.lang.NullPointerException while referencing string variable in code
问题描述
我正在尝试引用存储在xml中的一些字符串.我收到此错误:
I'm trying to reference a few strings that I've stored in an xml. I'm getting this error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method
'android.content.res.Resourcesandroid.content.Context.getResources()'
on a null object reference at
android.content.ContextWrapper.getResources(ContextWrapper.java:86)
在我使用getString
从xml引用变量的行中的
.
on the line where I'm using getString
to reference the variable from xml.
看到错误的行:
private String CLIENT_ID = getString(R.string.MY_CLIENT_ID);
完全错误:
com.android.example.helloworld E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.android.example.helloworld, PID: 8408
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.android.example.helloworld/com.android.example.helloworld.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2236)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.content.ContextWrapper.getResources(ContextWrapper.java:86)
at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:74)
at android.content.Context.getString(Context.java:377)
at com.android.example.helloworld.MainActivity.<init>(MainActivity.java:55)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1606)
at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
我的/res/values/variables.xml文件:
My /res/values/variables.xml file:
<string name="MY_CLIENT_ID">foo1</string>
<string name="MY_CLIENT_SECRET">bar1</string>
我的AndroidManifest.xml文件
My AndroidManifest.xml file
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="Hello!"
android:theme="@style/AppTheme" >
<meta-data
android:name="CLIENT_ID"
android:value="@string/MY_CLIENT_ID" />
<meta-data
android:name="CLIENT_SECRET"
android:value="@string/MY_CLIENT_SECRET" />
<activity
android:name="com.android.example.helloworld.MainActivity"
android:label="Hello!" >
<intent-filter android:label="@string/app_name" >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
我对MainActivity.java文件的部分代码:
My partial code for MainActivity.java file:
public class MainActivity extends ActionBarActivity implements myListener {
/* One of the very first lines that are executed throw the nullpointerexception */
private String CLIENT_ID = getString(R.string.MY_CLIENT_ID);
private String CLIENT_SECRET = getString(R.string.MY_CLIENT_SECRET);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
temp = (TextView) findViewById(R.id.temp);
obj = new foo(CLIENT_ID, CLIENT_SECRET, this);
obj.bar()
}
}
这是我到目前为止所做的.
Here's what I've done so far.
1)我正在使用 http://developer.android. com/guide/topics/resources/string-resource.html 作为参考.
1) I'm using http://developer.android.com/guide/topics/resources/string-resource.html as a reference.
2)如果我在开始时对值进行硬编码并运行该应用程序,则它可以正常工作.当我尝试从xml引用值时,只会收到上述错误.
2) If I hardcode the values in the beginning and run the app it works. I only get the said error when I try to reference the values from xml.
3)我在google和stackexchange上对此主题进行了大量搜索,并尝试了stackexchange链接上建议的几种方法,例如:
3) I have searched quite a bit on this topic on google and stackexchange and have tried several approaches suggested on the stackexchange links such as:
-
创建并调用如下方法.我在此方法中遇到了同样的错误.
creating and calling a method like below. I get that same error inside this method.
public String getStringResourceByName(String resourceName) {
String packageName = "com.android.example.helloworld";
Log.i("-- package name --",packageName);
int resId = this.getResources().getIdentifier(resourceName, "string", packageName);
String resName = getString(resId);
Log.i("-- resource name -- ",resName);
return resName;
}
使用MainActivity.this专门在上述方法中
Using MainActivity.this specifically in the above method
public String getStringResourceByName(String resourceName) {
String packageName = "com.android.example.helloworld";
Log.i("-- package name --",packageName);
int resId = MainActivity.this.getResources().getIdentifier(resourceName, "string", packageName);
String resName = getString(resId);
Log.i("-- resource name -- ",resName);
return resName;
}
所有更改都向我抛出相同的错误.
All of the changes throw the same error back at me.
有人可以指导我我在这里想念什么吗?希望我已经提供了足够的数据.
Can someone guide me on what am I missing here? I hope I've provided with sufficient data.
推荐答案
private String CLIENT_ID = getString(R.string.MY_CLIENT_ID);
如果在类初始化时初始化字段,则在onCreate()
之前调用getString()
,因此上下文尚未初始化.最好像这样使用它
If you initialize the field on class initialization, you are calling getString()
before onCreate()
, and thus the Context has not initialized. Better use it like this
public void onCreate(final Bundle bundle) {
// Other code
CLIENT_ID = getString(R.string.MY_CLIENT_ID);
}
我也强烈建议您不要缓存字符串,因为如果语言发生更改,您可能会得到错误的翻译(这个问题已经发生在我身上,因此我从经验中就可以这么说).而是在需要时使用getString()
.
Also I strongly advise against caching the strings, because you can get wrong translations if the language has changed (this problem already happened to me so I say this from experience). Instead, use getString()
whenever you need it.
这篇关于引用代码中的字符串变量时出现java.lang.NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!