我想在所有活動中使用一個常量值,所以我將它寫入了string.xml文件。getResources()中的java.lang.NullPointer異常。getString(R.string.value);
現在,到獲得的.java文件價值,我如下編寫代碼:
getResources().getString(R.string.my_website); - This is 18 line of Splash Class
我打電話主類的代碼如下:
public class Splash extends Activity {
final String WebsiteURL = getResources().getString(R.string.my_website);
}
但它給我java.lang.NullPointerException
。我寫錯了什麼?
這是相關的strings.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="my_website">http://www.mytestbuddy.com</string>
</resources>
logcat的:
01-30 17:57:15.853: E/AndroidRuntime(1553): FATAL EXCEPTION: main
01-30 17:57:15.853: E/AndroidRuntime(1553): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.Mobile.mytestbuddy/com.Mobile.mytestbuddy.Splash}: java.lang.NullPointerException
01-30 17:57:15.853: E/AndroidRuntime(1553): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1569)
01-30 17:57:15.853: E/AndroidRuntime(1553): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
01-30 17:57:15.853: E/AndroidRuntime(1553): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
01-30 17:57:15.853: E/AndroidRuntime(1553): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
01-30 17:57:15.853: E/AndroidRuntime(1553): at android.os.Handler.dispatchMessage(Handler.java:99)
01-30 17:57:15.853: E/AndroidRuntime(1553): at android.os.Looper.loop(Looper.java:130)
01-30 17:57:15.853: E/AndroidRuntime(1553): at android.app.ActivityThread.main(ActivityThread.java:3683)
01-30 17:57:15.853: E/AndroidRuntime(1553): at java.lang.reflect.Method.invokeNative(Native Method)
01-30 17:57:15.853: E/AndroidRuntime(1553): at java.lang.reflect.Method.invoke(Method.java:507)
01-30 17:57:15.853: E/AndroidRuntime(1553): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
01-30 17:57:15.853: E/AndroidRuntime(1553): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
01-30 17:57:15.853: E/AndroidRuntime(1553): at dalvik.system.NativeStart.main(Native Method)
01-30 17:57:15.853: E/AndroidRuntime(1553): Caused by: java.lang.NullPointerException
01-30 17:57:15.853: E/AndroidRuntime(1553): at android.content.ContextWrapper.getResources(ContextWrapper.java:80)
01-30 17:57:15.853: E/AndroidRuntime(1553): at com.Mobile.mytestbuddy.Splash.<init>(Splash.java:18)
01-30 17:57:15.853: E/AndroidRuntime(1553): at java.lang.Class.newInstanceImpl(Native Method)
01-30 17:57:15.853: E/AndroidRuntime(1553): at java.lang.Class.newInstance(Class.java:1409)
01-30 17:57:15.853: E/AndroidRuntime(1553): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
01-30 17:57:15.853: E/AndroidRuntime(1553): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1561)
01-30 17:57:15.853: E/AndroidRuntime(1553): ... 11 more
我已更新我的答案以適合您的編輯。 – keyboardsurfer