I am trying to use sharedpreferences to check if a user is logged in before they start using the application. I save the username in shredpreferences when the user logs in.
Login.java
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.login); Button btnLogin = (Button) findViewById(R.id.buttonlogin); btnLogin.setOnClickListener(new View.OnClickListener() { public void onClick(View adapt) { EditText usernameEditText = (EditText) findViewById(R.id.EditUserName); userName = usernameEditText.getText().toString(); EditText passwordEditText = (EditText) findViewById(R.id.EditPassword); userPassword = passwordEditText.getText().toString(); if (userName.matches("") && userPassword.matches("")) { toast("Please enter Username and Password"); return; } else if (userName.matches("") || userName.equals("")) { toast("Please enter Username"); return; } else if (userPassword.matches("") || userPassword.equals("")) { toast("Please enter Password"); return; } else { SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString("MEM1", userName); editor.commit(); new DownloadFilesTask().execute(); } } }); } private void toast(String text) { Toast.makeText(this, text, Toast.LENGTH_SHORT).show(); } private class DownloadFilesTask extends AsyncTask<Void, Void, Void> { protected void onPreExecute() { } protected void onPostExecute(Void result) { toast("user logged in"); startActivity(new Intent(Login.this, MainActivity.class)); finish(); } @Override protected Void doInBackground(Void... params) { return null; } } }
and I tried to check the username value before starting my mainactivity.
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE); String username =sharedPreferences.getString("MEM1", ""); if(username.equalsIgnoreCase("")||username.length()==0) { toast("username is null"); startActivity(new Intent(MainActivity.this, Login.class)); finish(); }
but the username is always null. Please help. Thanks
source share