I have a program that has 10 images. I want to change the background of each image when the user enters valid text in editText. So basically if user enters valid text in the editText it will change the first image (image 1). If the user enters text again in editText it should change image 2 etc. until image 10.
I have tried to create a list of images and retrieve every element in the image.
I don't know if my logic is wrong
The images are stamp1, stamp2, stamp3, stamp4 ....stamp12
final String Entercode = codeNumber.getEditableText().toString().trim();
Toast.makeText(getApplicationContext(),Entercode,Toast.LENGTH_SHORT).show();
if (Entercode.equals("sweet")){
for (int i = 0; i < stampImageList.size(); i++) {
Object obj = stampImageList.get(i);
stampImageList = new ArrayList();
stampImageList.add(stamp1);
stampImageList.add(stamp2);
stampImageList.add(stamp3);
stampImageList.add(stamp4);
stampImageList.add(stamp5);
stampImageList.add(stamp6);
stampImageList.add(stamp7);
stampImageList.add(stamp8);
stampImageList.add(stamp9);
stampImageList.add(stamp10);
stampImageList.add(stamp11);
stampImageList.add(stamp12);
if (obj == stampImageList.get(2)) {
// stamp4.setBackgroundResource(R.drawable.earned_stamp);
stamp3.setBackgroundResource(R.drawable.earned_stamp);
AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
builder.setIcon(R.drawable.logo);
builder.setMessage("Stamp Earned");
} else if (obj == stampImageList.get(3)) {
stamp5.setBackgroundResource(R.drawable.earned_stamp);
AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
builder.setIcon(R.drawable.logo);
builder.setMessage("Stamp Earned");
}
}
} else{
AlertDialog.Builder alert = new AlertDialog.Builder(getApplicationContext());
alert.setIcon(R.drawable.logo);
alert.setTitle("Validation results");
alert.setMessage("validation failed");
}
You should use TextWatcher to EditText.In afterchange method you compare with values.
EditText et = (EditText)findViewById(R.id.editText);
Log.e("TextWatcherTest", "Set text xyz");
et.setText("xyz");
et.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) { }
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
#Override
public void afterTextChanged(Editable s) {
Log.e("TextWatcherTest", "afterTextChanged:\t" +s.toString());//Compare here with stamp1 or like that
}
});
#steve, here I have prepared a code for 10 Drawable Images in your project.
public class Pictures_Activity_stack extends AppCompatActivity {
private String TAG= "Pictures_Activity---";
private ImageView picture;
private EditText text;
private Button validate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pictures_stack);
picture = (ImageView)findViewById(R.id.picture); //imageview where your picture changes
text = (EditText) findViewById(R.id.text);//edittext where you input text
validate = (Button) findViewById(R.id.button);//button to validate the text and change picture accordingly
// array to store your drawable images
final int pictures[] = {
R.drawable.firstimage,
R.drawable.secondimage,
R.drawable.p3,
R.drawable.p4,
R.drawable.p5,
R.drawable.p6,
R.drawable.p7,
R.drawable.p8,
R.drawable.p9,
R.drawable.p10
};
// click the button to set the image
validate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String input = text.getText().toString(); //input from edittext
if (input.equals("first")) {
picture.setImageResource(pictures[0]); //set first image in array if input=first
Toast.makeText(getBaseContext(),input,Toast.LENGTH_SHORT).show();
}
else if (input.equals("second")) {
picture.setImageResource(pictures[1]);//set first image in array if input=secind
Toast.makeText(getBaseContext(),input,Toast.LENGTH_SHORT).show();
}
// else if (input.equals("third")) {
// // and so on for other string values...
// .................................
// }
else
{
// if your input does not matches any string do this
Toast.makeText(getBaseContext(),"NO MATCHED STRING",Toast.LENGTH_SHORT).show();
}
}
});
}
}
The above code set images according to input in edit Text, when button is clicked.
What I'm trying to do is:
If the EditText input is equal to the random number generated, then stop the loop otherwise keep on the loop and reset input text.
For some reason, I'm getting an infinite loop. I am new to programming, any help is really appreciated.
Here is the code:
public class Main extends Activity implements OnClickListener{
private TextView tvResult;
private TextView tvRandTest;
private EditText et1;
private String randonNumber;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tvResult = (TextView) findViewById(R.id.textView4);
tvRandTest = (TextView) findViewById(R.id.textView3);
et1 = (EditText) findViewById(R.id.editText1);
}//End Main
public void myClickHandler(View view)
{
if(view.getId() == R.id.button1)
{
//Generates 6 one digit Random Numbers
int randonNumber1 = (int) (0 + Math.random() * 9);
//Parse Numbers
String rd1 = Integer.toString(randonNumber1);
randonNumber = rd1;
boolean done = false;
do
{
et1.getText().toString();
if(et1.equals(randonNumber))
{
Toast.makeText(Main.this,"Equal Number", Toast.LENGTH_SHORT).show();
tvResult.setText(randonNumber);
done = true;
}//end if
else
{
Toast.makeText(Main.this,"Not Equal Number", Toast.LENGTH_SHORT).show();
et1.setText("");
}//end else
}//End While
while(!done);
}//End if
if(view.getId() == R.id.button2)
{
tvRandTest.setText(randonNumber);
}
}//End Method
#Override
public void onClick(View arg0) {
// TODO
}
}//End Class
if(et1.equals(randonNumber))
I will change it with
if(et1.equals(String.valueOf(randonNumber)))
you put directly the int value inside the equals method two things will happen:
the autboxing will create an Integer object starting from the int value
the toString() method will be called through this object.
the toString() method of Integer in android, as the doc stands:
Returns a string containing a concise, human-readable description of this object.
So you are compareing the address of the new object with the content of et1 and not with its real value. Here the reference
In this line et1.getText().toString(); you need to assign result to variable, for example String input = et1.getText().toString(); Then in next line you need to compare two strings, if(input.equals(randonNumber)) But your program can hang cause of infinity loop on UI thread. You should use TextWatcher
to handle when text in EditText was changed
I have a problem regarding Edit Text in Android.
I have a field named Username :
I want that whenever someone writes a username with a space e.g "Gaurav Arora". Then it should raise a toast or error on the login button press.
I did in this way - I simply stopped the effect of space bar with the help of a text watcher as-
public static TextWatcher getNameTextWatcher(final TextView agrTextView) {
TextWatcher mTextWatcherName = new TextWatcher() {
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
}
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
}
public void afterTextChanged(Editable arg0) {
String result = agrTextView.getText().toString().replaceAll(" ", "");
if (!agrTextView.getText().toString().equals(result)) {
agrTextView.setText(result);
}
}
}
But this has not solved my purpose. I just want to implement whenever the person uses a username with space it should accept the space but on the press of login button it should raise a toast
Thanks
Just check if your edit text contains blank space or not.
Use the following code in the onClick() event of the Button.
if (agrTextView.getText().toString().contains(" ")) {
agrTextView.setError("No Spaces Allowed");
Toast.makeText(MyActivity.this, "No Spaces Allowed", 5000).show();
}
Try this..
btnLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String result = agrTextView.getText().toString();
if(result.contains ("\\s"))
Toast.makeText(getApplicationContext(), "Space ", Toast.LENGTH_LONG).show();
}
});
Simply do this:
TextView.getText().toString().contains(" ");
String question = txtNote.getText().toString();
if(question.trim().length() > 0){
Log.i("LOG", "Has value");
}else{
Log.i("LOG", "don't has value");
}
use trim() method to remove all spaces and then check for empty
if ( !edtText.getText().toString().trim().isEmpty()) {
//the EditText is not Empty
}
Also you can block entering space bar in username, or can give toast or snack on entering space in username .
Can refer this link might be helpful for you Block entering space in edittext.
Let me know if any concern.
What's wrong here ?
Random numbers work well.
Checking the part number also works well.
But when I type a the same number that has been randomly selected is always "Toast Bad".
Code: http://pastebin.com/0pdySnW9
Sorry but i can't paste code here.
In your onClick method you are infact generating another random number.
So the number you are typing in, is NOT going to be equal to the random number, as it is NOT the one displayed on screen.
Depending on what you are trying to achieve.. remove line 32, and make random a global variable.
In your onClick you are generating a new random number with this line
int random = random();
You should make your random variable amember variable so that it can be accessed throughout your activity without changing
ex
public class MainActivity extends Activity implements OnClickListener {
private TextView display;
private Button ok;
public EditText et;
private int random; //note this is now a member variable
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ok = (Button) findViewById(R.id.button1);
ok.setOnClickListener(this);
display = (TextView) findViewById(R.id.textView1);
et = (EditText) findViewById(R.id.etNumbers);
random = random();
display.setText("Random Number:" + random); // Show the random number
}
// ************RANDOM******************************
public static int random() {
Random generator = new Random();
int x = generator.nextInt(100);
return x;
}
// ************************************************
public void onClick(View v) {
// TODO Auto-generated method stub
int numberEntered = -1;
try {
numberEntered = Integer.parseInt(et.getText().toString());
} catch (NumberFormatException nfe) {
Toast.makeText(et.getContext(), "That's not a number!",
Toast.LENGTH_LONG).show();
}
if (random == numberEntered) {
Toast.makeText(et.getContext(), "Great!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(et.getContext(), "Bad!", Toast.LENGTH_LONG).show();
}
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have 5 EditTexts in android. I would like to know if I could check if all 5 EditTexts are null. Is there any way to do this??
I did something like this once;
EditText usernameEditText = (EditText) findViewById(R.id.editUsername);
sUsername = usernameEditText.getText().toString();
if (sUsername.matches("")) {
Toast.makeText(this, "You did not enter a username", Toast.LENGTH_SHORT).show();
return;
}
private boolean isEmpty(EditText etText) {
if (etText.getText().toString().trim().length() > 0)
return false;
return true;
}
OR As Per audrius
private boolean isEmpty(EditText etText) {
return etText.getText().toString().trim().length() == 0;
}
If function return false means edittext is not empty and return true means edittext is empty...
For validating EditText use EditText#setError method for show error and for checking empty or null value use inbuilt android class TextUtils.isEmpty(strVar) which return true if strVar is null or zero length
EditText etUserName = (EditText) findViewById(R.id.txtUsername);
String strUserName = etUserName.getText().toString();
if(TextUtils.isEmpty(strUserName)) {
etUserName.setError("Your message");
return;
}
try this :
EditText txtUserName = (EditText) findViewById(R.id.txtUsername);
String strUserName = usernameEditText.getText().toString();
if (strUserName.trim().equals("")) {
Toast.makeText(this, "plz enter your name ", Toast.LENGTH_SHORT).show();
return;
}
or use the TextUtils class like this :
if(TextUtils.isEmpty(strUserName)) {
Toast.makeText(this, "plz enter your name ", Toast.LENGTH_SHORT).show();
return;
}
Way late to the party here, but I just have to add Android's own TextUtils.isEmpty(CharSequence str)
Returns true if the string is null or 0-length
So if you put your five EditTexts in a list, the full code would be:
for(EditText edit : editTextList){
if(TextUtils.isEmpty(edit.getText()){
// EditText was empty
// Do something fancy
}
}
Other answers are correct but do it in a short way like
if(editText.getText().toString().isEmpty()) {
// editText is empty
} else {
// editText is not empty
}
Try this
TextUtils.isEmpty(editText.getText());
You can use length() from EditText.
public boolean isEditTextEmpty(EditText mInput){
return mInput.length() == 0;
}
I usually do what SBJ proposes, but the other way around. I simply find it easier to understand my code by checking for positive results instead of double negatives.
You might be asking for how to check for empty EdiTexts, but what you really want to know is if it has any content and not that it is not empty.
Like so:
private boolean hasContent(EditText et) {
// Always assume false until proven otherwise
boolean bHasContent = false;
if (et.getText().toString().trim().length() > 0) {
// Got content
bHasContent = true;
}
return bHasContent;
}
As SBJ I prefer to return "has no content" (or false) as default to avoid exceptions because I borked my content-check. That way you will be absolutely certain that a true has been "approved" by your checks.
I also think the if calling it looks a bit cleaner as well:
if (hasContent(myEditText)) {
// Act upon content
} else {
// Got no content!
}
It is very much dependent on preference, but i find this easier to read. :)
Why not just disable the button if EditText is empty? IMHO This looks more professional:
final EditText txtFrecuencia = (EditText) findViewById(R.id.txtFrecuencia);
final ToggleButton toggle = (ToggleButton) findViewById(R.id.toggleStartStop);
txtFrecuencia.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
toggle.setEnabled(txtFrecuencia.length() > 0);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
});
I use this method, that uses trim() to avoid blank spaces :
EditText myEditText = (EditText) findViewById(R.id.editUsername);
if ("".equals(myEditText.getText().toString().trim()) {
Toast.makeText(this, "You did not enter a value!", Toast.LENGTH_LONG).show();
return;
}
an example if you have several EditText´s
if (("".equals(edtUser.getText().toString().trim()) || "".equals(edtPassword.getText().toString().trim()))){
Toast.makeText(this, "a value is missing!", Toast.LENGTH_LONG).show();
return;
}
if(TextUtils.isEmpty(textA.getText())){
showToast(it's Null");
}
you can use TextUtils.isEmpty like my Example !
Good luck
with this short code you can delete empty space at start and end of the string. If the string is "" return the message "error" else you ave a string
EditText user = findViewById(R.id.user);
userString = user.getText().toString().trim();
if (userString.matches("")) {
Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show();
return;
}else{
Toast.makeText(this, "Ok", Toast.LENGTH_SHORT).show();
}
private boolean hasContent(EditText et) {
return (et.getText().toString().trim().length() > 0);
}
I used TextUtils for this:
if (TextUtils.isEmpty(UsernameInfo.getText())) {
validationError = true;
validationErrorMessage.append(getResources().getString(R.string.error_blank_username));
}
You can also check all the EditText Strings in one If condition: like this
if (mString.matches("") || fString.matches("") || gender==null || docString.matches("") || dString.matches("")) {
Toast.makeText(WriteActivity.this,"Data Incomplete", Toast.LENGTH_SHORT).show();
}
I wanted to do something similar. But getting the text value from edit text and comparing it like (str=="") wasn't working for me. So better option was:
EditText eText = (EditText) findViewById(R.id.etext);
if (etext.getText().length() == 0)
{//do what you want }
Worked like a charm.
Try this out with using If ELSE If conditions. You can validate your editText fields easily.
if(TextUtils.isEmpty(username)) {
userNameView.setError("User Name Is Essential");
return;
} else if(TextUtils.isEmpty(phone)) {
phoneView.setError("Please Enter Your Phone Number");
return;
}
You could call this function for each of the edit texts:
public boolean isEmpty(EditText editText) {
boolean isEmptyResult = false;
if (editText.getText().length() == 0) {
isEmptyResult = true;
}
return isEmptyResult;
}
EditText txtUserID = (EditText) findViewById(R.id.txtUserID);
String UserID = txtUserID.getText().toString();
if (UserID.equals(""))
{
Log.d("value","null");
}
You will see the message in LogCat....
"check out this i m sure you will like it."
log_in.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
username=user_name.getText().toString();
password=pass_word.getText().toString();
if(username.equals(""))
{
user_name.setError("Enter username");
}
else if(password.equals(""))
{
pass_word.setError("Enter your password");
}
else
{
Intent intent=new Intent(MainActivity.this,Scan_QRActivity.class);
startActivity(intent);
}
}
});
use TextUtils.isEmpty("Text here"); for single line code
The following works for me all in one statement:
if(searchText.getText().toString().equals(""))
Log.d("MY_LOG", "Empty");
First I retrieve a text from the EditText and then convert it to a string and finally comparing it with "" using .equals method.
This function work for me
private void checkForm() {
EditText[] allFields = {
field1_txt,
field2_txt,
field3_txt,
field4_txt
};
List < EditText > ErrorFields = new ArrayList < EditText > ();
for (EditText edit: allFields) {
if (TextUtils.isEmpty(edit.getText())) {
// EditText was empty
ErrorFields.add(edit); //add empty Edittext only in this ArayList
for (int i = 0; i < ErrorFields.size(); i++) {
EditText currentField = ErrorFields.get(i);
currentField.setError("this field required");
currentField.requestFocus();
}
}
}
}
EditText edt=(EditText)findViewById(R.id.Edt);
String data=edt.getText().toString();
if(data=="" || data==null){
Log.e("edit text is null?","yes");
}
else {
Log.e("edit text is null?","no");
}
do like this for all five edit text
You can use setOnFocusChangeListener , it will check when focus change
txt_membername.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View arg0, boolean arg1) {
if (arg1) {
//do something
} else {
if (txt_membername.getText().toString().length() == 0) {
txt_membername
.setError("Member name is not empty, Plz!");
}
}
}
});
if ( (usernameEditText.getText()+"").equals("") ) {
// Really just another way
}
I prefer using ButterKnife list binding and then applying actions on the list. For example, with the case of EditTexts, I have the following custom actions defined in a utility class (in this case ButterKnifeActions)
public static <V extends View> boolean checkAll(List<V> views, ButterKnifeActions.Check<V> checker) {
boolean hasProperty = true;
for (int i = 0; i < views.size(); i++) {
hasProperty = checker.checkViewProperty(views.get(i), i) && hasProperty;
}
return hasProperty;
}
public static <V extends View> boolean checkAny(List<V> views, ButterKnifeActions.Check<V> checker) {
boolean hasProperty = false;
for (int i = 0; i < views.size(); i++) {
hasProperty = checker.checkViewProperty(views.get(i), i) || hasProperty;
}
return hasProperty;
}
public interface Check<V extends View> {
boolean checkViewProperty(V view, int index);
}
public static final ButterKnifeActions.Check<EditText> EMPTY = new Check<EditText>() {
#Override
public boolean checkViewProperty(EditText view, int index) {
return TextUtils.isEmpty(view.getText());
}
};
And in the view code, I bind the EditTexts to a list and apply the actions when I need to check the views.
#Bind({R.id.edit1, R.id.edit2, R.id.edit3, R.id.edit4, R.id.edit5}) List<EditView> edits;
...
if (ButterKnifeActions.checkAny(edits, ButterKnifeActions.EMPTY)) {
Toast.makeText(getContext(), "Please fill in all fields", Toast.LENGTH_SHORT).show();
}
And of course this pattern is extendable to checking any property on any number of views. The only downside, if you can call it that, is the redundancy of views. Meaning, to use those EditTexts, you would have to bind them to single variables as well so that you can reference them by name or you would have to reference them by position in the list (edits.get(0), etc.). Personally, I just bind each of them twice, once to a single variable and once to a the list and use whichever is appropriate.
To editText is empty try another this simple way :
String star = editText.getText().toString();
if (star.equalsIgnoreCase("")) {
Toast.makeText(getApplicationContext(), "Please Set start no", Toast.LENGTH_LONG).show();
}
Try this out:
its in Kotlin
//button from xml
button.setOnClickListener{
val new=addText.text.toString()//addText is an EditText
if(new=isNotEmpty())
{
//do something
}
else{
new.setError("Enter some msg")
//or
Toast.makeText(applicationContext, "Enter some message ", Toast.LENGTH_SHORT).show()
}
}
Thank you