Search code examples
javaandroidandroid-studiosessionandroid-studio-2.1

Sharedpreferences not saved


I have tried all the possible solution given in other answers about shared preference, and still was not able to solve, thus made this question.

I have been using these files

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";
}

and 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);
    }
}}

In the Login.java after I commit the changes to the editor, I just wanted to check the values if they are saved or not.

Thus the below code is there:

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

But whenever I run the program, after logging in, the toast is always "The data is saved as null"

Is there any way around it?


Solution

  • You need to get the email, that is, the value of the key EMAIL_SHARED_PREF from sharedPreferences:

    String email = sharedPreferences.getString(Config.EMAIL_SHARED_PREF, "NOT FOUND");
    

    'NOT FOUND' is the value that will be set to email if EMAIL_SHARED_PREF is not initialized with a value in SharedPreferences. Next, you can just call email in your toast maker.

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