comparing two strings in Android ( if-else statemente) - android

I am working on a login page in an Android App.
As you know, the app must check if the username and password are valid, and then grant the user access to the application.
I have used the following code:
...
EditText un = (EditText) findViewById(R.id.username1);
EditText pw = (EditText) findViewById(R.id.password1);
String u = un.getText().toString();
String p = pw.getText().toString();
//////// Now on the click of the Login Button:
public void onClickL (View view){
if ( (u.equals("Android")) && (p.equals("1234"))) /////// move to a new activity
else ///////Display a warning message: Try again
}
when I run this code this only executes the else part. why its not executing the if part? what should I do ?

The reason is that you are fetching the EditText's value while declaring the EditText. Actually you nee to fetch the Text from EditText while clicking on the button, hence you need to move you code to onClick() method like below,
#Override
public void onClick (View view)
{
String u = un.getText().toString();
String p = pw.getText().toString();
if ( (u.equals("Android")) && (p.equals("1234"))) /////// move to a new activity
{
....
}
else ///////Display a warning message: Try again
{
....
}
}

please try this:
public void onClickL (View view){
u = un.getText().toString();
p = pw.getText().toString();
if ( u.equals("Android") && p.equals("1234") ) /////// move to a new activity
{
}
else ///////Display a warning message: Try again
{
}
}

try Following code
need to clear space in username if it is available.
public void onClick (View view){
String username = un.getText().toString().trim();
String password = pw.getText().toString();
if ((username.equals("Android")) && (password.equals("1234"))) {
//do something
} else{
//do something
}
}

Try this..
get the text inside Click function like below
public void onClick (View view){
String u = un.getText().toString().trim();
String p = pw.getText().toString().trim();
if ((u.equals("Android")) && (p.equals("1234"))) {
//do something
}
else{
//do something
}
}

Related

Android studio login system

i am trying to create a login system on android studio using java, i have tried a piece of code i have found and modifies it to my own program- i am getting errors that the tutorial cannot explain and would appreciate if someone could tell me what i'm doing wrong.
on line 10 under username it says expression expected
The else statement says there should be an if but as you can see there is ?
public void LoginButton(){
UserName = findViewById(R.id.UserName);
userPassword = findViewById(R.id.userPassword);
userPin = findViewById(R.id.userPin);
GoBtn.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
if (UserName.getText().toString().equals("user");// here i would preferably link to a database but do to time restaitns i have modeled it with user
userPassword.getText().toString().equals("pass");
{
Toast.makeText(MainActivity.this, "Username and password is correct",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity.this, StudentActivity.class);
startActivity(intent);
}
else {
Toast.makeText(MainActivity.this,"Username and password is NOT correct",
Toast.LENGTH_SHORT).show();
}
}
I need this to lead the user to the next activty if the input is correct but so far i cannot get it to run due to the errors.
Issues
You can't use a semicolon (;) right after if statement because an empty ; is also considered a statement.
If Statement is incorrect: It has to be a valid statement
Many braces ({ and }) are missing
Here is a sample code
public void LoginButton() {
UserName = findViewById(R.id.UserName);
userPassword = findViewById(R.id.userPassword);
userPin = findViewById(R.id.userPin);
GoBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (UserName.getText().toString().equals("user") &&
userPassword.getText().toString().equals("pass")) {
// use your code
} else {
// use your code
}
}
});
}
Suggestion: Please read more Java
your if condition syntax is wrong you need to use AND operator(&&).
change these lines
if (UserName.getText().toString().equals("user");
userPassword.getText().toString().equals("pass");
to
if((UserName.getText().toString().equals("user")) && (userPassword.getText().toString().equals("pass")))

How to link code to EditText view to check the email validity?

I'm completely new to android and development too. I created a page to take the email EditText, password EditText and signup button. So here how can I link this EditText to code to verify the entered values in both EditText is valid?
Below is the code that i'm trying to use.
public void isEmailValid(View view) {
this.view = view;
EditText editText = (EditText) findViewById(R.id.editText);
if (editText.getText().toString().matches("[a-zA-Z0-9._-]+#[a-z]+\\.+[a-z]+") && editText.length() > 0) {
editText.setText("valid email");
} else {
editText.setText("invalid email");
}
}
Thanks in advance.
If you want to evaluate email address after clicking the button you might set a click listener for your button and do it :
Button yourButton = (Button) findViewById(R.id.your_button);
yourButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
evaluateEmail();
}
});
and here is your method for evaluation :
private void evaluateEmail() {
EditText editText = (EditText) findViewById(R.id.editText);
if (editText.getText().toString().matches("[a-zA-Z0-9._-]+#[a-z]+\\.+[a-z]+") && editText.length() > 0) {
//it is valid
} else {
//it is not valid
}
}
Try this code:
public final static boolean isValidEmail(CharSequence target) {
return !TextUtils.isEmpty(target) &&
android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
How can we perform Email Validation on edittext in android ? I have gone through google & SO but I didn't find out a simple way to validate it. follow link..
How should I validate an e-mail address?
You can use Android Patterns class to perform match for your email regex.
Patterns.EMAIL_ADDRESS.matcher(editText.getText().toString()).matches();

How to Check the empty text fields before uploading image or video in android?

I'm new to stackoverflow and android, sorry if i'm wrong. I am trying to check the text fields is empty or not, when the text field is empty, upload button should show please enter title and when user enters the text then only it should upload the image. After entering title then also it again shows the toast.
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (title1.matches("")){
Toast.makeText(getApplicationContext(), "Please enter the Title and Category", Toast.LENGTH_SHORT).show();
} else if(description1.matches("")){
Toast.makeText(getApplicationContext(), "Please Select Category", Toast.LENGTH_SHORT).show();
} else {
flag = 1;
// uploading the file to server
new UploadFileToServer().execute();
}
}
});
Any help would be appreciated.
To check for empty fields, use
if(TextUtils.isEmpty(editText.getText().toString())) {
// do something
}
or if you want to check if string is empty or null use -
if(TextUtils.isEmpty(stringToCheck) {
// do something
}
try this.
Place this code in your button onClickListener:
String mText = mEditText.getText().toString();
if(TextUtils.isEmpty(mText)){
//Do what you want(Edittext is NULL)
}else{
//Do what you want(Not NULL)
}
Try to get value from your edittext like below:
Globally declare variable : -
String editvalue;
In onCreate() :-
EditText youredittext = (EditText)findViewById(R.id.youredittextid);
editvalue = youredittext.getText.toString().trim();
Now in your condition check :
if(editvalue.isEmpty() || editvalue == null){
// Do what you want when editText's value is null or empty
}else{
}
You can also use
TextUtils.isEmpty(CharSequence str)
for empty and null string check.
Returns true if the string is null or 0-length

empty field error only first block execute

public void save_record()
{
name_val = name.getText().toString();
pass_val = password.getText().toString();
cpass_val = cpassword.getText().toString();
save.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(name_val.equals(null)==true || pass_val.equals(pass_val)==true || cpass_val.equals(cpass_val)==true)
{
Toast.makeText(getApplicationContext(), "Complete Text Field",Toast.LENGTH_LONG).show();
}
}
});
}
if all fields are completed or not only first block execute... please tell me anser
here you are using || between your conditions so if all fields are empty then
if(name_val.equals(null)==true) is going to be executed and if all the fields are filled then one of the other two will execute for sure because you are comparing
pass_val.equals(pass_val)==true and cpass_val.equals(cpass_val)==true which is always going to be true so check your conditions and then try

Android - How to check if textview is null or not null

I have some textview in my application
and want to check whether the properties of text on my textview has a value or null.
then i want to display a toast if the value on my textview null
but the toast is not running as it should
this is my code :
public class brekeleV2 extends Activity {
static Context context;
brekeleV2Model r = new brekeleV2Model();
private EditText jalan, kota, postal;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
context = getApplicationContext();
Button go = (Button)findViewById(R.id.go);
go.setOnClickListener(onGo);
Button reset = (Button)findViewById(R.id.reset);
reset.setOnClickListener(onRes);
jalan =(EditText)findViewById(R.id.jalan);
kota =(EditText)findViewById(R.id.kota);
postal =(EditText)findViewById(R.id.post);
jalan.setText(null);
kota.setText(null);
postal.setText(null);
}
and this is the onClick method code:
private View.OnClickListener onGo=new View.OnClickListener() {
public void onClick(View v) {
if (jalan.getText()!= null && kota.getText()!=null){
switch(v.getId()){
case R.id.go:
Intent maps = new Intent();
maps.setClassName("com.openit.brekele", "com.openit.brekele.brekeleV2Nav");
brekeleV2Nav.putLatLong(lat, lon);
startActivity(maps);
break;
}
}else{
Toast msg = Toast.makeText(brekeleV2.this, "Lengkapi Data", Toast.LENGTH_LONG);
msg.setGravity(Gravity.CENTER, msg.getXOffset() / 2, msg.getYOffset() / 2);
msg.show();
}
if(!textview.getText().toString.matches(""))
{
// not null not empty
}else {
//null or empty
}
This is what I would use.
if (mText1.getText().length() > 0 && mText2.getText().length() > 0) {
// Your code.
}
in the end i found my problem solving. here is my code:
if (jalan.getText().toString().length()>0 || kota.getText().toString().length()>0){
//switch(v.getId()){
//case R.id.go:
Intent maps = new Intent();
maps.setClassName("com.openit.razer", "com.openit.razer.mapRazerNav");
mapRazerNav.putLatLong(lat, lon);
startActivity(maps);
//break;
//}
}else{
Toast msg = Toast.makeText(razerNav.this, "Lengkapi Data", Toast.LENGTH_LONG);
msg.setGravity(Gravity.CENTER, msg.getXOffset() / 2, msg.getYOffset() / 2);
msg.show();
}
i used to check the length, because on my xml i add like this :
android:text=" "
see? this is my fault.
anyway thanks for helping me. :)
TextView has a public length() method you can use to check if there are any characters in the TextView.
if (textView.length() > 0) {
// textView is not null
} else {
// textView is null
}
Try textView.getText() != "" instead.
Are you sure that the else condition is invoked? Debug it!
Maybe you need to put the toast into a runOnUiThread statement:
runOnUiThread(new Runnable() {
public void run() {
mText.setText("Hello there, " + name + "!");
}
});
Method getText() in TextView returns EditAble that cant compare with String
you should convert EditAble to String using String.ValueOf() method.
String jalanContent = String.ValueOf(jalan.getText());
if(jalanContent.equals(""){
//do your action here
} else {
//some action here
}
hope it'd be usefull
if (jalan.getText()!= null && kota.getText()!=null)
This is the line of code that doesn't work for you.
Best solution for such scenario is using matches("") method for String
So the solution will be:
if (!jalan.getText().toString.matches("") && !kota.getText().toString().matches("")){
// code for not null textViews
}
else
{
//Code for nul textView
}
I would have modified the correct answer a bit (missing () after toString but we're not allowed edit code so:
if(textview.getText().toString().matches(""))
{
// is null or empty
}else {
//not null or empty
}

Categories

Resources