So I have two screens, a set password screen and an enter password (login) screen. I'd like it to pop up the enter password screen if there is no password (ie, the application's never been used) and upon subsequent launches go to the login screen. If the user enters a password, it compares with the value stored in sharepreferences and continues to the menu if it's correct. But the login screen seems unable to access the password after the set-password screen is used.
How do I make the login screen see the password set by the registration page?
Here's the create password code:
public class CreatePassword extends Activity {
public EditText setPass1, setPass2;
String newPass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_createpassword);
setPass1 = (EditText)findViewById(R.id.editTextSetPassword);
setPass2 = (EditText)findViewById(R.id.editTextRepeatSetPassword);
}
public void btnSubmitNewPassword(View v){
if(setPass1.getText().toString() != "") {
if (setPass1.getText().toString().equals(setPass2.getText().toString())) {
newPass = setPass1.getText().toString();
SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("sharedPref", MODE_PRIVATE);
SharedPreferences.Editor prefEditor = sharedPref.edit();
prefEditor.putString("password", newPass);
prefEditor.apply();
Toast.makeText(getApplicationContext(), newPass, Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "New Password Set", Toast.LENGTH_LONG).show();
startActivity(new Intent(CreatePassword.this, Menu.class));
} else {
Toast.makeText(getApplicationContext(), "Passwords don't match!", Toast.LENGTH_LONG).show();
}
}
else{
Toast.makeText(getApplicationContext(), "Please Enter Desired Password", Toast.LENGTH_LONG).show();
}
}
}//end CreatePassword class
And the EnterPassword (login) screen that refuses to use the password just set:
public class EnterPassword extends Activity {
EditText editTextPasswordAttempt;
SharedPreferences sharedPref;
String passwordAttempt, passwordActual;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_enterpassword);
sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
boolean passwordExists = sharedPref.contains("password");
if(passwordExists == false){
startActivity(new Intent(EnterPassword.this, CreatePassword.class));
}
editTextPasswordAttempt = (EditText)findViewById(R.id.editTextPassword);
}
public void btnSubmitToMenu(View v){
passwordActual = sharedPref.getString("password", );
Toast.makeText(getApplicationContext(), passwordActual, Toast.LENGTH_LONG).show();
passwordAttempt = editTextPasswordAttempt.getText().toString();
if(passwordAttempt.equals(passwordActual)) {
startActivity(new Intent(EnterPassword.this, Menu.class));
}
else{
Toast.makeText(getApplicationContext(), "Invalid Password", Toast.LENGTH_LONG).show();
}
}
}
You are using 2 different SharedPreferences.
In CreatePassword activity you do:
getApplicationContext().getSharedPreferences("sharedPref", MODE_PRIVATE);
But in EnterPassword activity you do:
PreferenceManager.getDefaultSharedPreferences(this);
If you use the same line in both Activities it should work.
You need to use same name of SharedPreferences while access SharedPreferences values.Access SharedPreferences in EnterPassword activity with same way using below line:
getApplicationContext().getSharedPreferences("sharedPref", MODE_PRIVATE);
Related
In my application's login screen, i am fetching a JSON response into the shared preferences in my retrofit2 onResponse method. I get everything as correct from the database and putting as correctly into the shared preferences. I am getting an User_Role from db as string, then based on User_Role, i am directing the user to according activity. I need to reach that User_Role in case R.id.Login: step. In my Logcat i see my response is as i want. I check with Toast after i commit preferences, if i can manage to put preferences correctly. Yes it is writes to screen response.success Organizator. So the only problem i can not retrieve it. Please help.
Because of everything works correctly in my apicall(because i checked every step with Toast.makeText.show(); on screen) i am only putting my LoginActivity.class code below,
LoginActivity.class :
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
Button bSignUp, bLogin;
EditText etPassword, etEmail;
private ProgressDialog progressDialog;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
bSignUp = (Button) findViewById(R.id.bSignUp);
bLogin = (Button) findViewById(R.id.bLogin);
bSignUp.setOnClickListener((View.OnClickListener) this);
bLogin.setOnClickListener((View.OnClickListener) this);
etPassword = (EditText) findViewById(R.id.etPassword);
etEmail = (EditText) findViewById(R.id.etEmail);
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Logging in");
progressDialog.setMessage("Please wait ....");
bLogin.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.bSignUp:
Intent SignUpIntent = new Intent(this, SignUpActivity.class);
startActivity(SignUpIntent);
break;
case R.id.bLogin:
String email = etEmail.getText().toString();
String password = etPassword.getText().toString();
if (!email.isEmpty() && !password.isEmpty()) {
progressDialog.show();
loginProcess(email, password);
//Here i need to obtain SharedPreferences that i filled in onResponse Method. It goes directly wrong email or password statement. Because of can't retrieve settings.getString("User_Role","")
SharedPreferences settings = getSharedPreferences("Pref", MODE_PRIVATE);
String userRole = settings.getString("User_Role","");
Toast.makeText(LoginActivity.this, userRole, Toast.LENGTH_SHORT).show();
if (userRole.equals("Organizator")) {
intent = new Intent(this, OrganizerHomeActivity.class);
startActivity(intent);
} else if(userRole.equals("Speaker") || userRole.equals("Listener")) {
intent = new Intent(this, UserHomeActivity.class);
startActivity(intent);
}
else{
Toast.makeText(LoginActivity.this, "Wrong email or password", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(LoginActivity.this, "Fields are empty", Toast.LENGTH_SHORT).show();
}
break;
default:
break;
}
}
private void loginProcess(String email, String password) {
LoginAPI loginAPI = RetrofitService.getClient().create(LoginAPI.class);
retrofit2.Call<UserList> call = loginAPI.loginUser(email,password);
call.enqueue(new Callback<UserList>(){
#Override
public void onResponse(Call<UserList> call, Response<UserList> response) {
if(response.isSuccessful()){
List<User> userLists = response.body().getUser();
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
//SharedPreferences settings = getSharedPreferences("Pref", MODE_PRIVATE);
SharedPreferences.Editor prefEditor = settings.edit();
prefEditor.putBoolean(Constants.IS_LOGGED_IN, true);
prefEditor.putString("UserName", userLists.get(0).getFirstName());
prefEditor.putString("SSN", userLists.get(0).getsSN());
prefEditor.putString("User_Role", userLists.get(0).getUserRole());
prefEditor.commit();
// In my Logcat i see my respnse is as i want, and i check with below Toast if i can manage to put preferences correctly. Yes it is writes to screen response.success Organizator. So there is no problem.
Toast.makeText(LoginActivity.this, "response.success "+settings.getString("User_Role",""), Toast.LENGTH_SHORT).show();
}
progressDialog.dismiss();
}
#Override
public void onFailure(Call<UserList> call, Throwable t) {
Toast.makeText(LoginActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
});
}
}
Put your SharedPreference logic after onResponse success. it's because it executes before your response get. that's why it empty. so Change code like this
private void checkMethod(){
SharedPreferences settings = getSharedPreferences("Pref", MODE_PRIVATE);
String userRole = settings.getString("User_Role","");
Toast.makeText(LoginActivity.this, userRole, Toast.LENGTH_SHORT).show();
if (userRole.equals("Organizator")) {
intent = new Intent(this, OrganizerHomeActivity.class);
startActivity(intent);
} else if(userRole.equals("Speaker") || userRole.equals("Listener")) {
intent = new Intent(this, UserHomeActivity.class);
startActivity(intent);
}
else{
Toast.makeText(LoginActivity.this, "Wrong email or password", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(LoginActivity.this, "Fields are empty", Toast.LENGTH_SHORT).show();
}
}
And Call this method from onResponse like below
public void onResponse(Call<UserList> call, Response<UserList> response) {
if(response.isSuccessful()){
List<User> userLists = response.body().getUser();
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
//SharedPreferences settings = getSharedPreferences("Pref", MODE_PRIVATE);
SharedPreferences.Editor prefEditor = settings.edit();
prefEditor.putBoolean(Constants.IS_LOGGED_IN, true);
prefEditor.putString("UserName", userLists.get(0).getFirstName());
prefEditor.putString("SSN", userLists.get(0).getsSN());
prefEditor.putString("User_Role", userLists.get(0).getUserRole());
prefEditor.commit();
// In my Logcat i see my respnse is as i want, and i check with below Toast if i can manage to put preferences correctly. Yes it is writes to screen response.success Organizator. So there is no problem.
Toast.makeText(LoginActivity.this, "response.success "+settings.getString("User_Role",""), Toast.LENGTH_SHORT).show();
checkMethod();
}
Try to start intent condition in the response method. No need to store value in shared preferences.
I made a simple login activity in which I used android sqlite database to store login information i.e. username and password. When user click create account button in signup activity, s/he will be transferred to another activity where they can see what is their username and pass. In that screen I need to check if preferences are clear and then the text of the button will be changed based on the decision.
I passed the info between activities using SharedPreference, but I can not delete it or clear it when the user clicks sign out.. Below is the code of both activities..
Here's my SignUp.java
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.signup);
// get Instance of Database Adapter
loginDataBaseAdapter=new LoginDataBaseAdapter(this);
loginDataBaseAdapter=loginDataBaseAdapter.open();
// Get Refferences of Views
editTextUserName=(EditText)findViewById(R.id.editTextUserName);
editTextPassword=(EditText)findViewById(R.id.editTextPassword);
editTextConfirmPassword=(EditText)findViewById(R.id.editTextConfirmPassword);
tv=(TextView)findViewById(R.id.textView);
btnCreateAccount=(Button)findViewById(R.id.buttonCreateAccount);
btnCreateAccount.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String userName=editTextUserName.getText().toString();
String password=editTextPassword.getText().toString();
String confirmPassword=editTextConfirmPassword.getText().toString();
// check if any of the fields are vaccant
if(userName.equals("")||password.equals("")||confirmPassword.equals("")) {
Toast.makeText(getApplicationContext(), "Field Vaccant", Toast.LENGTH_LONG).show();
return;
}
// check if both password matches
if(!password.equals(confirmPassword)) {
Toast.makeText(getApplicationContext(), "Password does not match", Toast.LENGTH_LONG).show();
return;
}
if(password.length()<8) {
Toast.makeText(getApplicationContext(),"Password must be 8 digits longer",Toast.LENGTH_LONG).show();
}
else {
// Save the Data in Database
loginDataBaseAdapter.insertEntry(userName, password);
try {
sharedPreferences= PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(Name,userName);
editor.putString(Pass,password);
editor.commit();
} catch (NullPointerException e) {
e.printStackTrace();
}
intent=new Intent(getApplicationContext(),AfterLogin.class);
startActivity(intent);
Toast.makeText(getApplicationContext(), "Account Successfully Created ", Toast.LENGTH_LONG).show();
}
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
loginDataBaseAdapter.close();
}
And the AfterLogin.Java
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.afterlogin);
username=(TextView)findViewById(R.id.Username);
name=(TextView)findViewById(R.id.Name);
user=(TextView)findViewById(R.id.User);
pass=(TextView)findViewById(R.id.Pass);
sout=(Button)findViewById(R.id.SignOut);
s= sharedPreferences.getString(Name,"");
us=sharedPreferences.getString(Pass,"");
username.setText(s);
name.setText(s);
user.setText(s);
pass.setText(us);
sout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.clear();
editor.commit();
String n=sharedPreferences.getString(Name,"");
if (n == null) {
sout.setText("Signed Out");
}
}
});
}
AfterLogin.java you have checked
n == null
but passed the default value as empty for String n
String n=sharedPreferences.getString(Name,""); //EMPTY
change
if (n==null) {
sout.setText("Signed Out");
}
to
if (n.isEmpty()) {
sout.setText("Signed Out");
}
Can you try by committing the clear and commit in a single line. Like editor.clear().commit() or editor.clear().apply(). This might help you since you are committing or applying changes on editor object after making changes.
The problem could be that you are using String n=sharedPreferences.getString(Name,""); which always returns something. Default value if preference doesn't exists or it's value if it exists.
To check if a preference has been deleted i'd better use String n=sharedPreferences.contains(Name); which returns a boolean that shows if the preference exists or not.
Hope it helps!
When I'm logging in on my app my I want my login page will not show anymore if the user is already logged in before. Because everytime a user terminates the app and opens the app again the login page will show with the loading message. I want to implement it because if the user opens the app without data connection the user will still go to his page.
Well here is my code.
pref = getSharedPreferences("Login.conf", Context.MODE_PRIVATE);
editor = pref.edit();
editor.putBoolean("hasLoggedIn", true);
editor.commit();
boolean hasLoggedIn = pref.getBoolean("hasLoggedIn", false);
if(hasLoggedIn){
String username = pref.getString("username", "");
String password = pref.getString("password", "");
if (!username.equals("") && (!password.equals(""))) {
postData.put("username", username);
postData.put("password", password);
authenticate(postData);
}
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (TextUtils.isEmpty(etUsername.getText().toString())) {
Toast.makeText(LoginActivity.this, "Username is empty", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(etPassword.getText().toString())) {
Toast.makeText(LoginActivity.this, "Password is empty", Toast.LENGTH_SHORT).show();
return;
}
editor = pref.edit();
postData.put("username", etUsername.getText().toString());
postData.put("password", MD5.encrypt(etPassword.getText().toString()));
editor.commit();
authenticate(postData);
}
});
}
authenticate
private void authenticate(final HashMap<String, String> postData){
PostResponseAsyncTask task1 = new PostResponseAsyncTask(LoginActivity.this, postData,
new AsyncResponse() {
#Override
public void processFinish(String s) {
Log.d(TAG, s);
if (s.contains("renter")) {
// Login success, Save to prefs
editor = pref.edit();
editor.clear();
editor.putString("username", postData.get("username"));
editor.putString("password", postData.get("password"));
editor.putString("userlevel", s);
editor.commit();
Toast.makeText(LoginActivity.this, "Renter Login Successful!", Toast.LENGTH_SHORT).show();
Intent in = new Intent(LoginActivity.this, RenterTabs.class);
startActivity(in);
finish();
} else if (s.contains("owner")) {
// Login success, Save to prefs
editor = pref.edit();
editor.clear();
editor.putString("username", postData.get("username"));
editor.putString("password", postData.get("password"));
editor.putString("userlevel", s);
editor.commit();
Toast.makeText(LoginActivity.this, "Owner Login Successful!", Toast.LENGTH_SHORT).show();
Intent in = new Intent(LoginActivity.this, OwnerTabs.class);
startActivity(in);
finish();
} else if (s.contains("driver")) {
editor = pref.edit();
editor.clear();
editor.putString("username", postData.get("username"));
editor.putString("password", postData.get("password"));
editor.putString("userlevel", s);
editor.commit();
Toast.makeText(LoginActivity.this, "Driver Login Successful!", Toast.LENGTH_SHORT).show();
Intent in = new Intent(LoginActivity.this, DriverTabs.class);
startActivity(in);
finish();
}else if(s.contains("-1")){
Toast.makeText(LoginActivity.this, "Wrong username or password...", Toast.LENGTH_SHORT).show();
}
}
});
task1.execute("http://carkila.esy.es/carkila/authenticate.php");
I don't see why should if(hasLoggedIn) line ever be negative. You always put a true value in hasLoggedIn shared preferences and then you have an if statement on that.
So what I've understood so far is, you want to click the login button automatically when some user is already logged in your application before using the username and the password stored in the SharedPreferences. So if I'm assuming the problem correctly, here's how you can implement this.
I'm just rewriting your code. See the comments for better understanding.
pref = getSharedPreferences("Login.conf", Context.MODE_PRIVATE);
boolean hasLoggedIn = pref.getBoolean("hasLoggedIn", false);
// Move the onClickListener outside the if statement
// Because, if the user is not already logged in
// Then you need to have a click action on this button.
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (TextUtils.isEmpty(etUsername.getText().toString())) {
Toast.makeText(LoginActivity.this, "Username is empty", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(etPassword.getText().toString())) {
Toast.makeText(LoginActivity.this, "Password is empty", Toast.LENGTH_SHORT).show();
return;
}
editor = pref.edit();
postData.put("username", etUsername.getText().toString());
postData.put("password", MD5.encrypt(etPassword.getText().toString()));
editor.commit();
authenticate(postData);
}
});
if(hasLoggedIn) {
String username = pref.getString("username", "");
String password = pref.getString("password", "");
// Remove this
// if (!username.equals("") && (!password.equals(""))) {
// postData.put("username", username);
// postData.put("password", password);
// authenticate(postData);
// }
// Simply put this in here
btnLogin.performClick();
}
And save the preference after a successful login in the authenticate function
private void authenticate(...) {
// On a successful login
editor = pref.edit();
editor.putBoolean("hasLoggedIn", true);
editor.commit();
}
My mobile app needs a feature that from the splash screen when the user is still logged in it wont show the login page any more using shared preference. Here are my codes for references.
Splash
public class Splash extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
Thread myThread = new Thread(){
#Override
public void run() {
try {
sleep(2000);
Intent in = new Intent (getApplicationContext(),MainActivity.class);
startActivity(in);
finish();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
myThread.start();
}
}
Loginpage(the one that will be skipped if user doesn't logs out)
public class MainActivity extends AppCompatActivity {
final String TAG = this.getClass().getName();
Button btnLogin;
EditText etUsername, etPassword;
TextView tvRegister;
SharedPreferences pref;
SharedPreferences.Editor editor;
HashMap<String, String> postData = new HashMap<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
etUsername = (EditText) findViewById(R.id.etFirstname);
etPassword = (EditText) findViewById(R.id.etPassword);
btnLogin = (Button) findViewById(R.id.btnLogin);
tvRegister = (TextView) findViewById(R.id.tvRegister);
pref = MainActivity.this.getSharedPreferences("Login.conf", Context.MODE_PRIVATE);
String username = pref.getString("username", "");
String password = pref.getString("password", "");
if (!username.equals("") && (!password.equals(""))) {
postData.put("username", username);
postData.put("password", password);
authenticate(postData);
}
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editor = pref.edit();
editor.clear();
postData.put("username", etUsername.getText().toString());
postData.put("password", MD5.encrypt(etPassword.getText().toString()));
editor.commit();
authenticate(postData);
}
});
tvRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent in = new Intent(MainActivity.this, RegisterActivity.class);
startActivity(in);
}
});
}
private void authenticate(final HashMap<String, String> postData){
PostResponseAsyncTask task1 = new PostResponseAsyncTask(MainActivity.this, postData,
new AsyncResponse() {
#Override
public void processFinish(String s) {
Log.d(TAG, s);
if (s.contains("renter")) {
// Login success, Save to prefs
editor = pref.edit();
editor.clear();
editor.putString("username", postData.get("username"));
editor.putString("password", postData.get("password"));
editor.commit();
Toast.makeText(MainActivity.this, "Renter Login Successful!", Toast.LENGTH_SHORT).show();
Intent in = new Intent(MainActivity.this, RenterTabs.class);
startActivity(in);
finish();
} else if (s.contains("owner")) {
// Login success, Save to prefs
editor = pref.edit();
editor.clear();
editor.putString("username", postData.get("username"));
editor.putString("password", postData.get("password"));
editor.commit();
Toast.makeText(MainActivity.this, "Owner Login Successful!", Toast.LENGTH_SHORT).show();
Intent in = new Intent(MainActivity.this, OwnerTabs.class);
startActivity(in);
finish();
} else if (s.contains("-1")) {
Toast.makeText(MainActivity.this, "Wrong username or password...", Toast.LENGTH_SHORT).show();
}
}
});
task1.execute("http://carkila.esy.es/carkila/authenticate.php");
task1.setEachExceptionsHandler(new EachExceptionsHandler() {
#Override
public void handleIOException(IOException e) {
Toast.makeText(getApplicationContext(), "Cannot Connect to Server", Toast.LENGTH_SHORT).show();
}
#Override
public void handleMalformedURLException(MalformedURLException e) {
Toast.makeText(getApplicationContext(), "URL Error", Toast.LENGTH_SHORT).show();
}
#Override
public void handleProtocolException(ProtocolException e) {
Toast.makeText(getApplicationContext(), "Protocol Error", Toast.LENGTH_SHORT).show();
}
#Override
public void handleUnsupportedEncodingException(UnsupportedEncodingException e) {
Toast.makeText(getApplicationContext(), "Encoding Error", Toast.LENGTH_SHORT).show();
}
});
}
}
The classes that It'll be going are OwnerTabs.java or RenterTabs.java
Thanks guys :)
In the login class where you're saving the username and password to the sharedpreferences, you should also save a boolean value isLoggedIn- true if the login is successful, and false if not.
Then, you can then put the authenticate method in your splash activity too and call it using the saved username and password values (if the boolean is true). You should rather extract the authenticate method to a separate class and call it from login as well as the signup.
If calling the authenticate method is not important if the user is already logged in, you can simply check the isLoggedIn in your splash activity and direct the user to Owner or Renter class.
I'm new to android developing. I started to make a login screen first but getting entered text is not working. I do not know why. I have been using log and toast but its getting here is code of mine. Toast shows empty and tag wont even appear on debug window and yes I have those fields in layout file.
public class MyActivity extends ActionBarActivity {
private static final String TAG = "LoginInfo";
EditText txtusername, txtpassword;
Button button;
String username, password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
txtusername = (EditText) findViewById(R.id.txtUserName);
txtpassword = (EditText) findViewById(R.id.txtPassword);
button = (Button) findViewById(R.id.btnLogin);
username = txtusername.getText().toString();
password = txtpassword.getText().toString();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), username, Toast.LENGTH_SHORT).show();
Log.d(TAG, username + password);
if ((!username.isEmpty()) & (!password.isEmpty())) {
SharedPreferences sharedpreferences = getSharedPreferences("Login_Info", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("USERNAME", username);
editor.putString("PASSWORD", password);
editor.commit();
Log.d(TAG, username + password);
} else {
Toast.makeText(getApplicationContext(), "Entered Login Info is Incorrect", Toast.LENGTH_SHORT).show();
}
}
});
}
You need to move
username = txtusername.getText().toString();
password = txtpassword.getText().toString();
inside onClick() because it's value is empty. when the view is created.
change your code as below, you getText on onCreate that return blank because of no text in this.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
username = txtusername.getText().toString();
password = txtpassword.getText().toString();
Toast.makeText(getApplicationContext(), username, Toast.LENGTH_SHORT).show();
Log.d(TAG, username + password);
if ((!username.isEmpty()) & (!password.isEmpty())) {
SharedPreferences sharedpreferences = getSharedPreferences("Login_Info", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("USERNAME", username);
editor.putString("PASSWORD", password);
editor.commit();
Log.d(TAG, username + password);
} else {
Toast.makeText(getApplicationContext(), "Entered Login Info is Incorrect", Toast.LENGTH_SHORT).show();
}
}
});
public class MyActivity extends ActionBarActivity {
private static final String TAG = "LoginInfo";
EditText txtusername, txtpassword;
Button button;
String username, password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
txtusername = (EditText) findViewById(R.id.txtUserName);
txtpassword = (EditText) findViewById(R.id.txtPassword);
button = (Button) findViewById(R.id.btnLogin);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
username = txtusername.getText().toString();
password = txtpassword.getText().toString();
Toast.makeText(getApplicationContext(), username, Toast.LENGTH_SHORT).show();
Log.d(TAG, username + password);
if ((!username.isEmpty()) & (!password.isEmpty())) {
SharedPreferences sharedpreferences = getSharedPreferences("Login_Info", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("USERNAME", username);
editor.putString("PASSWORD", password);
editor.commit();
Log.d(TAG, username + password);
} else {
Toast.makeText(getApplicationContext(), "Entered Login Info is Incorrect", Toast.LENGTH_SHORT).show();
}
}
});
You should not do this in onCreate() as you call EditText.getText().toString(); when the view is created, so the user still has not entered any data. You should move them to the onClick() method.
username = txtusername.getText().toString();
password = txtpassword.getText().toString();
These lines should not be there in onCreate(). Because initially , the EditTexts are empty.
As user gives the input, then only user would press Login Button.
So put the above mentioned lines within onClick() event of the button.
If the editTexts are found empty in onClick() event of the button , you should show the Toast message like :
"Please provide the credentials to Login!"
put these lines inside onClick()
username = txtusername.getText().toString();
password = txtpassword.getText().toString();
Each time you enter text into edittext you can get values onClick().
Hope this help.