Authentication Android - android

I want to create a static test in my authentication but when I click on button "Valider" nothing happen, instead when I remove the "if" condition and I click on "valider" button the next activity start. I think there is a problem when I put a condition for testing but I don't know what's it. Can you help ? thanks
public class TabAdmin extends Activity implements View.OnClickListener{
private EditText username;
private EditText password;
public String user_name;
public String pass_word;
private Button valider;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.authen);
username = (EditText) findViewById(R.id.login);
password = (EditText) findViewById(R.id.pwd);
valider = (Button) findViewById(R.id.valider);
valider.setOnClickListener((OnClickListener) this);
}
public void onClick(View v) {
if (v == valider) {
user_name = username.getText().toString();
pass_word = password.getText().toString();
if((user_name=="admin")&&(pass_word=="admin"))
{
Intent goToNextActivity = new Intent(getApplicationContext(), MenuAdmin.class);
startActivity(goToNextActivity);
}
}
}

try using if (v.equals(valider)) instead of if (v == valider)

For one thing the way you're comparing strings isn't right for Java. Try
if ("admin".equals(user_name) && "admin".equals(pass_word)) {
This isn't a great way of doing passwords though as anyone can read the strings out of the APK.

instead of
if((user_name=="admin")&&(pass_word=="admin"))
use
if((user_name.equals("admin"))&&(pass_word.equals("admin")))
I hope it can help u

Related

The email address is badly formatted Firebase

hi i am working on a android project where i am using firebase as back-end and i am building a signup and login form . When ever i sign up the code is working well and . When i try to retrieve it using "signInWithEmailAndPassword i am getting the fallowing error. The email address is badly formatted Firebase`
login Activity
public class LoginActivity extends AppCompatActivity {
private EditText mLoginEmailField;
private EditText mloginPassField;
private Button mLoginbtn;
private Button mNewAccountbtn;
private DatabaseReference mDatabaseRefrence;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mAuth = FirebaseAuth.getInstance();
mLoginEmailField = (EditText) findViewById(R.id.loginEmailField);
mloginPassField = (EditText) findViewById(R.id.loginPasswordField);
mLoginbtn = (Button) findViewById(R.id.loginBtn);
mNewAccountbtn = (Button) findViewById(R.id.newAccountbtn);
mDatabaseRefrence = FirebaseDatabase.getInstance().getReference().child("Users");
mNewAccountbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent rigisterIntent = new Intent(LoginActivity.this,RigisterActivity.class);
rigisterIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(rigisterIntent);
}
});
mLoginbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CheckLogin();
}
});
}
private void CheckLogin() {
String email = mloginPassField.getText().toString().trim();
String pass = mloginPassField.getText().toString().trim();
if(!TextUtils.isEmpty(email) && !TextUtils.isEmpty(pass)){
mAuth.signInWithEmailAndPassword(email,pass).addOnCompleteListener(this,new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
CheackUserExsists();
}else{
System.out.println("Sign-in Failed: " + task.getException().getMessage());
Toast.makeText(LoginActivity.this,"Erorr Login",Toast.LENGTH_LONG).show();
}
}
});
}
}
private void CheackUserExsists() {
final String user_id = mAuth.getCurrentUser().getUid();
mDatabaseRefrence.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChild(user_id)){
Intent MainIntent = new Intent(LoginActivity.this,MainActivity.class);
MainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(MainIntent);
}else
{
Toast.makeText(LoginActivity.this,"You need to setup your Account.. ",Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
Rigister Actvity
public class RigisterActivity extends AppCompatActivity {
private EditText mNameField;
private EditText mPassField;
private EditText mEmailField;
private Button mRigisterbtn;
private ProgressDialog mProgres;
private DatabaseReference mDatabase;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rigister);
mDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
mAuth = FirebaseAuth.getInstance();
mProgres = new ProgressDialog(this);
mNameField = (EditText) findViewById(R.id.nameField);
mPassField = (EditText) findViewById(R.id.passFiled);
mEmailField = (EditText) findViewById(R.id.emailField);
mRigisterbtn = (Button) findViewById(R.id.rigisterbtn);
mRigisterbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StartRigister();
}
});
}
private void StartRigister() {
final String name = mNameField.getText().toString().trim();
String pass = mPassField.getText().toString().trim();
String email = mEmailField.getText().toString().trim();
if(!TextUtils.isEmpty(name) && !TextUtils.isEmpty(pass) && !TextUtils.isEmpty(email)){
mProgres.setMessage("Signing Up... ");
mProgres.show();
mAuth.createUserWithEmailAndPassword(email,pass).addOnCompleteListener(this,new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
String user_id = mAuth.getCurrentUser().getUid();
DatabaseReference CurentUser_db = mDatabase.child(user_id);
CurentUser_db.child("name").setValue(name);
CurentUser_db.child("image").setValue("defalut");
mProgres.dismiss();
Intent mainIntent = new Intent(RigisterActivity.this, MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(mainIntent);
}
}
});
}
}
}
I have made sure that i have setup email and password active in the auth section of firebase.
still firebase giving me the following error.
Your code to set email is incorrect. You are setting email to the value of the EditText for password.
In method CheckLogin(), change:
String email = mloginPassField.getText().toString().trim();
to:
String email = mLoginEmailField .getText().toString().trim();
Simply use Edittext named as Email and Password you need not do anything.
the error comes up only if you use plaintext for both...
I faced this problem recently, possible solutions are :
Check the inputType of your EditText Field.
ADD this attribute to your EditText
android:inputType="textEmailAddress"
In Activity class, it should look like if u are using TextInputLayout instead of editText
mDisplayName=(TextInputLayout) findViewById(R.id.reg_name);
mDisplayEmail=(TextInputLayout)findViewById(R.id.reg_email);
mDisplayPassword=(TextInputLayout)findViewById(R.id.reg_password);
String name = mDisplayName.getEditText().getText().toString();
String email = mDisplayEmail.getEditText().getText().toString();
String password = mDisplayPassword.getEditText().getText().toString();`
Remove whitespaces from email text it worked for me. by using trim() method you can remove spaces.
The error popped for me due to my silly action of using "tab" to go to the next text field. Don't use "tab" for it, instead use your mouse to move to the next text field. Worked for me.
What helped me resolve this issue is to put the android:id into the correct place.
If you are using Material design, there are two parts of your text input, the layout and the actual functional part.
If you put the ID into the layout, you'll only be able to access editText property in the activity class, but if you put it in the functional part, you'll be able to access .text or getText() as someone above has stated.
Change
String pass = mloginPassField.getText().toString().trim();
mAuth.signInWithEmailAndPassword(email,pass)
to
String password = mloginPassField.getText().toString().trim();
mAuth.signInWithEmailAndPassword(email,password)
Your code to set email is incorrect.
Perhaps a space was used as the last letter.
final User? user = (await _auth.signInWithEmailAndPassword(
email: _emailController.text.toString().trim(),
password: _passwordController.text,
)).user;[![enter image description here][1]][1]

String variables becomes null outside setOnClickListener() function

I have a simple android app in which I want to get the user input (String). So I have an "EditText" box and an "Enter" button. When the user types something and hits Enter, I am trying to display that text and it works as long as I do all that inside the 'setOnClickListener()' function. The string variables becomes null outside the function. Here is my code:
public class MainActivity extends AppCompatActivity {
Button hitButton;
EditText userInput;
String myVariable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
hitButton = (Button)findViewById(R.id.button);
hitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
userInput = (EditText)findViewById(R.id.userInput);
myVariable= userInput.getText().toString();
}
});
TextView textView = (TextView)findViewById(R.id.textView);
textView.setText(myVariable); // THIS IS THE PROBLEM
// IT DISPLAYS NULL WHICH MEANS THAT String myVariable = null
}
}
If I put TextView.setText(myVariable) inside the setOnClickListener function then it works perfectly but outside the function, myVariable becomes null. And I need to user that variable outside the function.
Thanks in advance :)
If you want it outside the onClick method, Use SharedPreferences for this like
public class MainActivity extends AppCompatActivity {
Button hitButton;
EditText userInput;
String myVariable;
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String KEY = "Key";
SharedPreferences sharedpreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
hitButton = (Button)findViewById(R.id.button);
sharedpreferences = getActivity().getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
hitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
userInput = (EditText)findViewById(R.id.userInput);
myVariable= userInput.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(KEY, myVariable);
editor.commit();
}
});
TextView textView = (TextView)findViewById(R.id.textView);
textView.setText(sharedpreferences.getString(KEY, null)); // THIS IS THE PROBLEM
// IT DISPLAYS NULL WHICH MEANS THAT String myVariable = null
}
}
Hope it will help you
The method onCreate is called once when your Activity launches. So this is where you want to initialise your TextView like you do:
TextView textView = (TextView)findViewById(R.id.textView);
But in order to set the value of the variable myVariable when the user clicks the button and set the text of your TextView, you have to call the setText method of your TextView inside the onClick method.
public void onClick(View view) {
userInput = (EditText)findViewById(R.id.userInput);
myVariable= userInput.getText().toString();
textView.setText(myVariable);
}
On user's click the variable myVariable is set and it is available outside the function as well, because you have declare it on top.
Hope that helps!
onClick is the method which will trigger only when you click button.
So if your textView needs to get value updated when clicking button, It should be inside onClick than outside like this.
public void onClick(View view) {
userInput = (EditText)findViewById(R.id.userInput);
myVariable= userInput.getText().toString();
textView.setText(myVariable);
}
To complete Stallion's answer,
textView.setText(myVariable);
as you put it, is currently executed at the creation of your activity, as it is located in the onCreate method (which is why myVariable is still null) but never again after.
IT DISPLAYS NULL WHICH MEANS THAT String myVariable = null , its because you try to settext with a null variable only updated when onClick triggered.
You have to do this to make it work :
Declare and instantiate your EditText userIput outside your onclick method just after you instantiate your button and give your myVariable a default value "" in declaration .

Android Studio - Login page not working

I am trying to make a simple login page that with the correct username and password will go to another activity (Already been created) Also the attempt counter isn't functioning properly. Sorry If this poorly worded, hopefully it makes sense.
public class login extends Activity {
private EditText username;
private EditText password;
private Button login;
private TextView loginLocked;
private TextView attemptsLeft;
private TextView numberOfRemainingLoginAttemptsTV;
int numberOfRemainingLoginAttempts = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
setupVariables();
}
public void Login(View view) {
if (username.getText().toString().equals("admin") && password.getText().toString().equals("secret")) {
Intent i = new Intent(login.this, MainActivity.class);
startActivity(i);
Toast.makeText(getApplicationContext(), "Welcome User",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Wrong Credentials",
Toast.LENGTH_SHORT).show();
numberOfRemainingLoginAttempts--;
attemptsLeft.setVisibility(View.VISIBLE);
numberOfRemainingLoginAttemptsTV.setVisibility(View.VISIBLE);
numberOfRemainingLoginAttemptsTV.setText(Integer.toString(numberOfRemainingLoginAttempts));
if (numberOfRemainingLoginAttempts == 0) {
login.setEnabled(false);
loginLocked.setVisibility(View.VISIBLE);
loginLocked.setBackgroundColor(Color.RED);
loginLocked.setText("Please Try Again Later");
}
}
}
private void setupVariables() {
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
login = (Button) findViewById(R.id.button);
loginLocked = (TextView) findViewById(R.id.loginLocked);
attemptsLeft = (TextView) findViewById(R.id.attemptsLeft);
numberOfRemainingLoginAttemptsTV = (TextView) findViewById(R.id.numberOfRemainingLoginAttemptsTV);
numberOfRemainingLoginAttemptsTV.setText(Integer.toString(numberOfRemainingLoginAttempts));
}
}
When you use startActivity() you have to use it on the context (Not always. Only in certain conditions but I think it is a good practice to declare it on the context). So change startActivity(i) to login.this.startActivity(i);
Hopefully that should get it running.
Hope it helps!
EDIT: pls post your Layout file as well. AND in your public void login add this
REMEMBER: put it directly in the void and NOT in the if statement
Log.i("LOGIN DETAILS","Username: "+username.getText().toString()+"Password: "+password.getText().toString());
Then post your log cat with the info filter.
If your not so good with the log cat you can instead add this line of code in your public void login NOT in if statement
Toast.makeText(login.this, "Username: "+ username.getText().toString() + "password: " + password.getText().toString(), Toast.LENGTH_LONG).show();

EditText to phone memory?

I have found a very good solution to my problem on another post (Save entered text in editText via button)
however when I implement this code, my application crashes. Any advice would be appreciated, the error I receive is that the "String or" in the method makeTag() is not used. Please have a look
private Button savenotebutton1;
private SharedPreferences savednotes;
private EditText editText1;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.x1);
savenotebutton1 = (Button) findViewById(R.id.savenotebutton1);
editText1 = (EditText) findViewById(R.id.noteEditText1);
savednotes = getSharedPreferences("notes",MODE_PRIVATE);
editText1.setText(savednotes.getString("tag", "Default Value")); //add this line
savenotebutton1.setOnClickListener(saveButtonListener);
}
private void makeTag(String tag){
String or = savednotes.getString(tag, null);
SharedPreferences.Editor preferencesEditor = savednotes.edit();
preferencesEditor.putString("tag",tag); //change this line to this
preferencesEditor.commit();
}
public OnClickListener saveButtonListener = new OnClickListener(){
#Override
public void onClick(View v) {
if(editText1.getText().length()>0){
makeTag(editText1.getText().toString());
((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(editText1.getWindowToken(),0);
}
}
};
}
You should replace this
String or = savednotes.getString(tag, null);
With
String or = savednotes.getString("tag", "Default Value")
Under your makeTag() function
Update: Error is about you are not register your activity into manifest.xml file.

Trouble converting an editable to a string (username/password test)

I'm trying to create a simple username/password login screen. I have the layout done, and right now, I'm trying to set it so when the username (EditText) == "crete", then it should do something. Here is my code...:
public class Login extends Activity {
public static EditText username, password;
public Button loginbutton;
boolean accessgranted;
public String dbu, dbp, user1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
username = (EditText) this.findViewById(R.id.username);
password = (EditText) this.findViewById(R.id.password);
loginbutton = (Button) this.findViewById(R.id.loginbutton);
user1 = "crete";
loginbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try{
dbu = (username.getText()).toString();
}
finally{
if (dbu == user1){
username.setText("SUCCESS");
}
}
}
});
}
}
this, sadly, doesn't work. It correctly converts it to a string (i think) because when I tested this code out :
loginbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try{
dbu = (username.getText()).toString();
}
finally{
username.setText("done" + dbu);
}
}
}
});
It correctly enters what you entered into the EditText, plus the word "done".
There seems to be a problem with creating if-then statements??
You test for String equality with the method .equals("String").
With == you are testing if the references to the objects are equal.
Try using equalsIgnoreCase(String) instead of the == comparator.
Like this: dbu.equalsIgnoreCase(user1)
dub and user1 are two separate String objects. You're comparing them like this: dbu == user1. This will always return false. Instead, replace it with dbu.equals(user1).

Categories

Resources