Results 1 to 3 of 3
- 10-04-2011, 08:33 AM #1
Member
- Join Date
- Oct 2011
- Posts
- 12
- Rep Power
- 0
how to choose between two answers in android Java
i am new to android develop ,
and i have that code that it should print on screen "hello" if i put in the text box "1"
and "hi" if 2 , but it dosent work
so any help will be accepted
and here is the code:
thanks for the helpersJava Code:import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class FindcityActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button button = (Button) findViewById(R.id.button1); final EditText nameField = (EditText) findViewById(R.id.editText1); final String name = nameField.getText().toString(); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if(name.equals("1")) { Toast.makeText(FindcityActivity.this, "Hello ", Toast.LENGTH_SHORT).show(); } else if(name == "2") { Toast.makeText(FindcityActivity.this, "Hi ", Toast.LENGTH_SHORT).show(); } } }); } }
- 10-04-2011, 06:22 PM #2
Senior Member
- Join Date
- Oct 2010
- Location
- Germany
- Posts
- 780
- Rep Power
- 4
Re: how to choose between two answers in android Java
You have to evaluate the value of the textfield when clicking on the button, not before (because there you will get an empty string :D)
And the first one ist right! Use equals instead of "==".
Summary: remove the line 17 and change the listener code to
Java Code:button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (nameField.getText().toString().equals("1")) { Toast.makeText(FindcityActivity.this, "Hello ",Toast.LENGTH_SHORT).show(); } else if (nameField.getText().toString().equals("2")) { Toast.makeText(FindcityActivity.this, "Hi ",Toast.LENGTH_SHORT).show(); } } });
- 10-05-2011, 07:59 AM #3
Member
- Join Date
- Oct 2011
- Posts
- 12
- Rep Power
- 0
Similar Threads
-
15 most Java Interview Questions With Answers
By manideep.d132 in forum Reviews / AdvertisingReplies: 2Last Post: 01-23-2012, 08:26 PM -
need answers to this java program
By peixd in forum New To JavaReplies: 2Last Post: 06-14-2010, 04:23 AM -
Java- Interview Questions and Answers
By nishants in forum Java SoftwareReplies: 0Last Post: 04-17-2010, 12:48 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks