android: Log in Button - android

I'm having problem with my Log in activity.. the button will load the next activity even though no data inputted on the text field..
here's the code...
public void onButtonClick(View v){
if(v.getId()== R.id.Blogin) {
EditText a = (EditText)findViewById(R.id.TFusername);
String str = a.getText().toString();
EditText b = (EditText)findViewById(R.id.TFpassword);
String pass = b.getText().toString();
String password = helper.searchPass(str);
if(pass.equals(password))
{
Intent i = new Intent(User.this, Userlog.class);
i.putExtra("Username",str);
startActivity(i);
}
else
{
Toast temp = Toast.makeText(User.this, "Username and Password don't match!", Toast.LENGTH_SHORT);
temp.show();
}

Check for empty strings
replace
if(pass.equals(password))
with
if(pass.equals(password) && !TextUtils.isEmpty(str) && !TextUtils.isEmpty(pass))
This should work.
Cheers

You can check if a String is empty using the TextUtils class's isEmpty method, which is a static one.
// Checks if a username & a password were typed, then checks if password is correct
if(!TextUtils.isEmpty(str) && !TextUtils.isEmpty(pass) && pass.equals(password))
Notice that you are not checking whether the username is valid or not.

In you helper. searchPass(), do you return an empty string if no usrName is matched?If so, you have to check if the returned string is empty or you can return another special value :D

Related

If statement, Android Studio with Firebase

So I am trying to send data back to my Firebase Database with only users that have signed up and logged in. I have written a code to send the data but i am trying to write an else if statement that a message in this case a Toast appears if they have not signed up. I am struggling to write a code for that.
private void sendScore() {
String userName = name.getText().toString();
String userScore = BenchScore.getText().toString();
if(!TextUtils.isEmpty(userName) && !TextUtils.isEmpty(userScore)) {
String id = databaseReference.push().getKey();
ScoreProfile scoreProfile = new ScoreProfile(id, userName, userScore);
databaseReference.child(FirebaseAuth.getInstance().getUid()).setValue(scoreProfile);
name.setText("");
BenchScore.setText("");
} else if(FirebaseAuth.getInstance().) {
Toast.makeText(Score.this, "You need to sign up in order to use this", Toast.LENGTH_SHORT).show();
}
}
If you want to check if an user is logged in you can use :
...
else if( FirebaseAuth.getInstance().getCurrentUser() == null )
{
// Call your toast here
}
Replace ur code with this one:
private void sendScore() {
String userName = name.getText().toString();
String userScore = BenchScore.getText().toString();
if(FirebaseAuth.getInstance().getUid() != null && !TextUtils.isEmpty(userName) && !TextUtils.isEmpty(userScore)){
String id = databaseReference.push().getKey();
ScoreProfile scoreProfile = new ScoreProfile(id, userName, userScore);
databaseReference.child(FirebaseAuth.getInstance().getUid()).setValue(scoreProfile);
name.setText("");
BenchScore.setText("");
} else if (FirebaseAuth.getInstance().getUid() == null) {
Toast.makeText(Score.this, "You need to sign up in order to use this", Toast.LENGTH_SHORT).show();
}
}
I've just included a check for whether getUid() is non null in the if statement and in else if, I've checked whether getUid() is null. This would serve your purpose, hopefully.

i want "enter data" msg when ever i click on submit button without filling the details and decreasing id value whenever i delete 1 item

i have created a app with 3 edit text and and 3 buttons,
Edittext:
- id
- name
- date
Button:
submit.
check.
delete.
name to store name of user,
date to store date,
submit to store data in sqlit database,
check to retrive data,
delete to delete the specfied id in database,
id is auto incremented it is used when deleting.
my problem here is if i not enter anything in the edit text it takes null values
and display as shown in below pic instead of taking null i want to show message "PLEASE ENTER DATA"
and whenever i delete data next id value must decrease by 1 please help me.
Before entering the data to database use should check EditTexts are null or not in on click method and if null print toast messages like below
idEditText = (EditText) findViewById(R.id.editText_id);
nameEditText = (EditText) findViewById(R.id.editText_Name);
dateEditText = (EditText) findViewById(R.id.editText_Date);
String id = idEditText.getText().toString().trim();
String name = nameEditText.getText().toString().();
String date = dateEditText.getText().toString().();
if(id.length() == 0 || name.length() == 0 || date.length())
{
Toast.makeText(this, "Please fill all details",Toast.LENGTH_SHORT).show();
}
Try this
idEditText =(EditText) findViewById(R.id.editText_id);
nameEditText =(EditText)findViewById(R.id.editText_Name);
dateEditText =(EditText)findViewById(R.id.editText_Date);
private boolean checkEmptyFields() {
boolean check = false
String id = idEditText.getText().toString().trim();
String name = nameEditText.getText().toString().trim();
String date = dateEditText.getText().toString().trim();
if (id.isEmpty()) {
idEditText.setError("Invalid Input");
check = true;
} else {
dEditText.setError(null);
check = false;
}
if (name.isEmpty()) {
nameEditText.setError("Invalid Input");
check = true;
} else {
nameEditText.setError(null);
check = false;
}
if (date.isEmpty()) {
dateEditText.setError("Invalid Input");
check = true;
} else {
dateEditText.setError(null);
check = false;
}
return check;
}
if (!checkEmptyFields())
{
//Add Data to DB
}

How to test string for null value

Have a problem with this code!
I want to check the editText values, if it is null or not...
But it gets stuck at the if segment, doesnt mather if it is a value in the editText or not.
If there is a value in the editText string it should go further and calculate the values.
Second problem I have is the toast, it doesnt show the text in the string variable, it just prints the string link.
private EditText fp;
private EditText fC;
private EditText drive;
private TextView totalcost;
public void CalcButton(View button) {
// Converting strings to float and check if each is NULL (empty)
if (!(fp.getText().equals(null)) || (fC.getText().equals(null)) || (drive.getText().equals(null)))
{
Toast.makeText(getApplicationContext(), "#string/toast", Toast.LENGTH_LONG).show();
}else {
String n1 = fp.getText().toString();
float no1 = Float.parseFloat(n1);
String n2 = fC.getText().toString();
float no2 = Float.parseFloat(n2);
String n3 = drive.getText().toString();
float no3 = Float.parseFloat(n3);
// Calculates the floats
float calc = no1 * no2 * no3;
// Converting and prints out the result
String sum = Float.toString(calc);
totalcost.setText(sum);
}
You should not do it this way, do this instead:
if (!fp.getText().toString().equals("")) {
}
To problem with Toast - use this:
Toast.makeText(getApplicationContext(), R.string.toast, Toast.LENGTH_LONG).show();
Try to use TextUtils.isEmpty() instead, it checks for null and 0-length String.
On your if statement it should look like:
if (!TextUtils.isEmpty(fp.getText().toString())) {
// Code
}
And on your Toast, change "#string/toast" to R.string.toast or getApplicationContext().getString(R.string.toast);
The code should look like:
// Converting strings to float and check if each is NULL (empty)
if (! (TextUtils.isEmpty(fp.getText().toString()) ||
(TextUtils.isEmpty(fC.getText().toString())) ||
(TextUtils.isEmpty(drive.getText().toString()))))
{
Toast.makeText(getApplicationContext(), getApplicationContext().getString(R.string.toast), Toast.LENGTH_LONG).show();
}
More on the getString() method here.
EDIT: I've seen that your code also was missing a pair of parenthesis ( ). So your "not" was only applying to the first test.
Something like:
!(test1) || test2 || test3
Instead of
!((test1) || (test2) || (test3))
To check if EditText is empty you do editText.getText().toString().equals("")
So, Your if-statement will look like this:
if (!(fp.getText().toString().equals("")) ||
(fC.getText().toString().equals("")) ||
(drive.getText().toString().equals("")))
And your Toast would be like this:
Toast.makeText(getApplicationContext(), R.string.toast, Toast.LENGTH_LONG).show();
function isNull(int resourceId, boolean getError){
EditText editText= (EditText) findViewById(resourceId);
String strEditText = String.valueOf(editText.getText());
if(TextUtils.isEmpty(strEditText)) {
if(getError) editText.setError("this is null!");
return true;
}else{
return false;
}
}
May be this block gives you a few clues about yours
about If Conditions;
In your 'IF conditions', parentheses seems less than the count it is necessary.
Try to add one more after (!)
I guess it should be like this;
for Negative
if (!(
(String.valueOf(fp.getText()).equals("")) ||
(String.valueOf(fC.getText()).equals("")) ||
(String.valueOf(drive.getText()).equals(""))
))
for Positive
if (
(String.valueOf(fp.getText()).equals("")) ||
(String.valueOf(fC.getText()).equals("")) ||
(String.valueOf(drive.getText()).equals(""))
)

Android: Check if EditText is Empty when inputType is set on Number/Phone

I have an EditText in android for users to input their AGE. It is set an inputType=phone.
I would like to know if there is a way to check if this EditText is null.
I've already looked at this question: Check if EditText is empty. but it does not address the case where inputType=phone.
These, I've checked already and do not work:
(EditText) findViewByID(R.id.age)).getText().toString() == null
(EditText) findViewByID(R.id.age)).getText().toString() == ""
(EditText) findViewByID(R.id.age)).getText().toString().matches("")
(EditText) findViewByID(R.id.age)).getText().toString().equals("")
(EditText) findViewByID(R.id.age)).getText().toString().equals(null)
(EditText) findViewByID(R.id.age)).getText().toString().trim().length() == 0
(EditText) findViewByID(R.id.age)).getText().toString().trim().equals("")
and isEmpty do not check for blank space.
Thank you for your help.
You can check using the TextUtils class like
TextUtils.isEmpty(ed_text);
or you can check like this:
EditText ed = (EditText) findViewById(R.id.age);
String ed_text = ed.getText().toString().trim();
if(ed_text.isEmpty() || ed_text.length() == 0 || ed_text.equals("") || ed_text == null)
{
//EditText is empty
}
else
{
//EditText is not empty
}
First Method
Use TextUtil library
if(TextUtils.isEmpty(editText.getText().toString())
{
Toast.makeText(this, "plz enter your name ", Toast.LENGTH_SHORT).show();
return;
}
Second Method
private boolean isEmpty(EditText etText)
{
return etText.getText().toString().trim().length() == 0;
}
Add Kotlin getter functions
val EditText.empty get() = text.isEmpty() // it == ""
// and/or
val EditText.blank get() = text.isBlank() // it.trim() == ""
With these, you can just use if (edittext.empty) ... or if (edittext.blank) ...
If you don't want to extend this functionality, the original Kotlin is:
edittext.text.isBlank()
// or
edittext.text.isEmpty()
EditText textAge;
textAge = (EditText)findViewByID(R.id.age);
if (TextUtils.isEmpty(textAge))
{
Toast.makeText(this, "Age Edit text is Empty", Toast.LENGTH_SHORT).show();
//or type here the code you want
}
I use this method for same works:
public boolean checkIsNull(EditText... editTexts){
for (EditText editText: editTexts){
if(editText.getText().length() == 0){
return true;
}
}
return false;
}
Simply do the following
String s = (EditText) findViewByID(R.id.age)).getText().toString();
TextUtils.isEmpty(s);
I found that these tests fail if a user enters a space so I test for a missing hint for empty value
EditText username = (EditText) findViewById(R.id.editTextUserName);
EditText password = (EditText) findViewById(R.id.editTextPassword);
// these hint strings reflect the hints attached to the resources
if (username.getHint().equals("Enter your username") || password.getHint().equals("Enter Your Password")){
// enter your code here
} else {
// alls well
}
editText.length() usually works for me
try this one
if((EditText) findViewByID(R.id.age)).length()==0){
//do whatever when the field is null`
}
Java: Check if EditText is Empty
1) find the EditText
ourEditText = view.findViewById(R.id.edit_text);
2) Get String value of EditText
String ourEditTextString = ourEditText.getText().toString();
3) Remove all spaces
Incase user inputs only blank spaces.
String ourEditTextNoSpaces = ourEditTextString.replaceAll(" ","");
3) Check if empty
boolean isOurEditTextEmpty = ourEditTextNoSpaces.isEmpty();
Try this. This is the only solution I got
String phone;
try{
phone=(EditText) findViewByID(R.id.age)).getText().toString();
}
catch(NumberFormatException e){
Toast.makeText(MainActivity.this, "plz enterphone Number ", Toast.LENGTH_SHORT).show();
return;
}

Remember Me Function At Login

I have two textbox and a checkmebox. But when i type my username and password and tick on the checkmebox, exit the application and go back again it doesn't appear. Why?
// Get reference to UI elements
txtLogin = (EditText) findViewById(R.id.txtLogin);
txtPassword = (EditText) findViewById(R.id.txtPassword);
SharedPreferences pref = getSharedPreferences(PREFS_NAME,MODE_PRIVATE);
String username = pref.getString(PREF_USERNAME, null);
String password = pref.getString(PREF_PASSWORD, null);
if (username == null || password == null) {
//Prompt for username and password
Toast.makeText(getBaseContext(),
"HI",
Toast.LENGTH_SHORT).show();
}
// Remember me function
CheckBox cbRemember = (CheckBox) findViewById(R.id.chkRememberPassword);
if (cbRemember.isChecked()) {
getSharedPreferences(PREFS_NAME,MODE_PRIVATE)
.edit()
.putString(PREF_USERNAME, txtLogin.toString())
.putString(PREF_PASSWORD, txtPassword.toString())
.commit();
}
First: You should not be using txtLogin.toString(); but rather use txtLogin.getText(); to get the values from the editText controls.
Are you sure the code that saves the preferences is invoked?
use these to get value
String username = txtLogin.getText().toString().trim();

Categories

Resources