i have a EditText in android in which i want the user to enter the text and checks for the condition "BYE"
Code sample:
EditText text = (EditText)findViewById(R.id.EditText01);
String abc= text .getText().toString();
while( !(abc).equals("bye")){
abc = text.getText().toString();//user should enter the text from keyboard and the while loop should go and chech the condition.but not able to enter the text
//do some operation with abc
}
How can i make user to enter the text??The UI should wait for the text to be entered(something like we have InputStreamReader in java applications).
Very Simple:-
EditText text = (EditText)findViewById(R.id.EditText01);
String str = text.getText().toString();
now in str u will get string which is entered in EditText
I don't think you need a loop to do this. From your comment it looks like you also have an "Enter" button or something that you click to do the checking. Just set an onclicklistener and onclick you can make the edittext invisible (or un-editable), check is the edittext is equal to "BYE" and then do your actions might look something like this:
final EditText ET = (EditText) findViewById(R.id.EnterText);
Button B1 = (Button) findViewById(R.id.EnterButton);
B1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ET.setVisibility(View.INVISIBLE);
if(ET.getText().toString() == "BYE")
{
//do something if it is "BYE"
} else {
Context context = getApplicationContext();
CharSequence text = "Please enter BYE";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
ET.setVisibility(View.VISIBLE);
} });
Instead of running this check in an infinite loop, only run it on every onKeyUp of the EditText. You know, anyway, that the condition will only ever be fulfilled if the user actually enters something.
Related
Sorry taking your time, am asked a question in a very wrong way.
So what I doing now, a small notepad program where the title and content saved of the note to the SQLite database.
This part working as should, but I don't have any input check and the app saving the note with empty title and content.
there is my current code for this :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dba = new DatabaseHandler(MainActivity.this);
title = (EditText) findViewById(R.id.titleEditText);
content = (EditText) findViewById(R.id.wishEditText);
saveButton = (Button) findViewById(R.id.saveButton);
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveToDB();
}
});
}
private void saveToDB() {
MyNote wish = new MyNote();
wish.setTitle(title.getText().toString().trim());
wish.setContent(content.getText().toString().trim());
dba.addWishes(wish);
dba.close();
//clear
title.setText("");
content.setText("");
Intent i = new Intent(MainActivity.this, DisplayNotesActivity.class);
startActivity(i);
How can I implement a basic input checking and avoid the saving of empty notes?
my first idea was to check the emptiness of the input and drop a toast message, tried several solutions from not, but not worked me.
many thanks
C
You have to be sure you're using the same EditText variable which in this case I think is title.
EditText title = (EditText) findViewById(R.id.titleEditText);
if(title.getText().toString().isEmpty()) {
Toast.makeText(MainActivity.this, "Input Text Is Empty.. Please Enter Some Text", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(MainActivity.this, title.getText().toString(), Toast.LENGTH_SHORT).show();
}
}
});
U need to specyfi your question.
But from what i undestood u don't know how check editText is empty and don't know why can't write into text box.
First easy method is just check length of string if it bigger than 0 that's meen it's not empty
EditText title = (EditText) findViewById(R.id.IDEDITTEXT);
if(String.valueOf(title.getText()).length()>0){
//do something
}else{
//do something
}
And about second (i thing question) is check your xml file (layout) does your editText is enabled and not is textViev.
Btw your code is hard to read like your question:)
EditText title = (EditText) findViewById(R.id.titleEditText);
if(title.getText().toString().length()<=0) {
Toast.makeText(MainActivity.this, "Input Text Is Empty.. Please Enter Some Text", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(MainActivity.this, title.getText().toString(), Toast.LENGTH_SHORT).show();
}
}
});
try this code...
I am trying to disable the button after it is clicked. Th app doesn't crash it just doesn't disable it. wondering could anyone help me out?
here is the on click method for the button i am trying to disable.
//Submit button for answer
final Button submit = (Button) findViewById(R.id.submit);
submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
EditText answerA = (EditText) findViewById(R.id.answerA);
String toCompare = answerA.getText().toString();
TextView score = (TextView)findViewById(R.id.score_text_a);
scoreKeeper scoremgr = new scoreKeeper();
//anaswer to input
if(toCompare.matches("Alligator") || toCompare.matches("alligator") ||
(toCompare.matches("Alligator ") || toCompare.matches("alligator "))) {
//adds to score if inout matches one of the above
scoremgr.addToScore();
score.setText("Your score is " +Integer.toString(scoremgr.checkScore()));
//calls the next letter class
Intent intent_b = new Intent(button_a.this, button_b.class);
startActivity(intent_b);
//displays a toast message if correct
Toast.makeText(button_a.this, "Well Done, You Got it Right", Toast.LENGTH_SHORT).show();
submit.setEnabled(false);
}else{
//displays a toast meaasge if wrong
Toast.makeText(button_a.this, "Wrong Answer, Try Again", Toast.LENGTH_SHORT).show();
}
}
});
You put your "setEnabled" under an if statement. Just put it before. If that's a feature, check if the correct statement is executed, the condition is probably invalid, resulting the button not being disabled.
In first place, check if your code are being executed, you are doing it right, also you can try to use to disable your button:
btn.setEnabled(false);
btn.setClickable(false);
Also, change your Button variable to an instance variable without final
and access it inside your onClick method.
If you want to remove the button from your layout, you can change the visibility on it:
btn.setVisibility(View.GONE):
in your xml file set
android:clickable="true"
and now
btn.setEnabled(false);
btn.setClickable(false);
and check your (if condition ) does it returns true or not
I'm trying to build basic calculator, but when I put a number at first edittext and hit add button, it gets crashed.
It is fine when I add two number in both editTexts. There was no problem in that. But the problem happened when I put only one number and hit add.
It is throwing NumberFormatException: Invalid int: "".
here is my basic code.
public class MainActivity extends AppCompatActivity {
EditText num1;
EditText num2;
Button add,sub,multi,div;
TextView MyResults;
String Number1 ;//;
String Number2 ;//
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
num1 = (EditText)findViewById(R.id.num1);
num2 = (EditText)findViewById(R.id.num2);
add = (Button)findViewById(R.id.Add);
sub = (Button)findViewById(R.id.Sub);
multi = (Button)findViewById(R.id.Multiple);
div = (Button)findViewById(R.id.Divide);
MyResults = (TextView)findViewById(R.id.results);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Number1 =num1.getText().toString();
Number2 =num2.getText().toString();
int mAdd1 = Integer.valueOf(Number1);
int mAdd2 = Integer.valueOf(Number2);
int myAdd = mAdd1+mAdd2;
MyResults.setText(String.valueOf(myAdd));
Toast.makeText(getApplicationContext(), "Added: "+ myAdd, Toast.LENGTH_LONG).show();
}
});
}//end OnCreate.
When you leave an EditText empty
int mAdd2 = Integer.valueOf(Number2);
Will crash because a empty String is not a valid Integer (hence the NumberFormatException).
You could put it in a try/catch like this:
try {
Number1 =num1.getText().toString();
Number2 =num2.getText().toString();
int mAdd1 = Integer.valueOf(Number1);
int mAdd2 = Integer.valueOf(Number2);
MyResults.setText(String.valueOf(myAdd));
Toast.makeText(getApplicationContext(), "Added: "+ myAdd, Toast.LENGTH_LONG).show();
catch (NumberFormatException e) {
//Give a toast saying the user did not enter two correct values
}
Or alternatively, check the value beforehand and check if nothing was entered:
number1 =num1.getText().toString();
number2 =num2.getText().toString();
if (number1.equals("") || number2.equals("")) {
//Show error or set numbers to a different value
}
However, for this to work you must assume the user did not enter anything that isn't a valid Integer like a letter, for example by setting the EditText's input type to numbers.
android:inputType="number"
You should do validation checking for a blank edit text and not do the calculation in this case.
Instead you might take advantage of EditText's setError(CharSequence) method where you can show a message to the user why the input is not valid.
I have a quick question.
I have a screen with some numbers, when you click one of the numbers, the number gets appended to the end of the edittext.
input.append(number);
I also have a backbutton, when the user clicks this button I want to remove the last character.
At the moment I have the following :
Editable currentText = input.getText();
if (currentText.length() > 0) {
currentText.delete(currentText.length() - 1,
currentText.length());
input.setText(currentText);
}
Is there an easier way to do this ? Something in the line of input.remove()?
I realise this is an old question but it's still valid. If you trim the text yourself, the cursor will be reset to the start when you setText(). So instead (as mentioned by njzk2), send a fake delete key event and let the platform handle it for you...
//get a reference to both your backButton and editText field
EditText editText = (EditText) layout.findViewById(R.id.text);
ImageButton backButton = (ImageButton) layout.findViewById(R.id.back_button);
//then get a BaseInputConnection associated with the editText field
BaseInputConnection textFieldInputConnection = new BaseInputConnection(editText, true);
//then in the onClick listener for the backButton, send the fake delete key
backButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
textFieldInputConnection.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL));
}
});
try this out,
String str = yourEditText.getText().toString().trim();
if(str.length()!=0){
str = str.substring( 0, str.length() - 1 );
yourEditText.setText ( str );
}
I am trying to get a message to appear when a button is clicked to tell the user to fill in the blank field. Currently, if the field is blank, it crashes/force closes the app. I tried to do the following code and had zero success. Originally I didn't have the if/else in there, I just ran the calculator(); method and the following imm code.
Could someone point me into the right direction?
public void onClick(View v)
{
if ((EditText)findViewById(R.id.amount1)== null)
{
Context context = getApplicationContext();
CharSequence text = "Enter a number";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
else
{
calculator();
InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
}
Im pretty sure this is the bad code:
if ((EditText)findViewById(R.id.amount1)== null)
Just dont know how to word it the way I want.
Try checking the length of the text in the EditText widget
EditText e = (EditText)findViewById(R.id.amount1));
if(e.getText().length == 0){
//Show Toast
}else{
//continue your code
}
Use this code.
EditText et = (EditText)findViewById(R.id.amount1));
if(et1.getText().length() == 0){
//Display toast here
} else{
//Your code
}
EditText text = (EditText)findViewById(R.id.amount1);
if(TextUtils.isEmpty(text.toString())) {
// show toast
}
Even if the field is blank, the edittext is not null. Use:
EditText editText = (EditText)findViewById(R.id.amount1);
String text = new String(editText.getText());
if (test.equals("")) {
//...
((EditText)findViewById(R.id.amount1)== null is just getting a reference to the EditText with the id amount1, it is not checking to see if that EditText has a valid entry.
To see if the EditText has text, you can get the String it holds by via EditText#getText().toString()
To make this work, first store the reference to the EditText in a var, then perform your checks on the String:
EditText et = (EditText)findViewById(R.id.amount1);
String amount1 = et.getText().toString();
if (amount1.equals("")) {
// Do your stuff here
}
I'm using local variables and just assuming you want the string to have content. You will likely need to do other checks to handle all the cases (like malformed input). Some of this you can reduce by setting the inputType on the EditText. For example, you might set it to numberDecimal if you are trying to handle only decimal numbers.
You actually want to check if the contents of the EditText are null or an empty string.
The line in question should look something like this:
if("".equals(((EditText)findViewById(R.id.amount1)).getText().toString()))
Of course you may want to break that statement up into more lines to make it a bit more readable!