eaglearms92
eaglearms92

Reputation: 33

compare two text (one from Button, compare after click it), Android

i am new in Android Studio, can you help me? from fragment code below, i try to compare two text which one of it is from Button, after click test_ans button, will go to 'true' activity if they are same. But unfortunately the app is stopped :(

package com.xxx.xxx.xxx;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class Main extends AppCompatActivity {

private String mAnswer = "xxx";
private Button mButtonAns;

static {
    System.loadLibrary("native-lib");
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mButtonAns = (Button)findViewById(R.id.test_ans);
    mButtonAns.setOnClickListener(new View.OnClickListener(){

        @Override
        public void onClick(View view) {

            if (mButtonAns.getText() == mAnswer) {
                Intent i = new Intent(Main.this, True.class);
                startActivity(i);
                //^go to true activity

            } else {
                //go to false activity
            }

        }
    });
}
}

i tried delete @Override public void onClick(View view), the getText() become red, is that onClick is the problem? please help ;(

Upvotes: 0

Views: 1685

Answers (3)

user7960788
user7960788

Reputation:

You can also use matches for comparing String

if (mAnswer.matches(mButtonAns.getText())) { ... }

Upvotes: 0

Shubham
Shubham

Reputation: 531

if (mButtonAns.getText().toString().equals(mAnswer)){
    //do something 
}

Upvotes: 0

Linh
Linh

Reputation: 60923

For compare 2 string you need to use equals instead of ==. == will compare the pointer of 2 String and equals will compare the value of 2 String

if (mAnswer.equals(mButtonAns.getText())) {
   ...
}

Upvotes: 2

Related Questions