0

Ok my pattience is gone now...I tried for 30 minutes to make this simple thing work but I failed so bad.Maybe it is because I started directly with android,no java...I studied c++ before,and in c++ this was so easy to do...

I have a button in a xml file:

 <Button android:text="Button" android:layout_width="wrap_content" android:id="@+id/button1" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:layout_marginBottom="108dp"> </Button> 

And in my java file I have a string like this:

 String test = new String(); test = "google"; 

I 've already set up the onclick listener for the button so there is no problem. My question is if:

 Button buttonx = (Button)findViewById(R.id.button1); 

How can I compare if onClick(onclick code is already made) buttonx's text = the string test that is "google".

I tried with getText,setText...but nothing...

3 Answers 3

2

OK. First things first: Strings are completely different in Java to C++. In fact, Objects are pretty different all-round.

String test = new String(); test = "google"; 

does not do what you think it does.

What this does is create a new empty String object and store a reference to it in test. The next line stores a reference to a constant String "google" in test and makes the empty String you constructed in the previous line eligible for garbage collection. This is completely different to C++, where the second line would actually call the = operator on the String class. You can kinda think of everything in Java being a pointer (but not really), so assignment in Java behaves like pointer assignment in C++ (but not really).

Back to your question.

Something like this might work:

String test = "google"; Button b = ...; if (test.equals(b.getText()) { // whatever } 

Remember that although Java and C++ share some syntax similarities they are really completely different languages. Java references kinda behave like pointers, but not really.

Really.

Sign up to request clarification or add additional context in comments.

Comments

1
String test = new String(); test = "google"; Button buttonx = (Button)findViewById(R.id.button1); if (test.equals(buttonx.getText())) { // it's equal } 

Comments

0
if (button.getText().toString().equalsIgnoreCase(test)) Toast.makeText(this, "Button text equals!", Toast.LENGTH_SHORT).show(); else Toast.makeText(this, "Button text is not the same.", Toast.LENGTH_SHORT).show(); 

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.