Android Questions App Answer==MyAnswer not null - android

I make android questions app. I can not find the right answer. Answer list.
Right answer: String answer = quizList.get(position).getAnswer();
Button Click:
buttonA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (answer =="A"){
lblsignboard.setText("Ok");
}
else
{
lblsignboard.setText("No");
}
}
});
Answer = "A", but this code does not work. Always gives the answer is no.

When you are comparing strings in java,always use .equals
Because the function (.equals) checks the actual contents of the string, the == operator checks whether the references to the objects are equal.
and now furthur using equalsignorecase you need not to worry about search string is in caps or small.
buttonA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (equalsIgnoreCase("a")){
lblsignboard.setText("Ok");
}else{
lblsignboard.setText("No");
}
}
});

You can use this way too, to keep you code working even the answer key is of different case. Use either equals("A") or equalsIgnoreCase("a").
buttonA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (answer.equals("A") || equalsIgnoreCase("a")){
lblsignboard.setText("Ok");
}else{
lblsignboard.setText("No");
}
}
});

In Android we make use of two things to compare strings:
1. equals : this is used when you want to compare even case of the string.
2. equalsIgnoreCase: This is just for content comparison.
Here is the small illustration as how it works:
String myString = "heLLo";
if(myString.equals("hello"))
{
System.out.print("equals");
}
else if(myString.equalsIgnoreCase("hello"))
{
System.out.print("equalsIgnoreCase");
}
Here equalsIgnoreCase will be printed.

Strings can only compare by .equals method not by ==. Also you have to check string is null or not because .equals method may invoke
nullpointerexception and you app may crash.
buttonA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(answer!=null &&(answer.equals("A")||equalsIgnoreCase("a"))) {
lblsignboard.setText("Ok");
} else {
lblsignboard.setText("No");
}
}
});

String can compare is .equals or .eqalignorecase not a '==' sign.'==' using a int value compare.
String answer=item.get(position).getAnswer();
if(answer!=null && (answer.equals("A")||equalsIgnoreCase("a")){
Log.e("Comapare","----------Success");
}else{
Log.e("Comapare","----------not compare");
}

Related

Android method rewrite to Lambda

I've want to rewrite the method to Lamda.
CheckCar.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
CheckMotor.setChecked(false);
et_mileage.setText(String.valueOf(DistanceTextD_Car));
}
});enter code here
Lamda:
CheckCar.setOnClickListener(view->CheckMotor.setChecked(false));
But how to add et_mileage.setText(String.valueOf(DistanceTextD_Car));
Just change the single expression to a statement block
CheckCar.setOnClickListener(view -> {
CheckMotor.setChecked(false));
et_mileage.setText(String.valueOf(DistanceTextD_Car));
});
As the docs say, the arrow token -> is followed by
A body, which consists of a single expression or a statement block.
CheckCar.setOnClickListener(view-> {
CheckMotor.setChecked(false);
et_mileage.setText(String.valueOf(DistanceTextD_Car));
});

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

Why is that unreachable code?

I'm generating a question and answers of that randomly. And I want to generate new random arrays and answer options according to those when users chose the correct answer. But it says "unreachable code" when I add a boolean while loop... What is theproblem?
Thanks...
final boolean basadon = false;
while(basadon)
{
Random soru = new Random();
final int[] rastgele = new int[1];
for (int i=0; i<1; i++)
{
rastgele[i]= soru.nextInt(8);
}
ArrayList<Integer> cevap = new ArrayList<Integer>();
for (int k = 0; k <= 7; ++k)
{
cevap.add(k);
}
final Integer[] rastgele2 = new Integer[4];
if (rastgele[0]!=cevap.get(0))
{
rastgele2[0]=cevap.get(0);
}
else
{
rastgele2[0]=cevap.get(3);
}
if (rastgele[0]!=cevap.get(1))
{
rastgele2[1]=cevap.get(1);
}
else
{
rastgele2[1]=cevap.get(3);
}
if (rastgele[0]!=cevap.get(2))
{
rastgele2[2]=cevap.get(2);
}
else
{
rastgele2[2]=cevap.get(3);
}
rastgele2[3]=rastgele[0];
Collections.shuffle(Arrays.asList(rastgele2));
view.setText(countries.get(rastgele[0]));
cevap1.setBackgroundResource(heads[rastgele2[0]]);
cevap1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (rastgele[0]==rastgele2[0])
{
cevap1.setBackgroundResource(heads[8]);
countries.remove(rastgele[0]);
basadon=true;
}
else {
cevap1.setBackgroundResource(heads[9]);
}
}
});
cevap2.setBackgroundResource(heads[rastgele2[1]]);
cevap2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (rastgele2[1]==rastgele[0])
{
cevap2.setBackgroundResource(heads[8]);
countries.remove(rastgele[0]);
basadon=true;
}
else {
cevap2.setBackgroundResource(heads[9]);
}
}
});
cevap3.setBackgroundResource(heads[rastgele2[2]]);
cevap3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (rastgele2[2]==rastgele[0])
{
cevap3.setBackgroundResource(heads[8]);
countries.remove(rastgele[0]);
basadon=true;
}
else {
cevap3.setBackgroundResource(heads[9]);
}
}
});
cevap4.setBackgroundResource(heads[rastgele2[3]]);
cevap4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (rastgele2[3]==rastgele[0])
{
cevap4.setBackgroundResource(heads[8]);
countries.remove(rastgele[0]);
basadon=true;
}
else {
cevap4.setBackgroundResource(heads[9]);
}
}
});
}
} }
Looks like you start with basedon value as false and later set it to true inside the loop.
So, Change
final boolean basedon = false
while (basedon) {
....
}
to
boolean basedon = false;
do {
....
} while (basedon);
while(basadon) is always false, so you never enter the loop. What you really mean is probably while(basadon==false). Also, don't declare basalon as final boolean because you want to modify its value later, and that will give error.
Why are you declaring all of those variables as final?
If bsadon for example needs to change from false to true, it can't be final. A final value is exactly that, a constant, it won't change.
Don't declare something as final unless you want it to keep the same value for the entire runtime of your program.
You are saying basadon is always "false", that's what final means, so the compiler is telling you you will never enter the while, since you need it to evaluate "true" to enter.
The expression between () in you while clause, needs to evaluate to true for the code to enter.
To your specific question which you have asked:
Why does the compiler give unreachable code warning
The answer is that since the condition in while loop is always false, there is no chance that the code in while loop will get executed. The warning is given to indicate that (given the current code situation) you have wasted your effort in typing that portion of code and it is guaranteed never to be executed. To rectify this, you can remove the final modifier from basedon and put a programming logic to set the value of basedon which will decide whether to enter the loop or not. If you want the loop to always run put while(true).
But I believe that what you wanted to ask was how to make the random question and answer generator. For that you'll have to post a bigger chunk of your code (It looks like you are trying to put a loop over a listener callback ?) and phrase your question to ask specific problems (possibly post a separate question).
It's probably complaining because basadon is known to be false and the body of the while loop cannot be reached. You can suppress the complaint by adding this annotation to the method:
#SuppressWarnings("unused")
You might also try removing the final modifier from the declaration of basadon. That might resolve the issue (but I'm not sure about that).
EDIT I finally noticed that you are trying to modify basadon directly from within your click listeners. That obviously won't work if basadon is final, yet you cannot access local variable unless it is final. I suggest you change basadon to be a (non-final) field of the enclosing class. Then all the warnings and errors should go away.

Login not working

I have written the simple code for Login authentication with hardcoded password.my problem is evenif I am entering the correct password my control is going in elese loop
edt=(EditText)findViewById(R.id.edt);
btn=(Button)findViewById(R.id.sub);
s1=edt.getText().toString();
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.d("mynameeeeee",s1);
if(s1=="123")
{
Toast.makeText(getApplicationContext(), "Successful",Toast.LENGTH_LONG).show();
}
else
{
Log.d("coming in elseeeee","coming in elseeeee");
Toast.makeText(getApplicationContext(), "not valid",Toast.LENGTH_LONG).show();
}
}
});
Here's the problem :
You are storing a reference of the edit text content at creation time, when the edit text is empty.
You should retrieve the content of the edit text EVERYTIME you want to compare, which is when the button is clicked in your case :
Do the following :
edt=(EditText)findViewById(R.id.edt);
btn=(Button)findViewById(R.id.sub);
btn.setOnClickListener ( new OnClickListener () {
#Override
public void onClick ( View v ) {
Log.d ( "mynameeeeee" , edt.getText().toString() );
if ( edt.getText().toString().equals ( "123" ) )
{
Toast.makeText(getApplicationContext(), "Successful",Toast.LENGTH_LONG).show();
}
else
{
Log.d("coming in elseeeee","coming in elseeeee");
Toast.makeText(getApplicationContext(), "not valid",Toast.LENGTH_LONG).show();
}
}
});
the string should be compared like:
if(s1.equals("123")) {}
Change your if statement like this
if(s1.equals("123"))
{
Toast.makeText(getApplicationContext(), "Successful",Toast.LENGTH_LONG).show();
}
else
{
Log.d("coming in elseeeee","coming in elseeeee");
Toast.makeText(getApplicationContext(), "not valid",Toast.LENGTH_LONG).show();
}
When comparing strings always use .equals() function
== Checks whether both the variable are referring to same object. In this case since they are referring to different object so the result of == is false.
use equals() method s1.equals("123") to check the content of the string object.

How to set my username and password in the code.?

Button loginbuttonbutton = (Button) findViewById(R.id.btnLogin);
loginbuttonbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if(inputEmail.getText().toString() == "EdEffort#ncat.edu" &&
inputPassword.getText().toString() == "Steelers") {
Intent myIntent = new Intent(view.getContext(),
Host_Setting_PageActivity.class);
startActivityForResult(myIntent, 0);
} else {
System.out.println("Username or password is incorrect");
}
}
});
That is my code and the application actually start but whenever I hit the login button the application closes.
first use .equals() to compare strings.
== compares string refrences.Not value.
.equals() = compare strings character equality
if((inputEmail.getText().toString().equals("EdEffort#ncat.edu")&&inputPassword.getText().toString().equals("Steelers"))
And if force close than put logcat here..
use equals insead of == for String comparison
loginbuttonbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if(inputEmail.getText().toString().equals("EdEffort#ncat.edu") && inputPassword.getText().toString().equals("Steelers") ){
Intent myIntent = new Intent(YOUR_CURRENT_ACTIVITY.this, Host_Setting_PageActivity.class);
startActivityForResult(myIntent, 0);
}
else{
System.out.println("Username or password is incorrect");
}
}
});
and make sure you are registering YOUR_CURRENT_ACTIVITY.this and Host_Setting_PageActivity.class both in manifest.xml
You should add
Host_Setting_PageActivity.class to your AndroidManifest
And also, you should compare strings always using .equals and not with "==" as "==" will really compare the instance of the string object and .equals will check the value of the string
dont use == method in if Condition but used .equals() method
like as
if(inputEmail.getText().toString().equals("abc") && inputPassword.getText().toString().equals("abc") ){
----------your code here-----------
}

Categories

Resources