Sharing the SharedPreferences - android

I have 2 activities namely MainActivity and OKActivity. The MainActivity statically checks for a password and lets you go to the OKActivity. I have used SharedPrefrences in the OKActivity for changing the password to a new one.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText password = (EditText) findViewById(R.id.editText_Password);
Button enter = (Button) findViewById(R.id.button);
enter.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
String user_pass;
user_pass = password.getText().toString();
if (user_pass.isEmpty()) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(MainActivity.this);
dialogBuilder.setIcon(R.drawable.ic_launcher);
dialogBuilder.setTitle("Oops!");
dialogBuilder.setMessage("Password Field Cannot Be Empty");
dialogBuilder.setPositiveButton("OK", null);
dialogBuilder.show();
}
else
if (user_pass.equals("123")) {
Toast.makeText(MainActivity.this, "Welcome!", Toast.LENGTH_SHORT).show();
Intent I = new Intent("com.mavenmaverick.password.OKActivity");
startActivity(I);
}
else
if(user_pass != ("123")){
Toast.makeText(MainActivity.this, "Incorrect", Toast.LENGTH_SHORT).show();
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(MainActivity.this);
dialogBuilder.setIcon(R.drawable.ic_launcher);
dialogBuilder.setTitle("Oops!");
dialogBuilder.setMessage("Incorrect Password");
dialogBuilder.setPositiveButton("OK", null);
dialogBuilder.show();
}
}
});
}
public class OKActivity extends Activity {
EditText newPassword;
String newUserPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ok);
newPassword = (EditText) findViewById(R.id.new_password);
newUserPassword = newPassword.getText().toString();
getpasswordSharedPreferences();
Button changePassword = (Button) findViewById(R.id.button_change);
changePassword.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
newUserPassword = newPassword.getText().toString();
getpasswordSharedPreferences();
setSharedPreferences();
}
});
}
private String getpasswordSharedPreferences() {
SharedPreferences userPassword = getSharedPreferences("USER_PASSWORD", MODE_PRIVATE);
String password = userPassword.getString("THE_PASSWORD", "123");
return password;
}
private void setSharedPreferences() {
SharedPreferences userPassword = getSharedPreferences("USER_PASSWORD", MODE_PRIVATE);
SharedPreferences.Editor password_edior = userPassword.edit();
password_edior.putString("THE_PASSWORD", newUserPassword);
password_edior.commit();
Toast.makeText(OKActivity.this, "Password Change Succesful", Toast.LENGTH_SHORT).show();
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(OKActivity.this);
dialogBuilder.setIcon(R.drawable.ic_launcher);
dialogBuilder.setTitle("Done!");
dialogBuilder.setMessage("New Password : "+newUserPassword);
dialogBuilder.setPositiveButton("OK", null);
dialogBuilder.show();
}
How can I access the SharedPrefrences in OKActivity for the password and use it in my MainActivity to allow access thereby making things dynamic over user-interaction cycles.

Just access the SharedPreferences in your OKActivity and in your MainActivity. The trick is to use the same TAG name - in your case it's 'USER_PASSWORD'.
Have a look at this --> SharedPreferences

Create a SharedPrefrences.java //then we can use when ever we need
public class SharedPrefrences {
public static void saveData(String name, String value, Context context) {
try {
SharedPreferences settings = context
.getSharedPreferences(Configuration.getPrefsName(), 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(name, value);
editor.commit();
} catch (NullPointerException ignored) {
}
}
public static String getData(String name, Context context) {
try {
SharedPreferences settings = context
.getSharedPreferences(Configuration.getPrefsName(), 0);
return settings.getString(name, "");
} catch (NullPointerException ignored) {
return "";
}
}
}
//In MainActivity
SharedPrefrences.saveData("Password","123456", getApplicationContext());
//In OKActivity
String passwordfromMainActivty = PreferencesUtils.getData("Password", getApplicationContext());
//To Add Newpassword
SharedPrefrences.saveData("NewPassword","abcd", getApplicationContext());

You get the same way in both activity's. Do get of your SharedPreferences with the same TAG.
private String getpasswordSharedPreferences() {
SharedPreferences userPassword = getSharedPreferences("USER_PASSWORD", MODE_PRIVATE);
String password = userPassword.getString("THE_PASSWORD", "123");
return password;
}
Maybe you can put this method's in other class, and call when you want from all activities:
You can put your set method here too
For example:
public class SharedPrefs {
private static final String SHARED_PREF = "USER_PASSWORD";
private static final String KEY_PASSWORD = "THE_PASSWORD";
public static void getStoredSharedPref(Context context, String key, String value) {
SharedPreferences sharedPref = context.getSharedPreferences(SHARED_PREF, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(propertyKey, value);
editor.commit();
}
}
and then call in your activities
SharedPrefs.getStoredSharedPref(context, SharedPrefsUtils.KEY_PASSWORD,"1234");

Related

Trying to keep user loggedIn in my android app after first login but not working

I am developing an android app, my app have a login activity. What i want to do is once a user is logged in for the first time it will remain logged in even if the app is closed.
I tried a way out but it didn't worked well.
Any help will b appreciated.
Thanks!
1) Login.java
private Snackbar snackbar;
private ProgressDialog pd;
private TextInputLayout mTiEmail;
private TextInputLayout mTiPassword;
private CompositeSubscription mSubscriptions;
private SharedPreferences mSharedPreferences;
private Boolean loggedIn = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mSubscriptions = new CompositeSubscription();
mSubscriptions = new CompositeSubscription();
loginUserName = (EditText) findViewById(R.id.email_edit);
loginPassword = (EditText) findViewById(R.id.pass_edit);
pd = new ProgressDialog(Login.this);
mTiEmail = (TextInputLayout) findViewById(R.id.email1);
mTiPassword = (TextInputLayout) findViewById(R.id.password);
loginButton = (TextView)findViewById(R.id.btn_login);
initSharedPreferences();
loginButton.setOnClickListener(view -> login());
}
#Override
protected void onResume() {
super.onResume();
//In onresume fetching value from sharedpreference
SharedPreferences sharedPreferences = getSharedPreferences(Constants.SHARED_PREF_NAME, Context.MODE_PRIVATE);
//Fetching the boolean value form sharedpreferences
loggedIn = sharedPreferences.getBoolean(Constants.LOGGEDIN_SHARED_PREF, false);
//If we will get true
if (loggedIn) {
//We will start the Profile Activity
Intent intent = new Intent(Login.this, Dashboard.class);
startActivity(intent);
}
}
private void initSharedPreferences() {
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(Login.this);
}
private void login() {
setError();
String email = loginUserName.getText().toString();
String password = loginPassword.getText().toString();
int err = 0;
if (!validateEmail(email)) {
err++;
mTiEmail.setError("Email should be valid !");
}
if (!validateFields(password)) {
err++;
mTiPassword.setError("Password should not be empty !");
}
if (err == 0) {
loginProcess(email,password);
} else {
Toast.makeText(this, "Enter valid details", Toast.LENGTH_SHORT).show();
}
}
private void setError() {
loginUserName.setError(null);
loginPassword.setError(null);
}
private void loginProcess(String email, String password) {
mSubscriptions.add(NetworkUtil.getRetrofit(email,password).login()
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(this::handleResponse,this::handleError));
}
private void handleResponse(Response response) {
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putString(Constants.TOKEN,response.getToken());
editor.putString(Constants.EMAIL,response.getMessage());
editor.apply();
loginUserName.setText(null);
loginPassword.setText(null);
Intent in = new Intent(Login.this,Dashboard.class);
startActivity(in);
Toast.makeText(this, "REGISTERED-->>", Toast.LENGTH_LONG).show();
}
private void handleError(Throwable error) {
if (error instanceof HttpException) {
Gson gson = new GsonBuilder().create();
try {
String errorBody = ((HttpException) error).response().errorBody().string();
Response response = gson.fromJson(errorBody,Response.class);
Toast.makeText(this, response.getMessage(), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
} else {
Toast.makeText(this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
Here in my onResume() method i tried a way out but didn't work, Any Suggestions?
2) Constants.java
public class Constants {
public static final String BASE_URL = "http://192.168.2.145:8080/api/v1/";
public static final String TOKEN = "token";
public static final String EMAIL = "email";
//This would be the name of our shared preferences
public static final String SHARED_PREF_NAME = "myloginapp";
//This would be used to store the email of current logged in user
public static final String EMAIL_SHARED_PREF = "email";
//We will use this to store the boolean in sharedpreference to track user is loggedin or not
public static final String LOGGEDIN_SHARED_PREF = "loggedin";
}
UPDATE
Login.java
public class Login extends AppCompatActivity {
TextView loginButton;
EditText loginUserName, loginPassword;
private Snackbar snackbar;
private ProgressDialog pd;
private TextInputLayout mTiEmail;
private TextInputLayout mTiPassword;
private CompositeSubscription mSubscriptions;
private SharedPreferences mSharedPreferences;
private Boolean loggedIn = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mSubscriptions = new CompositeSubscription();
mSubscriptions = new CompositeSubscription();
loginUserName = (EditText) findViewById(R.id.email_edit);
loginPassword = (EditText) findViewById(R.id.pass_edit);
pd = new ProgressDialog(Login.this);
mTiEmail = (TextInputLayout) findViewById(R.id.email1);
mTiPassword = (TextInputLayout) findViewById(R.id.password);
loginButton = (TextView)findViewById(R.id.btn_login);
initSharedPreferences();
loginButton.setOnClickListener(view -> login());
}
#Override
protected void onResume() {
super.onResume();
//In onresume fetching value from sharedpreference
mSharedPreferences = getSharedPreferences("login", Context.MODE_PRIVATE);
if(mSharedPreferences.getBoolean("LoggedIn", false)){
Intent intent = new Intent(Login.this,Dashboard.class);
startActivity(intent);
} else {
loginButton.setOnClickListener(view -> login());
//Do other stuff
}
}
private void initSharedPreferences() {
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(Login.this);
}
private void login() {
String username = loginUserName.getText().toString();
String password = loginPassword.getText().toString();
loginProcess(username,password);
int err = 0;
if (!validateFields(username)&& !validateFields(password)) {
err++;
mTiEmail.setError("Username should not be empty !");
}
if (err == 0) {
loginProcess(username,password);
} else {
Toast.makeText(this, "Enter valid details", Toast.LENGTH_SHORT).show();
}
}
private void loginProcess(String username,String password){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
RetrofitInterface requestInterface = retrofit.create(RetrofitInterface.class);
User user = new User();
user.setUsername(username);
user.setPassword(password);
ServerRequest request = new ServerRequest();
request.setOperation(Constants.LOGIN_OPERATION);
request.setUser(user);
Call<ServerResponse> response = requestInterface.operation(request);
response.enqueue(new Callback<ServerResponse>() {
#Override
public void onResponse(Call<ServerResponse> call, retrofit2.Response<ServerResponse> response) {
if(response.isSuccessful()) {
ServerResponse serverResponse = response.body();
if(serverResponse.getMessage().equals(Constants.SUCCESS)) {
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putBoolean("LoggedIn",true);
//editor.putString(Constants.EMAIL,serverResponse.getUser().getEmail());
editor.putString(Constants.USERNAME,serverResponse.getUser().getUsername());
editor.putString(Constants.BUSINESSNAME,serverResponse.getUser().getBusinessname());
editor.apply();
Toast.makeText(Login.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
goToProfile();
} else {
Toast.makeText(Login.this, serverResponse.getMessage(), Toast.LENGTH_SHORT).show();
}
} else {
Gson gson = new Gson();
ServerResponse errorResponse = null;
try {
errorResponse = gson.fromJson(response.errorBody().string(), ServerResponse.class);
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(Login.this, errorResponse.getMessage(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<ServerResponse> call, Throwable t) {
Log.d(Constants.TAG,"failed");
Toast.makeText(Login.this,t.getLocalizedMessage() , Toast.LENGTH_SHORT).show();
}
});
}
private void goToProfile(){
Intent intent = new Intent(this,Dashboard.class);
startActivity(intent);
}
}
Put this code in your onCreate()
SharedPreferences pref = getSharedPrefrences("login", Context.MODE_PRIVATE); //Opening 'login' sharedPreference
if(pref.getBoolean("LoggedIn", false)){ //checking if 'LoggedIn' exist in SharedPreference if no exist it returns false. if it exist fetches its value
//Move to Next Screen
} else {
loginButton.setOnClickListener(view -> login());
//Do other stuff
}
Then in your handleResponse().. Add these lines
//Lets suppose if User is logging in for the First time.. Below lines will add 'LoggedIn' to shared preference so user logged in directly next time
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("LoggedIn", true);
editor.apply();
Set LOGGEDIN_SHARED_PREF in your void handleResponse() as below :
editor.putBoolean(Constants.LOGGEDIN_SHARED_PREF,true);
Set your sharedPreferences globally
SharedPreferences sharedPreferences = getSharedPreferences(Constants.SHARED_PREF_NAME, Context.MODE_PRIVATE);
And edit on the same in your handleReponse()
SharedPreferences.Editor editor = sharedPreferences.edit();
I updated your code:
private Snackbar snackbar;
private ProgressDialog pd;
private TextInputLayout mTiEmail;
private TextInputLayout mTiPassword;
private CompositeSubscription mSubscriptions;
private SharedPreferences sharedPreferences;
private Boolean loggedIn = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mSubscriptions = new CompositeSubscription();
mSubscriptions = new CompositeSubscription();
loginUserName = (EditText) findViewById(R.id.email_edit);
loginPassword = (EditText) findViewById(R.id.pass_edit);
pd = new ProgressDialog(Login.this);
mTiEmail = (TextInputLayout) findViewById(R.id.email1);
mTiPassword = (TextInputLayout) findViewById(R.id.password);
loginButton = (TextView)findViewById(R.id.btn_login);
loginButton.setOnClickListener(view -> login());
}
#Override
protected void onResume() {
super.onResume();
//In onresume fetching value from sharedpreference
sharedPreferences = getSharedPreferences(Constants.SHARED_PREF_NAME, Context.MODE_PRIVATE);
//Fetching the boolean value form sharedpreferences
loggedIn = sharedPreferences.getBoolean(Constants.LOGGEDIN_SHARED_PREF, false);
//If we will get true
if (loggedIn) {
//We will start the Profile Activity
Intent intent = new Intent(Login.this, Dashboard.class);
startActivity(intent);
}
}
private void login() {
setError();
String email = loginUserName.getText().toString();
String password = loginPassword.getText().toString();
int err = 0;
if (!validateEmail(email)) {
err++;
mTiEmail.setError("Email should be valid !");
}
if (!validateFields(password)) {
err++;
mTiPassword.setError("Password should not be empty !");
}
if (err == 0) {
loginProcess(email,password);
} else {
Toast.makeText(this, "Enter valid details", Toast.LENGTH_SHORT).show();
}
}
private void setError() {
loginUserName.setError(null);
loginPassword.setError(null);
}
private void loginProcess(String email, String password) {
mSubscriptions.add(NetworkUtil.getRetrofit(email,password).login()
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(this::handleResponse,this::handleError));
}
private void handleResponse(Response response) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(Constants.TOKEN,response.getToken());
editor.putString(Constants.EMAIL,response.getMessage());
editor.putBoolean(Constants.LOGGEDIN_SHARED_PREF,true);
editor.apply();
loginUserName.setText(null);
loginPassword.setText(null);
Intent in = new Intent(Login.this,Dashboard.class);
startActivity(in);
Toast.makeText(this, "REGISTERED-->>", Toast.LENGTH_LONG).show();
}
private void handleError(Throwable error) {
if (error instanceof HttpException) {
Gson gson = new GsonBuilder().create();
try {
String errorBody = ((HttpException) error).response().errorBody().string();
Response response = gson.fromJson(errorBody,Response.class);
Toast.makeText(this, response.getMessage(), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
} else {
Toast.makeText(this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}

How to get user data with SharedPreferences from RegisterActivity

i programmed my register activity to get my user details and store it with SharePreferences
Now , im trying to get those values stored in the data to log in in my app but it seems im missing something, when i put anything in my edittexts in my login layout it logs in without checking the user
RegisterActivity.class
public class RegistrarUsuario extends AppCompatActivity {
private Button mBtnRegistrarUsuario;
private TextView mRegistrarTxt;
private EditText mUsername,mPassword,mSecondPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registrar_usuario);
mRegistrarTxt = (TextView) findViewById(R.id.titulo2);
mUsername = (EditText) findViewById(R.id.nombreUsuario);
mPassword = (EditText) findViewById(R.id.primeraContraseña);
mSecondPassword = (EditText) findViewById(R.id.segundaContraseña);
Typeface fuente = Typeface.createFromAsset(getAssets(),"fonts/MrDafoe-Regular.ttf");
mRegistrarTxt.setTypeface(fuente);
mBtnRegistrarUsuario = (Button) findViewById(R.id.btnRegistrarUsuario);
mBtnRegistrarUsuario.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences preference = getSharedPreferences("Reg",MODE_PRIVATE);
String username = mUsername.getText().toString().trim();
String password = mPassword.getText().toString().trim();
String secondpassword = mSecondPassword.getText().toString().trim();
if(username.length()<=0){
Toast.makeText(RegistrarUsuario.this, "Ingrese un usuario.", Toast.LENGTH_SHORT).show();
}
else if(password.length()<=0){
Toast.makeText(RegistrarUsuario.this, "Ingrese contraseña.", Toast.LENGTH_SHORT).show();
}
else if(secondpassword.length()<=0){
Toast.makeText(RegistrarUsuario.this, "Confirme su contraseña.", Toast.LENGTH_SHORT).show();
}
else if(password.equals(secondpassword)){
SharedPreferences.Editor editor = preference.edit();
editor.putString("Username",username);
editor.putString("Password",password);
editor.putString("SecondPassword",secondpassword);
editor.commit();
finish();
Toast.makeText(RegistrarUsuario.this, "Usuario creado con exito!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(RegistrarUsuario.this,PantallaPrincipal.class);
startActivity(intent);
}
else{
Toast.makeText(RegistrarUsuario.this, "No coinciden las contraseñas.", Toast.LENGTH_SHORT).show();
}
}
});
}
}
** LoginActivity.class**
public class MainActivity extends AppCompatActivity {
private EditText mUsername,mPassword;
private Button mLoginBtn,mBtnRecuperar,mBtnRegistrar;
private TextView mTextView;
private static String usuario ="admin";
private static String contraseña="123";
private final String KEY_USERNAME = "username";
private final String KEY_PASSWORD = "password";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mUsername = (EditText) findViewById(R.id.usuario);
mPassword = (EditText) findViewById(R.id.contraseña);
mLoginBtn = (Button) findViewById(R.id.btnIngresar);
mTextView = (TextView) findViewById(R.id.titulo);
Typeface fuente = Typeface.createFromAsset(getAssets(),"fonts/MrDafoe-Regular.ttf");
mTextView.setTypeface(fuente);
mBtnRecuperar = (Button) findViewById(R.id.btnRecuperar);
mBtnRecuperar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,RecuperarContrasenia.class);
startActivity(intent);
}
});
mBtnRegistrar = (Button) findViewById(R.id.btnRegistrar);
mBtnRegistrar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,RegistrarUsuario.class);
startActivity(intent);
}
});
mLoginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences preference = getSharedPreferences("Reg",MODE_PRIVATE);
String username = mUsername.getText().toString();
String password = mPassword.getText().toString();
String userDetails = preference.getString(username + password + "data","No information on that user.");
SharedPreferences.Editor editor = preference.edit();
editor.putString("display",userDetails);
editor.commit();
if(mUsername.getText().toString().trim().length() == 0 && mPassword.getText().toString().trim().length() == 0 ){
Toast.makeText(MainActivity.this, "Los campos estan vacios", Toast.LENGTH_SHORT).show();
}else
{
if(mUsername.getText().toString().trim().equals(username) && mPassword.getText().toString().trim().equals(password)){
Toast.makeText(MainActivity.this, "Bienvenido", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity.this,PantallaPrincipal.class);
startActivity(intent);
}else{
Toast.makeText(MainActivity.this, "Los campos son incorrectos", Toast.LENGTH_SHORT).show();
}
}
}
});
}
}
i dont know what im missing that it dont verify the user if exists or login with the credentials i make in RegisterActivity.class
thanks
You are never retrieving the username and password from SharedPreferences. And at the end you are checking the information the user puts in the TextEdits against itself so the validation always returns true to any non empty value.
Change this:
SharedPreferences preference = getSharedPreferences("Reg",MODE_PRIVATE);
String username = mUsername.getText().toString();
String password = mPassword.getText().toString();
To this:
SharedPreferences preference = getSharedPreferences("Reg",MODE_PRIVATE);
String username = preference.getString("Username", "");
String password = preference.getString("Password", "");

I want to store Register and Login information in shared preferences in android

I know there are n number of examples in android for shared preferences but I want to Register and store the info in shared preferences and in database using JSON. And then fetch data from JSON and Login with those credentials. If user is already logged in open Main Activity,else go to Splash screen and then open Login Activity. Please go through my detailed code :
RegisterActivity :
public class RegisterActivity extends AppCompatActivity implements ServerRequests.Registereponse {
private EditText password, phone, email;
public static EditText name;
ServerRequests serverRequests;
JSONParser jsonParser;
private Button registerButton;
TextView alreadyMember;
Editor editor;
UserSession session;
SharedPreferences sharedPreferences;
public static final String MyPREFERENCES = "MyPrefs";
public static final String Name1 = "nameKey";
public static final String Phone1 = "phoneKey";
public static final String Email1 = "emailKey";
public static final String Password1 = "passwordKey";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
jsonParser = new JSONParser();
serverRequests = new ServerRequests(getApplicationContext());
serverRequests.setRegistereponse(this);
alreadyMember = (TextView) findViewById(R.id.alreadyMember);
name = (EditText) findViewById(R.id.FName);
phone = (EditText) findViewById(R.id.PhoneNum);
email = (EditText) findViewById(R.id.mail);
password = (EditText) findViewById(R.id.password);
registerButton = (Button) findViewById(R.id.email_sign_in_button);
sharedPreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
registerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CharSequence temp_emailID = email.getText().toString();
if (name.getText().toString().length() == 0) {
name.setError("Please enter your name");
name.requestFocus();
} else if (phone.getText().toString().length() == 0) {
phone.setError("Please enter your phone number");
phone.requestFocus();
} else if (!isValidEmail(temp_emailID)) {
email.setError("Please enter valid email");
email.requestFocus();
} else if (password.getText().toString().length() == 0) {
password.setError("Please enter password");
password.requestFocus();
} else {
try {
String Name = name.getText().toString();
String Email = email.getText().toString();
String Password = password.getText().toString();
String Phone = phone.getText().toString();
JSONObject obj = jsonParser.makeRegisterJson(Name, Email, Password, Long.parseLong(Phone));
Log.e("final Json", obj.toString());
serverRequests.register(obj);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(Name1, Name);
editor.putString(Email1, Email);
editor.putString(Password1, Password);
editor.putString(Phone1, Phone);
editor.commit();
// Toast.makeText(RegisterActivity.this, "Registered Successfully!", Toast.LENGTH_LONG).show();
} catch (Exception e) {
}
}
// startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
}
});
alreadyMember.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
finish();
}
});
}
#Override
public void onRegsiterReposne(JSONObject object) {
Toast.makeText(RegisterActivity.this, "hiii" + object.toString(), Toast.LENGTH_SHORT).show();
}
public final static boolean isValidEmail(CharSequence target) {
if (TextUtils.isEmpty(target)) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
}
LoginActivity :
public class LoginActivity extends AppCompatActivity implements ServerRequests.Loginreponse {
private static final String PREFER_NAME = "Reg";
private Button email_sign_in_button;
private EditText email, password;
private TextView notMember, forgotPass;
UserSession session;
private SharedPreferences sharedPreferences;
ServerRequests serverRequests;
JSONParser jsonParser;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
jsonParser = new JSONParser();
serverRequests = new ServerRequests(getApplicationContext());
serverRequests.setLoginreponse(this);
notMember = (TextView) findViewById(R.id.notMember);
forgotPass = (TextView) findViewById(R.id.forgotPass);
notMember.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
finish();
}
});
forgotPass.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, ForgotPassword.class));
}
});
// get Email, Password input text
email = (EditText) findViewById(R.id.email);
password = (EditText) findViewById(R.id.pass);
// User Login button
email_sign_in_button = (Button) findViewById(R.id.login);
sharedPreferences = getSharedPreferences(PREFER_NAME, MODE_PRIVATE);
// Login button click event
email_sign_in_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
String Email = email.getText().toString();
String Password = password.getText().toString();
JSONObject obj = jsonParser.makeLoginJson(Email, Password);
Log.e("final Json", obj.toString());
serverRequests.login(obj);
} catch (Exception e) {
}
// startActivity(new Intent(LoginActivity.this, MainActivity.class));
// finish();
}
});
}
#Override
public void onLoginReposne(JSONObject object) {
Toast.makeText(LoginActivity.this, "helloo" + object.toString(), Toast.LENGTH_SHORT).show();
if (object.toString().contains("true")) {
Toast.makeText(LoginActivity.this, "Logged in..", Toast.LENGTH_SHORT).show();
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
}
}
}
SplashScreen :
public class SplashScreen extends Activity {
Thread splashTread;
SharedPreferences preferences;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
StartAnimations();
}
public void onAttachedToWindow() {
super.onAttachedToWindow();
Window window = getWindow();
window.setFormat(PixelFormat.RGBA_8888);
}
private void StartAnimations() {
Animation anim = AnimationUtils.loadAnimation(this, R.anim.alpha);
anim.reset();
LinearLayout l = (LinearLayout) findViewById(R.id.lin_lay);
l.clearAnimation();
l.startAnimation(anim);
anim = AnimationUtils.loadAnimation(this, R.anim.translate);
anim.reset();
ImageView iv = (ImageView) findViewById(R.id.splashImage);
iv.clearAnimation();
iv.startAnimation(anim);
/* TextView tv = (TextView) findViewById(R.id.splashText);
tv.clearAnimation();
tv.startAnimation(anim);*/
splashTread = new Thread() {
#Override
public void run() {
try {
int waited = 0;
// Splash screen pause time
while (waited < 3500) {
sleep(100);
waited += 100;
}
startNextScreen();
} catch (InterruptedException e) {
// do nothing
} finally {
SplashScreen.this.finish();
}
}
};
splashTread.start();
}
private void startNextScreen() {
preferences = getSharedPreferences("TrainingApp", MODE_PRIVATE);
String userLoginStatus = preferences.getString("userLoginStatus", "no");
if (userLoginStatus.equals("no")) {
Intent intent = new Intent(SplashScreen.this,
LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
SplashScreen.this.finish();
} else {
Intent intent = new Intent(SplashScreen.this,
MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
SplashScreen.this.finish();
}
}
}
JSONParser class :
public class JSONParser {
//----------For Register
public JSONObject makeRegisterJson(String name, String email, String password, long phone) throws JSONException {
JSONObject object = new JSONObject();
object.put("name", name);
object.put("email", email);
object.put("password", password);
object.put("phone", phone);
// if its in array------
/*JSONObject finalObject=new JSONObject();
finalObject.put("request",object);
return finalObject;*/
return object;
}
//--------For Login--------------------------------------------------------
public JSONObject makeLoginJson(String Name, String password) throws JSONException {
JSONObject object = new JSONObject();
object.put("userName", Name);
object.put("password", password);
/*JSONObject finalObject=new JSONObject();
finalObject.put("request",object);
return finalObject;*/
return object;
}
}
ServerRequests class :
// ---------------- for register------------------------------------------------------------------------------
public void setRegistereponse(Registereponse registereponse) {
this.registereponse = registereponse;
}
private Registereponse registereponse;
public interface Registereponse {
void onRegsiterReposne(JSONObject object);
}
public void register(JSONObject jsonObject) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, Services.REGISTER_URL, jsonObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.e("Json response", "" + response);
boolean b = response.getBoolean("success");
if (registereponse != null) {
registereponse.onRegsiterReposne(response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error ", "" + error);
}
}
);
queue.add(jsonObjectRequest);
}
// --------------For Login ---------------------------------------------------------------------------
public void setLoginreponse(Loginreponse loginreponse) {
this.loginreponse = loginreponse;
}
private Loginreponse loginreponse;
public interface Loginreponse {
void onLoginReposne(JSONObject object);
}
public void login(JSONObject jsonObject) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, Services.LOGIN_URL, jsonObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.e("Json response", "" + response);
boolean b = response.getBoolean("success");
if (loginreponse != null) {
loginreponse.onLoginReposne(response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error ", "" + error);
}
}
);
queue.add(jsonObjectRequest);
}
UserSession class :
public class UserSession {
// Shared Preferences reference
SharedPreferences pref;
// Editor reference for Shared preferences
Editor editor;
// Context
Context _context;
// Shared preferences mode
int PRIVATE_MODE = 0;
// Shared preferences file name
public static final String PREFER_NAME = "Reg";
// All Shared Preferences Keys
public static final String IS_USER_LOGIN = "IsUserLoggedIn";
// User name (make variable public to access from outside)
public static final String KEY_NAME = "Name";
// Email address (make variable public to access from outside)
public static final String KEY_EMAIL = "Email";
// password
public static final String KEY_PASSWORD = "Password";
public static final String KEY_PHONE = "PhoneNumber";
public static final String KEY_QUALIFICATION = "Qualification";
// Constructor
public UserSession(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREFER_NAME, PRIVATE_MODE);
editor = pref.edit();
}
//Create login session
public void createUserLoginSession(String uEmail, String uPassword) {
// Storing login value as TRUE
editor.putBoolean(IS_USER_LOGIN, true);
// Storing name in preferences
editor.putString(KEY_EMAIL, uEmail);
// Storing email in preferences
editor.putString(KEY_PASSWORD, uPassword);
// commit changes
editor.commit();
}
/**
* Check login method will check user login status
* If false it will redirect user to login page
* Else do anything
*/
public boolean checkLogin() {
// Check login status
if (!this.isUserLoggedIn()) {
// user is not logged in redirect him to Login Activity
Intent i = new Intent(_context, LoginActivity.class);
// Closing all the Activities from stack
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
return true;
}
return false;
}
/**
* Get stored session data
*/
public HashMap<String, String> getUserDetails() {
//Use hashmap to store user credentials
HashMap<String, String> user = new HashMap<String, String>();
// user name
user.put(KEY_NAME, pref.getString(KEY_NAME, null));
// user email id
user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));
user.put(KEY_PASSWORD, pref.getString(KEY_PASSWORD, null));
user.put(KEY_PHONE, pref.getString(KEY_PHONE, null));
user.put(KEY_QUALIFICATION, pref.getString(KEY_QUALIFICATION, null));
// return user
return user;
}
/**
* Clear session details
*/
public void logoutUser() {
// Clearing all user data from Shared Preferences
editor.clear();
editor.commit();
// After logout redirect user to MainActivity
Intent i = new Intent(_context, LoginActivity.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
// Check for login
public boolean isUserLoggedIn() {
return pref.getBoolean(IS_USER_LOGIN, false);
}
}
At the time of login successfull put this code:
prefs = getSharedPreferences("logindetail", 0);
SharedPreferences.Editor edit = prefs.edit();
edit.putString("userLoginStatus", "yes");
edit.commit();
At the time of logout use this:
prefs = getSharedPreferences("logindetail", 0);
SharedPreferences.Editor edit = prefs.edit();
edit.clear();
edit.commit();
And at the time of checking if user is login or not use below code:
Loginprefs = getApplicationContext().getSharedPreferences("logindetail", 0);
userLoginStatus = Loginprefs.getString("userLoginStatus", null);
if(userLoginStatus.tostring().equals("yes")){
//the user is login
}else{
//user is logout
}
Hope this helps you

SharedPreferences to save login data

In my application a user starts the application and try to logs in , the application checks whether there is in the Shared Set < User> with the list of credentials for all users , if it does not exist create it from scratch .... Here's my question is how do I check in the shared existence of this Set < User>?
Here, have a look at my code for shared preferences. This code will save your login data.
public class MainActivity extends Activity {
SharedPreferences sharedpreferences;
TextView name;
TextView email;
public static final String mypreference = "mypref";
public static final String Name = "nameKey";
public static final String Email = "emailKey";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (TextView) findViewById(R.id.etName);
email = (TextView) findViewById(R.id.etEmail);
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(Name)) {
name.setText(sharedpreferences.getString(Name, ""));
}
if (sharedpreferences.contains(Email)) {
email.setText(sharedpreferences.getString(Email, ""));
}
}
public void Save(View view) {
String n = name.getText().toString();
String e = email.getText().toString();
Editor editor = sharedpreferences.edit();
editor.putString(Name, n);
editor.putString(Email, e);
editor.commit();
}
public void clear(View view) {
name = (TextView) findViewById(R.id.etName);
email = (TextView) findViewById(R.id.etEmail);
name.setText("");
email.setText("");
}
public void Get(View view) {
name = (TextView) findViewById(R.id.etName);
email = (TextView) findViewById(R.id.etEmail);
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(Name)) {
name.setText(sharedpreferences.getString(Name, ""));
}
if (sharedpreferences.contains(Email)) {
email.setText(sharedpreferences.getString(Email, ""));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Here is simple login code we can store data by putString method of Editor class
SharedPreferences.Editor editor = sp.edit();
editor.putString("User", c.getString(c.getColumnIndex("Name")).toString());
editor.commit();
full code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et1 = (EditText) findViewById(R.id.editText);
et2 = (EditText) findViewById(R.id.editText2);
btn = (Button) findViewById(R.id.button);
btn3 = (Button) findViewById(R.id.button3);
btn3 = (Button) findViewById(R.id.button3);
ct = (Button) findViewById(R.id.ct);
final SQLiteDatabase db = openOrCreateDatabase("DemoDb",MODE_ENABLE_WRITE_AHEAD_LOGGING,null);
ct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
db.execSQL("create table login(LoginId varchar(10) primary key,Password varchar(10),Name varchar(10));");
}
});
sp = getSharedPreferences("myLogin", MODE_PRIVATE);
if(!sp.getBoolean("LogInMode",false)) {
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if( et1.getText().toString().length()==0 || et2.getText().toString().length()==0){
Toast.makeText(getBaseContext(), "User Not Found", Toast.LENGTH_SHORT).show();
}else {
String data = "content://com.example.maity.dbdemo.123/DemoDb";
Uri uri = Uri.parse(data);
ContentResolver resolver = getContentResolver();
String[] ar = {"", ""};
ar[0] = et1.getText().toString().trim();
ar[1] = et2.getText().toString().trim();
final Cursor c = resolver.query(uri, null, null, ar, null);
if (c.moveToNext()) {
if ((et1.getText().toString().trim().equals(c.getString(c.getColumnIndex("LoginId")).toString())) &&
(et2.getText().toString().trim().equals(c.getString(c.getColumnIndex("Password")).toString()))) {
SharedPreferences.Editor editor = sp.edit();
editor.putBoolean("LogInMode", true);
editor.putString("User", c.getString(c.getColumnIndex("Name")).toString());
editor.commit();
Intent intent = new Intent(MainActivity.this, WelcomePage.class);
startActivity(intent);
finish();
}
}else {
Toast.makeText(getBaseContext(), "User Not Found", Toast.LENGTH_SHORT).show();
}
}
}
});
}
else{
Intent intent = new Intent(MainActivity.this, WelcomePage.class);
startActivity(intent);
finish();
}
}
If your login api response is like below
{
"status": true,
"message": "Login Success",
"data": {
"user_id": "1",
"first_name": "Ketan",
"last_name": "Ramani",
"username": "ketanramani"
}
}
Then you can save all login response by dynamically using below code
SharedPreferences preferences = getApplicationContext().getSharedPreferences("LoginPref", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(dataObject.toString());
Iterator<String> iterator = jsonObject.keys();
while (iterator.hasNext()) {
String key = iterator.next();
editor.putString(key, jsonObject.optString(key)).apply();
}
} catch (JSONException e) {
e.printStackTrace();
}
Your data will save in sharedpreferences like below
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string name="user_id">1</string>
<string name="first_name">Ketan</string>
<string name="last_name">Ramani</string>
<string name="username">ketanramani</string>
</map>

Android SharedPreferences not loading and saving properly

I've been getting null returns from getting strings from my saved preferences. I'm not sure how savedpreferences worked but my understanding was that when call a sharedpreferences, it creates the keypair file on the phone so you can come back to it later.
My program is essentially a string creation application. When you press a button, it creates a string to send as an sms. My settings activity page has four edittexts that save whatever is inside them with a buttonclick and returns to the main activity. The final button creates a String by getting the value from the keyvalue pair and constructs the message. However, I've always gotten null for each of the values.
Heres the code for the settings page and then the main page. Please ask if I could add more, I didn't add ALL of the code, just the sharedpreferences portions.
public SharedPreferences sp;
public Editor e;
public void savethethings(){ //run this when enter is pressed/savew
EditText smsintro_hint = (EditText) findViewById(R.id.settings_smsintro_hint);
EditText smsbody_hint = (EditText) findViewById(R.id.settings_smsbody_hint);
EditText checkboxbody_hint = (EditText) findViewById(R.id.settings_checkboxbody_hint);
EditText checkboxbody_description_hint = (EditText) findViewById(R.id.settings_checkboxbody_description_hint);
String introstring = smsintro_hint.getText().toString();
String bodystring = smsbody_hint.getText().toString();
String checkboxbodystring = checkboxbody_hint.getText().toString();
String checkboxdescriptionstring = checkboxbody_description_hint.getText().toString();
e.putString("intro", introstring);
e.commit(); // you forgot to commit
if(!bodystring.isEmpty())
{
e.putString("body", bodystring);
e.commit();
}
if(!checkboxbodystring.isEmpty())
{
e.putString("checkbody", checkboxbodystring);
e.commit();
}
if(!checkboxdescriptionstring.isEmpty())
{
e.putString("checkboxdescr", checkboxdescriptionstring);
e.commit();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.settingmenu);
//SP
sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); // forget about
// named preferences - get the default ones and finish with it
e = sp.edit();
Button tt = (Button)findViewById(R.id.savebutton);
tt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
public void save(View view)
{
//THINGS HAPPEN HERE WITH SHARED PREFERENCES :(
savethethings();
this.finish();
return;
}
public String finishedtext(String userstring)
{
smsintroduction = (sp.getString("intro", ""));
smsbody = (sp.getString("body", ""));
checkboxtext = (sp.getString("checkbody", ""));
checkboxmessage = (sp.getString("checkboxdescr", ""));
if(smsintroduction.isEmpty())
{
if(smsbody.isEmpty())
{
if(checkboxtext.isEmpty())
{
if(checkboxmessage.isEmpty()) //topkek for most AND statements Ive ever put in in if/then form
{
//Essentially the DEFAULT if they're ALL null
smsbody = "Hi "+ userstring +"! This is coming from jake's phone and it wants to send a text so we can talk or whatever. ";
}
}
}
}
Toast.makeText( this, "Creating text, then press send!", Toast.LENGTH_LONG).show();
String thetext = "";
thetext = smsintroduction + " " + smsbody + " " + checkboxtext;
return thetext;
}
public void savethethings(){ //run this when enter is pressed/savew
EditText smsintro_hint = (EditText) findViewById(R.id.settings_smsintro_hint);
EditText smsbody_hint = (EditText) findViewById(R.id.settings_smsbody_hint);
EditText checkboxbody_hint = (EditText) findViewById(R.id.settings_checkboxbody_hint);
EditText checkboxbody_description_hint = (EditText) findViewById(R.id.settings_checkboxbody_description_hint);
String introstring = smsintro_hint.getText().toString();
String bodystring = smsbody_hint.getText().toString();
String checkboxbodystring = checkboxbody_hint.getText().toString();
String checkboxdescriptionstring = checkboxbody_description_hint.getText().toString();
// if(!introstring.isEmpty()) //if the fields are NOT empty, they should get saved.
// {
e.putString("intro", introstring);
e.commit(); // you forgot to commit
if(!bodystring.isEmpty())
{
e.putString("body", bodystring);
e.commit();
}
if(!checkboxbodystring.isEmpty())
{
e.putString("checkbody", checkboxbodystring);
e.commit();
}
if(!checkboxdescriptionstring.isEmpty())
{
e.putString("checkboxdescr", checkboxdescriptionstring);
e.commit();
}
}
Create java class named SessionManger and put all your methods for setting and getting SharedPreferences values. When you want to save value use the object of this class and set and get the values.
Sample code given below.
public class SessionManager {
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;
int PRIVATE_MODE = 0;
public SessionManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences("name_that_you_use", PRIVATE_MODE);
editor = pref.edit();
editor.apply();
}
public void setIntroMessage(String data) {
editor.putString("intro", data);
editor.commit();
}
public String getIntroMessage() {
return pref.getString("intro", null);
}
}

Categories

Resources