Conditional Statement Being Ignored - java

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

Related

I want to open a particular activity according to the value that I get from my firebase database [duplicate]

This question already has answers here:
What is the difference between == and equals() in Java?
(26 answers)
Closed 3 years ago.
I want to open a specific activity based on the data I retrieve from the firebase realtime database...
Firebase.setAndroidContext(this);
mRef=new Firebase("https://test-new-f2637.firebaseio.com/Name");
mValueView=(TextView) findViewById(R.id.valueView);
btn=(Button) findViewById(R.id.button);
mRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
value = dataSnapshot.getValue(String.class);
mValueView.setText(value);
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String n=mValueField.getText().toString();
if(n=="yes")
{
func1();
}
else
{
func2();
}
}
});
}
public void func1()
{
Intent intent = new Intent(this, first.class);
startActivity(intent);
}
public void func2()
{
Intent intent = new Intent(this, second.class);
startActivity(intent);
}
}
If I retrieve "yes" from the firebase databse then the first activity should be opened or else the second activity should open.
But the problem is that by retrieving the value as "yes" then also the second activity is opening
PS:-I'am new to android and firebase
n=="yes" will always be false
Have a read of this https://www.codejava.net/coding/10-common-mistakes-every-beginner-java-programmer-makes
https://www.codejava.net/coding/10-common-mistakes-every-beginner-java-programmer-makes#Comparison
The == operator compares two objects physically (their memory addresses) whereas the equals() method compares two objects semantically (their information). And in most of the cases, we should compare two objects meaningfully using the equals() method.
Try:
if("yes".equals(n)) {
func1();
} else {
func2();
}
Firstly, what is the value returned by Firebase, that you display on a Textview ?
Secondly, prefer using the method String#equals() to compare Strings.
Instead of if(n=="yes") , use if(n.equals("yes"))
you are getting text from another thextview and when you compare String value then don't use "==" use this ".equals("text")" for comparision in string :-
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String n=mValueView.getText().toString();
if(n.equals("yes"))
{
func1();
}
else
{
func2();
}
}
});

IF Condition doesnt work

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()){
}

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

Logic for WRONG,CORRECT and UNANSWERED QUESTIONS in the quiz app android

Want to implement "if" condition for WRONG,CORRECT and UNANSWERED QUESTIONS which will display correct,wrong and score at last.App runs but its not showing the correct score for it.
Want to implement below format in quiz-
if(wrong_Click_radioButton) {
wrong++;
nextquestion++;
}
if(correct_Click_radioButton) {
correct++;
nextquestion++;
}
if(not_clicked_any_radioButton) {
nextquestion++;
}
if(last_question_checking) {
score display;
switch to next android activity;
}
Want to implement the above concept.
#Override
public void onClick(View v) {
int id=gr.getCheckedRadioButtonId();
rbtanswer=(RadioButton) findViewById(id);
String answer=rbtanswer.getText().toString();
String check="Google";
if(answer.equals(check)) {
score=score+1;
}
Intent intent=new Intent(Next1Activity.this,Next2Activity.class);
Bundle b=new Bundle();
b.putInt("score",score);
intent.putExtras(b);
startActivity(intent);
Toast.makeText(getApplicationContext(), "Your score is"+score,Toast.LENGTH_SHORT).show();
}
Doing your works something like this........
I think problem here.......this part runs when did not select any radio button......so create wrong answer

Getting rid of "==" syntax error in android

The elseif(v == button2) line gives an error saying that "Syntax error on token '==', delete this token". I got the idea of using this from the topic "Variable OnClick listener android" from this website. Can anyone please tell me how to use it?
Here is my code:
View.OnClickListener yourListener = new View.OnClickListener(){
public void onClick(View v){
if( v == button1){
new AlertDialog.Builder(this)
.setTitle("Paracettamol")
.setMessage("This medicine is generally used to cure Fever")
.setNeutralButton("OK", null)
.show();}
}
elseif( v == button2){
new AlertDialog.Builder(this)
.setTitle("sertraline")
.setMessage("This medicine is generally used to cure Head aches")
.setNeutralButton("OK", null)
.show();
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
} ;
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
}
The answer of the asked question mentioned above has the following code:
Button btn1, btn2;
public void onCreate(Bundle b)
{
// here you do normal things like assigning a
// content view to the activity, initiate buttons, etc.
// then you assign the same listener to both buttons
btn1.setOnClickListener(yourListener);
btn2.setOnClickListener(yourListener);
}
// declare a OnClickListener that will execute different actions
// depending on the view that was clicked
View.OnClickListener yourListener = new View.OnClickListener(){
public void onClick (View v){
if( v == btn1 ){
// do something
}
elseif( v == btn1 ){
// do another thing
}
}
};
You might missed space between else and if - "elseif( v == button2) "
ah...
Your code sample is a mess...
I've re-formatted it and correct errors. Now it should work.
View.OnClickListener yourListener = new View.OnClickListener() {
public void onClick(View v) {
if (v == button1) {
new AlertDialog.Builder(v.getContext())
.setTitle("Paracettamol")
.setMessage(
"This medicine is generally used to cure Fever")
.setNeutralButton("OK", null).show();
} else if (v == button2) {
new AlertDialog.Builder(v.getContext())
.setTitle("sertraline")
.setMessage(
"This medicine is generally used to cure Head aches")
.setNeutralButton("OK", null).show();
}
}
};
Could you be more accurate asking question next time?

Categories