在我的Android活动我试图建立一个自定义的Java类WordPressRestApiHandler
像这样:访问字符串资源,并从定制Java类共享偏好
public class LoginActivity extends AppCompatActivity{
...
private final WordPressRestApiHandler wordPressRestApiHandler = new WordPressRestApiHandler(LoginActivity.this, service);
...
那堂课,我想有机会获得字符串资源并分享偏好。这就是为什么我使用LoginActivity.this
作为输入。这是我的自定义类的构造函数:
protected WordPressRestApiHandler(Context initiateContext, OAuth10aService initiateService) {
context = initiateContext;
service = initiateService;
int some = R.string.PREFERENCE_FILE_KEY;
String test = context.getString(some);
SharedPreferences sharedPref = context.getSharedPreferences(test,Context.MODE_PRIVATE);
...
我能够得到一些整数,其值是正确的,但我不能够访问字符串资源中的下一行。 logcat的告诉我:
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.getResourcesInternal(ContextThemeWrapper.java:127)
at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:121)
at android.support.v7.app.AppCompatActivity.getResources(AppCompatActivity.java:549)
at android.content.Context.getString(Context.java:476)
at com.example.my_app.WordPressRestApiHandler.<init>(WordPressRestApiHandler.java:40)
at com.example.my_app.LoginActivity.<init>(LoginActivity.java:35)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1078)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2557)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
在这个工作流程中的变量test
将包含我sharedPreferences文件的唯一标识符。因此它看起来像"com.example.PREFERENCE_FILE"
。
到目前为止,我已经尝试过类似呼吁App.getContext().getString()
自定义活动App
或处理过this
(因此AppCombatActivity
类型的对象),但他们没有为我工作的几种方法。
你能更具体地告诉你如何不能访问字符串资源测试吗?代码是不会编译的,或者你会得到一个异常,还是其他的东西? PREFERENCE_FILE_KEY的strings.xml中有什么? –
@ tim.paetz感谢您的回复!我更新了我的帖子,以回答你的问题。 –