Java 未保存SharedReferences

Java 未保存SharedReferences,java,android,android-studio,session,android-studio-2.1,Java,Android,Android Studio,Session,Android Studio 2.1,我已经尝试了其他答案中关于共享偏好的所有可能的解决方案,但仍然无法解决,因此提出了这个问题 我一直在使用这些文件 Config.java public class Config { //URL to our login.php file public static final String LOGIN_URL = "http://192.168.211.1/Remedcu/login.php"; public static final String KEY_NAME =

我已经尝试了其他答案中关于共享偏好的所有可能的解决方案,但仍然无法解决,因此提出了这个问题

我一直在使用这些文件

Config.java

public class Config {
    //URL to our login.php file
    public static final String LOGIN_URL = "http://192.168.211.1/Remedcu/login.php";

    public static final String KEY_NAME = "Name";
    public static final String KEY_EMAIL = "Email";
    public static final String KEY_PASSWORD = "Password";

    //If server response is equal to this that means login is successful
    public static final String LOGIN_SUCCESS = "success";

    //Keys for Sharedpreferences
    //This would be the name of our shared preferences
    public static final String SHARED_PREF_NAME = "iamhere";

    //This would be used to store the email of current logged in user
    public static String EMAIL_SHARED_PREF = null;

    //We will use this to store the boolean in sharedpreference to track user is loggedin or not
    public static String LOGGEDIN_SHARED_PREF = "loggedin";
}
和Login.java

public class Login extends AppCompatActivity {
private static final String TAG = "LoginActivity";
private Vibrator vib;
Animation animShake;
private EditText signupInputName, signupInputPassword;
private TextInputLayout signupInputLayoutName,
        signupInputLayoutPassword;
private Button btnSignUp;
ProgressDialog progress;
private static final String LOGIN_URL = "http://192.168.211.1/Remedcu/login.php";

public static final String KEY_NAME = "Username";
public static final String KEY_PASSWORD = "Password";
TextView textView;
private boolean loggedIn = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    signupInputLayoutName = (TextInputLayout) findViewById(R.id.signup_input_layout_name);
    signupInputLayoutPassword = (TextInputLayout) findViewById(R.id.signup_input_layout_password);
    textView = (TextView) findViewById(R.id.textView2);
    textView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(Login.this, Registration.class);
            startActivity(intent);

        }
    });

    signupInputName = (EditText) findViewById(R.id.signup_input_name);

    signupInputPassword = (EditText) findViewById(R.id.signup_input_password);

    btnSignUp = (Button) findViewById(R.id.btn_signup);

    animShake = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.shakei);
    vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

    btnSignUp.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            submitForm();
            //Intent intent=new Intent(Intent.ACTION_VIEW);
         }
    });
}

private void submitForm() {
    final   String      Name = signupInputName.getText().toString().trim();
    final   String    Password=signupInputPassword.getText().toString().trim();

    StringRequest stringRequest = new StringRequest(Request.Method.POST,LOGIN_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    if(response.equalsIgnoreCase("Invalid credentials")) {
                    Toast.makeText(Login.this, response, Toast.LENGTH_SHORT).show();
                    }
                    //String LOGIN_SUCCESS = "success";
                    if(response.equalsIgnoreCase("success")){
                      final String Use ="Welcome "+Name;
                      Toast.makeText(getApplicationContext(),Use,Toast.LENGTH_SHORT).show();

                        //Creating a shared preference
                        SharedPreferences sharedPreferences = Login.this.getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);

                        //Creating editor to store values to shared preferences
                        SharedPreferences.Editor editor = sharedPreferences.edit();

                        //Adding values to editor
                        editor.putBoolean(Config.LOGGEDIN_SHARED_PREF, true);
                        editor.putString(Config.EMAIL_SHARED_PREF, Name);
                        //Saving values to editor
                        editor.apply();

                        Toast.makeText(getApplicationContext(), "The data is saved as "+Config.EMAIL_SHARED_PREF,Toast.LENGTH_SHORT).show();


                        Intent intent = new Intent(Login.this, MapsActivity.class);
                        startActivity(intent);
                    }//else{
                        //If the server response is not success
                        //Displaying an error message on toast
                    //    Toast.makeText(Login.this, "Invalid credentials", Toast.LENGTH_LONG).show();
                    //}
                    //  Intent intent = new Intent(Registration.this, MainActivity.class);
                    // startActivity(intent);
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(Login.this,error.toString(),Toast.LENGTH_LONG).show();
                }
            }){
        @Override
        protected Map<String,String> getParams(){
            Map<String,String> params = new HashMap<String, String>();
            params.put(KEY_NAME,Name);
            params.put(KEY_PASSWORD,Password);
            return params;
        }

    };

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);


    if (!checkName()) {
        signupInputName.setAnimation(animShake);
        signupInputName.startAnimation(animShake);
        vib.vibrate(120);
        return;
    }
    if (!checkPassword()) {
        signupInputPassword.setAnimation(animShake);
        signupInputPassword.startAnimation(animShake);
        vib.vibrate(120);
        return;
    }


    signupInputLayoutName.setErrorEnabled(false);
    signupInputLayoutPassword.setErrorEnabled(false);

    //   Toast.makeText(getApplicationContext(),
    //    "You are logged in !!", Toast.LENGTH_SHORT).show();
}

private boolean checkName() {
    if (signupInputName.getText().toString().trim().isEmpty()) {

        signupInputLayoutName.setErrorEnabled(true);
        signupInputLayoutName.setError(getString(R.string.err_msg_name));
        signupInputName.setError(getString(R.string.err_msg_required));
        return false;
    }
    signupInputLayoutName.setErrorEnabled(false);
    return true;
}


private boolean checkPassword() {
    if (signupInputPassword.getText().toString().trim().isEmpty()) {

        signupInputLayoutPassword.setError(getString(R.string.err_msg_password));
        requestFocus(signupInputPassword);
        return false;
    }
    signupInputLayoutPassword.setErrorEnabled(false);
    return true;
}

private static boolean isValidEmail(String email) {
    return !TextUtils.isEmpty(email) &&
            android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}

private void requestFocus(View view) {
    if (view.requestFocus()) {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    }
}

@Override
protected void onResume() {
    super.onResume();
    //In onresume fetching value from sharedpreference
    SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);

    //Fetching the boolean value form sharedpreferences
    loggedIn = sharedPreferences.getBoolean(Config.LOGGEDIN_SHARED_PREF, false);

    //If we will get true
    if (loggedIn) {
        //We will start the Profile Activity
        Intent intent = new Intent(Login.this, MapsActivity.class);
        startActivity(intent);
    }
}}
但每当我运行程序时,在登录后,toast总是“数据保存为null”


有什么办法吗?

如果您想查看在键
Config.EMAIL\u SHARED\u PREF
下保存的内容,请运行以下代码:

 Toast.makeText(getApplicationContext(), "The data is saved as "+sharedPreferences.getString(Config.EMAIL_SHARED_PREF, ""),Toast.LENGTH_SHORT).show();

但是,请记住,您没有为
Config.EMAIL\u SHARED\u PREF
分配null以外的任何内容,因此您只需将其存储在
null
下,您需要从SharedReferences获取电子邮件,即键
EMAIL\u SHARED\u PREF
的值:

String email = sharedPreferences.getString(Config.EMAIL_SHARED_PREF, "NOT FOUND");
“NOT FOUND”(未找到)是如果未使用SharedReferences中的值初始化email_SHARED_PREF,则将设置为email的值。接下来,您可以在您的toast maker中拨打
电子邮件

    Toast.makeText(getApplicationContext(), "The data is saved as "+ email,Toast.LENGTH_SHORT).show();

这是因为该变量的值是
null
您需要检索存储在该键下的值。之前我将该值命名为“name”,那么Toast就是“保存为name的数据”,这正是我的观点。您打印的是该变量的值,而不是存储在
SharedReferences
中的实际值。如何访问存储的值?对不起,我是一个noob。任何张贴的答案都可以。不过,我强烈建议您下次阅读文档。当我使用上面的链接时,错误是“SharedReferences中的getString(String,String)不能应用于(String),它应该是
SharedReferences.getString(Config.EMAIL\u SHARED\u PREF,“defValue”)
,如果该键下没有存储任何内容,则第二个参数是默认值。
    Toast.makeText(getApplicationContext(), "The data is saved as "+ email,Toast.LENGTH_SHORT).show();