Search code examples
javaandroidsharedpreferences

Android Studio shared preferences is always returning default value


So im trying to make a login or register page popping up before my main activity. My backend works but the sharedpreferences wont be accessable even though the right values are stored in the object on runtime.

Debugging img

This is the main snippet where i try to read the value

sharedPreferences = getSharedPreferences("app",MODE_PRIVATE);
        if(sharedPreferences.getString("logged","false").equals("false")){
            Intent intentMain = new Intent(getApplicationContext(), Registration.class);
            startActivity(intentMain);
            finish();
        }

This is my login component:

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

        textViewRegisterNow = findViewById(R.id.registerText);
        textInputEditTextPassword = findViewById(R.id.password);
        textInputEditTextEmail = findViewById(R.id.email);
        textViewError = findViewById(R.id.error);
        progressBar = findViewById(R.id.loading);
        sharedPreferences = getSharedPreferences("app", MODE_PRIVATE);
        if(sharedPreferences.getString("logged","false").equals("true")){
            Intent intentMain = new Intent(getApplicationContext(), MainActivity.class);
            startActivity(intentMain);
            finish();
        }

        buttonSubmit = findViewById(R.id.submit);
        buttonSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                progressBar.setVisibility(View.VISIBLE);
                textViewError.setVisibility(View.GONE);
                email = textInputEditTextEmail.getText().toString();
                password = textInputEditTextPassword.getText().toString();

                RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
                String url ="";

                StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
                                progressBar.setVisibility(View.GONE);
                                try {
                                    JSONObject jsonObject = new JSONObject(response);
                                    String status = jsonObject.getString("status");
                                    String message = jsonObject.getString("message");
                                    if(status.equals("success")){
                                        name = jsonObject.getString("name");
                                        email = jsonObject.getString("email");
                                        apiKey = jsonObject.getString("apiKey");
                                        SharedPreferences.Editor editor = sharedPreferences.edit();
                                        editor.putString("logged,", "true");
                                        editor.putString("name,", name);
                                        editor.putString("email,", email);
                                        editor.putString("apiKey,", apiKey);
                                        editor.apply();
                                        Intent intentMain = new Intent(getApplicationContext(), MainActivity.class);
                                        startActivity(intentMain);
                                        finish();
                                    }else{

                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        progressBar.setVisibility(View.GONE);
                        textViewError.setText(error.getLocalizedMessage());
                        textViewError.setVisibility(View.VISIBLE);
                    }
                }){
                    protected Map<String, String> getParams(){
                        Map<String, String> paramV = new HashMap<>();
                        paramV.put("email", email);
                        paramV.put("password", password);
                        return paramV;
                    }
                };
                queue.add(stringRequest);

            }
        });

I almost looked through every thread in here but nothing works. Does anyone have an idea?


Solution

  • You must get saved value with the exact same key as the one you use when you save it.
    Here you save it using

    editor.putString("logged,", "true");
    

    and the key is logged, that terminates with a comma.

    And here you get it using

    sharedPreferences.getString("logged","false");
    

    the key is logged without comma.
    You have to change it like the following:

    sharedPreferences.getString("logged,","false");
    

    It is best practice to avoid using hardcoded keys to prevent errors like this. It make sense?