Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/396.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/222.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/joomla/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 来自不同类的共享首选项不起作用_Java_Android - Fatal编程技术网

Java 来自不同类的共享首选项不起作用

Java 来自不同类的共享首选项不起作用,java,android,Java,Android,虽然我在活动外部的单独类中定义了SharedReference,但它会引发异常。但是,我在活动中声明with时使用的相同方法工作得很好 我知道在我们调用getshared首选项之前应该首先启动活动 代码如下: sharedpreferencesutil.java android.content.SharedPreferences prefs = getSharedPreferences(Constants.APP_NAME, MOD

虽然我在活动外部的单独类中定义了SharedReference,但它会引发异常。但是,我在活动中声明with时使用的相同方法工作得很好

我知道在我们调用getshared首选项之前应该首先启动活动

代码如下:

sharedpreferencesutil.java
android.content.SharedPreferences prefs =
            getSharedPreferences(Constants.APP_NAME,
                    MODE_PRIVATE);
    android.content.SharedPreferences.Editor editor = prefs.edit();
public boolean savePassword(String password) {
        editor.putString(Constants.PASSWORD, password);
        return editor.commit();
    }

    public String getPassword() {
        return prefs.getString(Constants.PASSWORD, null);
    }



Activity class:

mUserName = (EditText) findViewById(R.id.EditTextUsername);
if(sharedPreferences.getUserNameFromPrefs().isEmpty()) {
        mUserName.setText(sharedPreferences.getUserNameFromPrefs(), TextView.BufferType.EDITABLE);
}
我也尝试过使用上下文,但仍然在活动类的getSharedPref方法上遇到运行时nullpointer异常


请帮助

这两个链接清楚地回答了您的问题

SharedReferenced仅适用于有效的活动上下文。您可以简单地将上下文作为参数传递给类,这将解决您的问题