0

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 ;(

1
  • for someone whom have same problem, please recheck your AndroidManifest Commented May 11, 2017 at 4:58

3 Answers 3

2

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())) { ... } 
Sign up to request clarification or add additional context in comments.

3 Comments

yea, looks better.. but the app still cant opened ("Unfortunately, XXX has stopped")
@eaglearms92 please share your crash log
ahh never mind, i didnt not declare on Manifest.. silly me, thx anyway :D
0
if (mButtonAns.getText().toString().equals(mAnswer)){ //do something } 

Comments

0

You can also use matches for comparing String

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.