My activity doesnt recognise text equality - android

Can someone help me, I'm killing myself over here. So in my activity I have this code and the application constantly displays that CurrentQ is not equal (currentQ.getODG() != answer.getText()) to the answer
I can see through LogCat with Log.d that the words are identical. I just can't understand what am I doing wrong.
08-25 05:28:45.125: D/yourans(25316): na život u mraku na život u mraku
this is from log cat
RadioGroup grp = (RadioGroup) findViewById(R.id.radioGroup1);
answer = (RadioButton) findViewById(grp.getCheckedRadioButtonId());
Log.d("yourans", currentQ.getODG() + " " + answer.getText());
if (currentQ.getODG().equals(answer.getText())) {
answer.setBackgroundResource(R.drawable.radiotocan);
Toast poruka1 = Toast.makeText(getApplicationContext(), "Točno!",
Toast.LENGTH_LONG);
View vieew1 = poruka1.getView();
// vieew.setBackgroundColor(Color.parseColor("#BD8BDC"));
vieew1.setBackgroundResource(R.drawable.toast1);
poruka1.setView(vieew1);
poruka1.setGravity(Gravity.CENTER_HORIZONTAL, 1, 1);
poruka1.show();
score1++;
Log.d("score1", "Your score" + score1);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
answer.setBackgroundResource(R.drawable.radiomain);
}
}, 300);
}
else if (currentQ.getODG() != answer.getText()) {
answer.setBackgroundResource(R.drawable.radionetocan);
Toast poruka2 = Toast.makeText(getApplicationContext(),
"Netočno, točan odgovor je:" + currentQ.getODG(),
Toast.LENGTH_LONG);
View vieew2 = poruka2.getView();
// vieew.setBackgroundColor(Color.parseColor("#BD8BDC"));
vieew2.setBackgroundResource(R.drawable.toast);
poruka2.setView(vieew2);
poruka2.setGravity(Gravity.CENTER_HORIZONTAL, 1, 1);
poruka2.show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
answer.setBackgroundResource(R.drawable.radiomain);
}
}, 300);
}

Try
if(currentQ.getODG().equalsIgnoreCase(answer.getText()))
instead of
if(currentQ.getODG()!=answer.getText())
Hope it helps!

Java uses the double-equals sign to check to see if the objects the two variables point to are the same object, not whether they are equivalent. Since both Strings are each returned by two separate method calls, they will never be the same object.
Instead you'll want to use one of the equality-testing methods from the String class:
.equals(String b) Tests to see if the two strings are exactly the same.
.equalsIgnoreCase(String b) Tests to see if the two strings are the same, ignoring whether they're uppercase or lowercase.
There are more options you can find in the String class's documentation, just check the public methods list.
In your case, change this line:
else if (currentQ.getODG() != answer.getText()) {
To read like:
else if (!currentQ.getODG().equals(answer.getText())) {
But for more flexibility in recognizing answers, use .equalsIgnoreCase() like this:
else if (!currentQ.getODG().equalsIgnoreCase(answer.getText())) {

try this:
change:
currentQ.getODG().equals(answer.getText())
to:
currentQ.getODG().trim().equalsIgnoreCase(answer.getText().trim())
change:
else if (currentQ.getODG() != answer.getText())
to:
else
I think probably there's blank space in your string, so use trim() to cut them out, then compare the strings while ignoring capital letter.
FYI: Reference.

Related

Unable to iterate over SegmentList while more than one match is found

I'm modifying the pocketsphinx android demo to test continuous keywords spotting based on a keywords list and relative thresholds.
When the onResult method of my implementation of edu.cmu.pocketsphinx.RecognitionListener is called this string
hypothesis.getHypstr() will contain the list of possible matches.
I read here that to get every single match and their weights it is possible to do like this:
for (Segment seg : recognizer.getDecoder().seg()) {
System.out.println(seg.getWord() + " " + seg.getProb());
}
However my code running is never iterating over segments like if SegmentList was empty while hypothesis.getHypstr() shows more than one match.
To reproduce the case I'm using this keyword list with very low tresholds so that more matches are easily found:
rainbow /1e-50/
about /1e-50/
blood /1e-50/
energies /1e-50/
My onPartialResult method is doing nothing while:
public void onEndOfSpeech() {
switchSearch(KWS_SEARCH);
}
public void onResult(Hypothesis hypothesis) {
if (hypothesis != null) {
for (Segment seg : recognizer.getDecoder().seg()) {
//No iteration is done here!!!
Log.d("onResult", seg.getWord() + " " + seg.getProb());
}
String text = hypothesis.getHypstr();
makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
}
For example if I say "energies" then hypothesis.getHypstr()="blood about energies blood" but no iteration is done over SegmentList: I can see it by putting a breakpoint at the beginning of the onResult method.
Any suggestion?
Thanks
There is a threading issue here. onResult message is delivered when recognizer is already restarted in switchSearch and so hypothesis is cleared and query for result returns nothing.
You can put this code inside switchSearch before recognizer is restarted, then it will work ok:
private void switchSearch(String searchName) {
boolean wasRunning = recognizer.stop();
if (wasRunning) {
for (Segment seg : recognizer.getDecoder().seg()) {
Log.d("!!!! ", seg.getWord());
}
}
// If we are not spotting, start listening with timeout (10000 ms or 10 seconds).
if (searchName.equals(KWS_SEARCH))
recognizer.startListening(searchName);
else
recognizer.startListening(searchName, 10000);
String caption = getResources().getString(captions.get(searchName));
((TextView) findViewById(R.id.caption_text)).setText(caption);
}
If you use only keyword spotting, you can also put this code inside onPartialResult which is invoked as soon as keyphrase is detected, not when silence is detected. That makes reaction faster. You do not need onEndOfSpeech and onResult in pure keyword spotting.

How to ignore spaces between text editview Android

I am trying to ignore spaces in editview between text, I am not quite sure how I can go about doing this. I know I can use trim feature to ignore spaces before and after the full text but how do I ignore space between strings if there is any;
String myTextEdited myText.getText().toString().trim();
For example, if I have / user types in this;
Allan Bob
3523 JKO
NY1 U90
I want to ingore spaces when I read this in my if statement or put it in another variable for example;
String name = "AllanBob"
For example, to ignore upper and lower cases I am doing this;
if (myText.getText().toString().trim().equalsIgnoreCase(userInput)) {
// do something
} else {
// do something
}
What I would like to do is add another feature in here that also ignores spaces before, between and after text e.g. instead of;
myname is Henry . (space until here)
It should read it as mynameishenry but to the user it still appears as they have written it.
Please let me know if my question was not clear, I will try explaining it better
EDITED:
is it possible to ignore spaces in string that I have inside my if statement. For example;
if (myText.getText().toString().trim().equalsIgnoreCase("Henry 0887")) {
// do something
} else {
// do something
}
but currently if the user types in henry0887, the if statement does not validate it because I added a space inside my validation text and therefoe its looking for a space in the text, is it possible to over come this, so even if I have space inside my validation it ignores it.
Did you try this:
String myString = myEditText.getText().toString();
myString = myString .replace(" ", "");
Hope it helps
EDIT:
if (myText.getText().toString().replace(" ", "").equalsIgnoreCase(userInput) || myText.getText().toString().equalsIgnoreCase(userInput)) {...
Try this,
if(myText.getText().toString().trim().replace(" ","").equalsIgnoreCase(userInput)) {
// do something
} else {
// do something
}
Hope this helps.
use replaceAll() method.
str = str.replace(" ","");
or for all space chars:
str = str.replace("\\s+","");
EDIT
if (myText.getText().toString().replace("\\s+","").equalsIgnoreCase(userInput)) {
// do something
} else {
// do something
}
EDIT2
if (myText.getText().toString().replace("\\s+","").equalsIgnoreCase("Henry 0887".replace("\\s+",""))) {
// do something
} else {
// do something
}

Comparing two EditText values in android

I'm trying to make an app where the user enters a word into an EditText box. Then, they enter something into another box and it checks to see if they are the same word. Here's the code that I used:
String word = textfield1.getText().toString();
String answer = textfield2.getText().toString();
textfield2.setText(textfield2.getText().toString());
if(word == answer){
Toast.makeText(getApplicationContext(), "correct",
Toast.LENGTH_LONG).show();
}else
Toast.makeText(getApplicationContext(), "incorrect", Toast.LENGTH_LONG).show();
}
However, it always says that the two strings aren't the same even if they are. Is there a way to fix this?
You can't compare strings with the == operator.
Use .equals() instead:
if(word.equals(answer)) {
//do whatever
}
Use String.equalsIgnoreCase for comparing content of both string variables.:
if(word.equalsIgnoreCase(answer)){
}
Use:
String word = textfield1.getText().toString();
String answer = textfield2.getText().toString();
if(answer.contentEquals(word)){
// Do something if equals
}
else{
// Do something if not equals
}
I think the best way to do this is using TextUtils:
if(TextUtils.equals(textfield1.getText(),textfield2.getText())){
//do something
}
instead of
if(word.contentEquals(answer)){
}
Use
if(word.equals(answer))
as we cant compare strings with Equal to (==) operator
Try This::
String word = textfield1.getText().toString();
String answer = textfield2.getText().toString();
if(word.equals(answer)){
Toast.makeText(getApplicationContext(), "correct",
Toast.LENGTH_LONG).show();
}else
Toast.makeText(getApplicationContext(), "incorrect", Toast.LENGTH_LONG).show();
}

android EditText value

I have the weirdest problem...
all I am trying to do is to get the value from a EditText and do some validation.
The value in the edittext must be between 1 and 10. However, even if I enter any number between 1 or 10 , it still validates false. I even tested the edittext input to make sure it is correct , and it is, but the if still fails . Any ideas ?
here is the code:
ed = (EditText) dialog2.findViewById(R.id.ed_quantity);
Button bq = (Button) dialog2.findViewById(R.id.alert_a);
dialog2.setCancelable(false);
dialog2.show();
bq.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v)
{
String test = ed.getText().toString();
Toast toast23452234 = Toast.makeText(mContext, "Quantity: "+test, Toast.LENGTH_LONG);
toast23452234.show();
if(test=="1"||test=="2"||test=="3"||test=="4"||test=="5"||test=="6"||test=="7"||test=="8"||test=="9"||test=="10")
{
quantity = Integer.parseInt(ed.getText().toString());
dialog2.dismiss();
ed.setText("1");
}
else
{
Toast toast2345223 = Toast.makeText(mContext, "Quantity must be between 1 and 10" , Toast.LENGTH_LONG);
toast2345223.show();
}
}
});
try this
test.trim().equalsIgnoreCase("1")
in your if-condition
Use equals method to compare strings..
if(test.equals("1")||test.equals("2")||test.equals("3")||test.equals("4")||test.equals("5")||test.equals("6")||test.equals("7")||test.equals("8")||test.equals("9")||test.equals("10"))
or use int to compare
int test = Integer.valueOf(ed.getText().toString());
String is not a native type so you can't do test=="1". This compares the object references and obviously the two objects have different references.
Call equals(Object object) method on string object. Like,
test.isEquals("1")
Better parse the input string to integer as
int testInteger = Integer.parseInt(test);
and compare as
if(testInteger==1 || testInteger ==2)
This saves many method calls to string object.
use .equals("") in case of String.
if(test.equals("1")||test.equals("2")||test.equals("3")||test.equals("4")||test.equals("5")||test.equals("6")||test.equals("7")||test.equals("8")||test.equals("9")||test.equals("10"))
use .equals on string operation instead of ==
if(test.equals("1")||... and so on)
or else convert string into "int".
Use test.equals("1") || .....
You can also do this
int t = Integer.parseInt(test);
if(t == 1 || t == 2 || ...)

"if" not working properly

hey,
i'm new to android and i have a problem. here is my code:
Log.v("Test", "" + lv_arr_id[0]); //displays 0
if (lv_arr_id[0] == "0") {
Toast.makeText(longOperationContext, "A", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(longOperationContext, "B", Toast.LENGTH_SHORT).show();
}
lv_arr_id[0] has the value "0" and is a string, its external data pulled via json from web. however each time the B toast gets triggered instead of the A toast. the value really is 0, i tested this in the logcat.
any ideas why?
thanks in advance
== compares the object and not the String contents. Use .equals("0") instead.
It's not that if is not working properly.
In Java, you can't use == to compare objects of java.lang.String class. You need to use equals method.
Something like:
if (lv_arr[0].equals("0")) {
//
} else {
}

Categories

Resources