Edittext.getText().toString(); is not working android - android

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.

Related

How to Retrieve Shared Preferences in Same Activity, It comes Empty?

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.

Keep user logged in when app is closed - Android Studio - MySQL

I have create an App where a User list for a group is already placed in a database on MySQL, the Usernames, passwords and variables assigned to them are already uploaded.
Below is the login activity that allows a user to log in and go to their own user area (There is a loginrequest class also that brings the params over).
What I need assistance with is making the application stay logged in until logout for that user even when they have closed the app.
Also will this if possible allow me to send user notifications when the app is closed to individual users?
thank you.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
final EditText etUsername = (EditText) findViewById(R.id.etUsername);
final EditText etPassword = (EditText) findViewById(R.id.etPassword);
final Button bLogin = (Button) findViewById(R.id.bLogin);
final TextView registerLink = (TextView) findViewById(R.id.tvRegisterHere);
//Register Here button
registerLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent registerIntent = new Intent(LoginActivity.this, RegisterActivity.class);
LoginActivity.this.startActivity(registerIntent);
}
});
//Login Button
bLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Taking the username and password and converting it to a string
final String username = etUsername.getText().toString();
final String password = etPassword.getText().toString();
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//Taking the JSONObject from the 000webhost database
JSONObject jsonResponse = new JSONObject(response);
//If the response is successful ie is there a username and password that match
boolean success = jsonResponse.getBoolean("success");
if (success){
//Gather the information below
String name = jsonResponse.getString("name");
int var1 = jsonResponse.getInt("var1");
int var2 = jsonResponse.getInt("var2");
int var3 = jsonResponse.getInt("var3");
int var4 = jsonResponse.getInt("var4");
Intent intent = new Intent(LoginActivity.this, UserAreaActivity.class);
intent.putExtra("name", name);
intent.putExtra("username", username);
intent.putExtra("var1", var1);
intent.putExtra("var2", var2);
intent.putExtra("var3", var3);
intent.putExtra("var4", var4);
intent.putExtra("password", password);
//Start the User Area Activity
LoginActivity.this.startActivity(intent);
}else{
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setMessage("Login Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
LoginRequest loginRequest = new LoginRequest(username, password, responseListener);
RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
queue.add(loginRequest);
}
});
}
You can use SharedPreferences, to resolve your problem.
Use this to verify if the user has "session" started or not
private SharedPreferences sharedpreferences;
sharedpreferences=getApplicationContext().getSharedPreferences("Preferences", 0);
String login = sharedpreferences.getString("LOGIN", null);
if (login != null) {
//put your code if user is logged. For example, go to another activity
}else {
// to go login activity
}
Use this to set the "session" when click on login button
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("LOGIN", newUser.getEmail_user());
editor.commit
Use this on Logout Button
Editor editor = sharedpreferences.edit();
editor.remove("LOGIN");
editor.commit();

Unable to access a string from SharedPreferences in Android

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

Android Studio SharedPreference Saving Login to Database

I want to save the the user's login details when they first login the mobile application into my Device table and have them bypass the login screen every time the application opens.
I think I've got that part going it's just saving the variables I'm not understanding. My question is how and where should I begin saving the user's detail?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// declaring variebles
etUsername = (EditText)findViewById(R.id.etUsername);
etPassword= (EditText)findViewById(R.id.etPassword);
btnLogin = (Button)findViewById(R.id.btnLogin);
etIpAddress = (EditText) findViewById(R.id.etIpAddress);
final String username = etUsername.getText().toString();
final String password = etPassword.getText().toString();
String ipAddress = etIpAddress.getText().toString();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(LoginActivity.this);
if (sharedPreferences.contains("ip")) {
performLogin(username, password, sharedPreferences.getString("ip", ipAddress));
}
// setting up things for login button
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String ipAddress = etIpAddress.getText().toString();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(LoginActivity.this);
String username = etUsername.getText().toString().trim();
String password = etPassword.getText().toString().trim();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("ip", ipAddress);
editor.putString("username", username);
editor.putString("password", password);
editor.commit();
performLogin(username, password, ipAddress);
}
});
}
Here:
performLogin(username, password, sharedPreferences.getString("ip", ipAddress));
user getting login fail because both username and password is passing empty value to performLogin every-time when starting Activity.
In same way as getting ip also get username and password from SharedPreferences like:
if (sharedPreferences.contains("ip")) {
String strUsername=sharedPreferences.getString("username", "");
String strPassword=sharedPreferences.getString("password", "");
String strIpAddress=sharedPreferences.getString("ip", ipAddress);
performLogin(strUsername, strPassword,strIpAddress);
}
You want to get the username and password from the shared preferences as like the ipAddress and then call the perfomLogin method.
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(LoginActivity.this);
if (sharedPreferences.contains("ip")) {
performLogin(sharedPreferences.getString("username", ""), sharedPreferences.getString("password", ""), sharedPreferences.getString("ip", ""));
}

Password stored in SharedPreferences not working in android?

In this order, this is the procedure I'd like to implement.
1) When imageButton is pressed, it checks the value of "pass" stored in SharedPreferences. If this matches the password, the intent starts the next activity.
2) If it is null, or does not match the password, a dialog box pops up prompting username and password entry.
3) If the entered password is correct, it writes the username and password to SharedPreferences.
4) If the entered password is incorrect, it makes a Toast indicating as such.
Thus far, the login is working perfectly. However, I can't seem to get the SharedPreferences function to work. My code is below:
Button aliaLogin = (Button)findViewById(R.id.imageButton);
aliaLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences prefs = getSharedPreferences("testapp", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("username","7");
editor.putString("pass","11");
editor.commit();
String username = prefs.getString("username",null);
String pass = prefs.getString("pass",null);
if (pass != null && !pass.isEmpty() && pass.equals(housePass[5])){
Intent intent = new Intent(getApplicationContext(), DisplayHouse.class);
intent.putExtra("Username", username);
startActivity(intent);
}
else {
final Dialog dialog = new Dialog(HouseMain.this);
dialog.setTitle("Login Required!");
dialog.setContentView(R.layout.login_toast);
dialog.show();
final EditText name = (EditText) dialog.findViewById(R.id.name);
final EditText password = (EditText) dialog.findViewById(R.id.password);
Button submit = (Button) dialog.findViewById(R.id.submitButton);
Button cancel = (Button) dialog.findViewById(R.id.cancelButton);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String username = name.getText().toString();
String pass = password.getText().toString();
SharedPreferences prefs = getSharedPreferences("testapp", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
if (pass.equals(housePass[5])) {
Intent intent = new Intent(getApplicationContext(), DisplayHouse.class);
intent.putExtra("Username", username);
editor.putString("username", username);
editor.putString("pass", pass);
editor.commit();
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "Incorrect! Impostor alert!", Toast.LENGTH_SHORT).show();
}
dialog.cancel();
}
});
cancel.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
dialog.cancel();
}
});
}
}
});
Could someone tell me what I'm doing wrong?
The problem is each time when you click on the button you are resetting the user name and password to default
SharedPreferences prefs = getSharedPreferences("testapp", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("username","7");
editor.putString("pass","11");
editor.commit();
you have to remove it from your code
You have override pass save to Preference file with other pass:
SharedPreferences prefs = getSharedPreferences("testapp", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("username","7");
editor.putString("pass","11");
editor.commit();

Categories

Resources