IF Condition doesnt work - java

Am trying to make an IF condition but it's not working well. I want when the EditText is null, the user doesn't go to the next Activity.
when it's filled it goes to the next activity after a button press.
Name = is my EditText assignment
one_next_diaspora_bt = is the Button.
Below is my Code:
final String Name = name_diaspora_edt.getText().toString();
one_next_diaspora_bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(Name.matches("")){
Toast.makeText(getApplicationContext(),"Make sure that you have filled your name please !!!",Toast.LENGTH_LONG).show();
}
else {
Intent i = new Intent(Diaspora.this,DiasporaTwo.class);
i.putExtra("Name",Name);
i.putExtra("Age",Age);
i.putExtra("Gender",Gender);
i.putExtra("MaritalStatus",MaritalStatus);
startActivity(i);
}
}
});

Change your condition to this:
if(edt.getText().toString().isEmpty()){
}
Or
if (edt.getText().trim().equals("")){
}

use:
if (Name.getText() != null && Name.getText().toString().trim().equals(""))
And follow the Java naming convention. variable names should start with lower case character

try this:
if (Name != null && Name.equalIgnoreCase("null") && Name.trim().equalIgnoreCase("")){
}else
{
}

Use this :
one_next_diaspora_bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String Name = name_diaspora_edt.getText().toString().trim();
if(Name.matches("")){
Toast.makeText(getApplicationContext(),"Make sure that you have filled your name please !!!",Toast.LENGTH_LONG).show();
}
else{
Intent i = new Intent(Diaspora.this,DiasporaTwo.class);
i.putExtra("Name",Name);
i.putExtra("Age",Age);
i.putExtra("Gender",Gender);
i.putExtra("MaritalStatus",MaritalStatus);
startActivity(i);
}
}
});
}

Try TextUtils.isEmpty, it will check null and empty as well. TextUtils is a built-in class in package android.text
if(android.text.TextUtils.isEmpty(Name)) {

First I would say, you really should follow naming conventions.
But you need to grab the String that lives inside of your EditText and compare it with .equals like so:
if(name.getText().toString().equals("")){
//do something
}

if (TextUtils.isEmpty(Name)){
Toast.makeText(getApplicationContext(),"Make sure that you have filled your name please !!!",Toast.LENGTH_LONG).show();
}
Use android default validation, TextUtils class

Use TextUtils.isEmpty(Name) instead of Name.matches("").
TextUtils.isEmpty(CharSequence str) >> Returns true if the string is null or 0-length.
Try this:
final String Name = name_diaspora_edt.getText().toString();
one_next_diaspora_bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(TextUtils.isEmpty(Name)) {
Toast.makeText(getApplicationContext(),"Make sure that you have filled your name please !!!",Toast.LENGTH_LONG).show();
} else {
Intent i = new Intent(Diaspora.this, DiasporaTwo.class);
i.putExtra("Name", Name);
i.putExtra("Age", Age);
i.putExtra("Gender", Gender);
i.putExtra("MaritalStatus", MaritalStatus);
startActivity(i);
}
}
});
Hope this will help~

You can directly check the EditText with this method , equals() works with Strings.
Try This
String data = Name.getText().toString();
Then
if(data.isEmpty()){
}

Related

Setting Listeners programmatically to an array of CheckBoxes

So far, I've encountered the issue "variable x is accessed within inner class,needs to be declared final. I am able to initialize the CheckBox's but I am unable to set a listener to them after initialization in the loop. Below is my code so far.
for(int i=0;i<checkBox_fiber_ID.length;i++){
int temp=getResources().getIdentifier(checkBox_fiber_ID[i],"id",getPackageName());
checkBoxes_fiber[i]=findViewById(temp);
checkBoxes_fiber[i].setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if(checkBoxes_fiber[i].isChecked()){
//do something
}
}
});
}
Any tips on how to solve this?
Take final String[] x={"defaultvalue Emptry"}
Then after inside onclick Listener set value of x using below code.
x[0]="new value"
and use this value in different function.
as per your code it look likes blow:
final String x[] ={""}
for(int i=0;i<checkBox_fiber_ID.length;i++){
int temp=getResources().getIdentifier(checkBox_fiber_ID[i],"id",getPackageName());
checkBoxes_fiber[i]=findViewById(temp);
checkBoxes_fiber[i].setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if(checkBoxes_fiber[i].isChecked()){
x[0]=checkBoxes_fiber[i].getvalue==> value name
}
}
});
}
Outside function get value of x using
String name=x[0]
You can try to create separate class of listener
private View.OnClickListener mCheckboxListener = new View.OnClickListener() {
public void onClick(View v) {
if(((CheckBox)view).isChecked())
{
int checkBoxId = (int)v.getTag(); //You can get Id for specific checkbox
//do other stuff with checkBoxId
}
}
};
And set Id to each checkbox like
for(int i=0;i<checkBox_fiber_ID.length;i++){
int temp=getResources().getIdentifier(checkBox_fiber_ID[i],"id",getPackageName());
checkBoxes_fiber[i]=findViewById(temp);
checkBoxes.setTag(i); //set check box id as tag for later usage
checkBoxes_fiber[i].setOnClickListener(mCheckboxListener);
}
I guess you are trying to do something base on the checkbox IDs. You can set a tag for a checkBox and get back the tag in future. Also, the view object in method void onClick(View view) is now an CheckBox. Just change a little in your code:
for(int i=0;i<checkBox_fiber_ID.length;i++){
int temp=getResources().getIdentifier(checkBox_fiber_ID[i],"id",getPackageName());
checkBoxes_fiber[i]=findViewById(temp);
checkBoxes_fiber[i].setTag(i); //mark the check box id for later usage
checkBoxes_fiber[i].setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
if(((CheckBox)view).isChecked()){
int checkBoxId = (int)view.getTag();
doSomething(checkBoxId);
}
}
});
}
}
And write a new method for business code:
public void doSomething(int no){
if(no==1){
//do something
}
else if(no==2){
//do something
}
//...
}

Android studio cannot resolve symbol equals

I am making a simple mobile app. For now I am just testing the app and trying to pass some values in between java files and put them in empty TextViews. I get values from a previous activity via Intent and then trying to pass them on to another activity called ConsultActivity.java:
String username = getIntent().getStringExtra("Identifiant");
final TextView tv = (TextView)findViewById(R.id.TVUsername);
if(username.equals("marcel123")){
tv.setText("M Dupond");
}
else if(username.equals("tommy1")){
tv.setText("M Thompson");
}
else if(username.equals("emma89")){
tv.setText("Mme Sinieux");
}
consult = (ImageView)findViewById(R.id.consult);
consult.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(MainActivity.this,ConsultActivity.class);
i.putExtra("Username", tv.getText().toString());
startActivity(i);
}
});
However in my ConsultActivity, when I am doing basically the same thing, my equals are highlighted and say "Cannot resolve symbol equals"
String name = getIntent().getStringExtra("Username");
final TextView textV = (TextView)findViewById(R.id.TVUsername2);
if(name.equals("M Dupond")){
textV.setText("M Dupond");
}
else if(name.equals("M Thompson")){
textV.setText("M Thompson");
}
else if(name.equals("Mme Sinieux")){
textV.setText("Mme Sinieux");
}
Probably its just a Synchronization problem try with: Sych project with gradle files

Creating app in Android studio but keep getting an error Required Boolean found int

So I'm creating an app that validates a users input but when I did it for the password all it says is Required boolean found int
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user);
submit = (Button)findViewById(R.id.submit);
name = (EditText)findViewById(R.id.name);
pass = (EditText)findViewById(R.id.pass);
number = (EditText)findViewById(R.id.number);
email = (EditText)findViewById(R.id.email);
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final String Name = name.getText().toString();
final String Pass = pass.getText().toString();
if(name.length()==0)
{
name.requestFocus();
name.setError("Field cannot be empty");
}
else if(!Name.matches("[a-zA-Z]+"))
{
name.requestFocus();
name.setError("ENTER ONLY ALPHABETICAL CHARACTERS");
}
else if (pass.length())
{
pass.requestFocus();
pass.setError("FIELD CANNOT BE EMPTY");
}
else {
Context context = getApplicationContext();
CharSequence text = "Thank you, your request is being processed!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
});
}
The error is happening on the line where it says pass.length. Could anyone please help in what the problem is
Use
else if (pass.length()>0)
instead so that you get a boolean value to use inside the if condition
While using conditional statements you have to use boolean variable to check the condition is valid or not.
else if (pass.length())
Here pass.length() returns the length of the variable, which is an integer. You should not use the integer to check the condition.
In contrast with e.g. C/C++ language, Java does not allow numeric values to be used instead of boolean values (0/1 != false/true).

Conditional Statement Being Ignored

Checkout the following snippet:
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v==yes_button) {
//Toast.makeText(this, "All records have been deleted!", Toast.LENGTH_LONG).show();
db.open();
db.deleteAll();
db.close();
Intent intent = new Intent(this, home_screen_activity.class);
startActivity(intent); }
else if (v==no_button){
Intent intent = new Intent(this, home_screen_activity.class);
startActivity(intent); }
}
}
For some reason, the else if portion is being ignored and the code runs as if it's not there, so even if the no button is clicked, the database is still deleted. It must be something simple I'm missing, but I can't seem to nail it down. Anyone have any ideas?
Thanks for the input everyone, but I got the problem solved by renaming the no_button. Weird.
Since v is an object and not a primitive type, the == comparison compares object locations in memory, rather than testing for equality. Instead, you need to modify your test to use the .equals method:
if (v.equals(yes_button)) {
...
} else {
}
Also, if there's really only two alternatives, you can, as I have above, omit a test to see if the press was on the "no" button.
In android, I usually check by the R.id.
#Override
public void onClick(View v) {
int viewID = v.getId();
if (viewID == R.id.yes_button) {
} else if (newID == R.id.no_button) {

How to change background color of editText?

I need to change background color of EditText if it is empty.
Below is my code but doesn't seem to be working.
public void onClick(View v) {
// TODO Auto-generated method stub
Change();
}
public void Change() {
if(("").equals(name)) {
name.setBackgroundColor(Color.RED);
return;
}
}
The easiest way is to check the length:
if (name.length() == 0) {
name.setBackgroundColor(Color.RED);
}
Assuming 'name' is the EditText in question, your if statement should read something like this:
if(("").equals(name.getText().toString()))
Performing an Object.equals(Object) between a String and an EditText (at least currently!) will not return true.
String name = nameedittext.getText().toString();
if(name.isEmpty()){
nameedittext.setBackgroundColor(Color.RED);
}
If you want to give a error message too then you can write this:
if(name.isEmpty()){
nameedittext.setBackgroundColor(Color.RED);
nameedittext.setError("Please Enter Name");
return;
}

Categories