I would like to check if a filled in textfield is greater than an other filled in textfield.
So like:
if (textfield1.getText().toString().equals(""))
Toast.makeText(getActivity(), "textfield one is empty, please fill in a number", Toast.LENGTH_SHORT).show();
i would like something like this:
if (textfield1.getText().toString().less than textfield2.getText().toString())
Toast.makeText(getActivity(), "textfield one is less than textfield two, this is not allowed", Toast.LENGTH_SHORT).show();
i can't find how
I assume there are numbers in your TextViews? Make an Integer from the String and compare those numbers:
Integer input1 = Integer.parseInt(textfield1.getText().toString());
Integer input2 = Integer.parseInt(textfield2.getText().toString());
if (input1 < input2) { }
If it is input length you are talking about use String.length() like so:
if (textfield1.getText().toString().length() < textfield2.getText().toString().length()) {
}
try this
if(textfield1.getText().toString().trim().length() > 0 && textfield2.getText().toString().trim().length() > 0) {
try {
int i1 = Integer.parseInt(textfield1.getText().toString().trim());
int i2 = Integer.parseInt(textfield2.getText().toString().trim());
if(i1 > i2) {
// do needfull here
}
} catch(Exception ex) {
Log.e("tag", ex.getMessage());
// user entered some character which is not number
}
}
Related
This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 1 year ago.
Hello I am making an app where user can order some books. When he, or she, fill out the order with his firs second name etc and hits order button applications,using Intent, will switch to SMS and thus will purchase books via text message.But i wish to be able, if user accidently forget to fill up all fields, toast pop up with message "Please fill up XYZ field". I used if else, but when some field remain empty something else happened.I got android message that my app needs to be closed and and return me to the previous activity.In my LogCat nothing happened . No error message.
this is my code :
public void kreiranjeNarudzbine(View v) {
EditText editTextIme = (EditText) findViewById(R.id.ime);
String imeNarucioca = editTextIme.getText().toString();
EditText editTextPrezime = (EditText)findViewById(R.id.prezime);
String prezimeNarucioca = editTextPrezime.getText().toString();
EditText editTelefonNarucioca = (EditText)findViewById(R.id.telefon);
String telefonNarucioca = editTelefonNarucioca.getText().toString();
EditText editAdresaNarucioca = (EditText)findViewById(R.id.adresa);
String adresaNarucioca = editAdresaNarucioca.getText().toString();
EditText editGradNarucioca = (EditText)findViewById(R.id.grad);
String gradNarucioca = editGradNarucioca.getText().toString();
EditText editKolicina = (EditText)findViewById(R.id.kolicina);
String narucenaKolicina = editKolicina.getText().toString();
int kolicina = Integer.parseInt(narucenaKolicina);
int cenaNarudzbine = cena(kolicina);
String poruka = sumiranjeNarudzbine(imeNarucioca, prezimeNarucioca,telefonNarucioca,adresaNarucioca,gradNarucioca,cenaNarudzbine);
Intent smsIntent = new Intent(Intent.ACTION_VIEW);
smsIntent.setType("vnd.android-dir/mms-sms");
smsIntent.putExtra("address", "+381629647169");
smsIntent.putExtra("sms_body",poruka);
if(imeNarucioca.equals("")){
Toast.makeText(Narudzbina.this, "Unesite ime", Toast.LENGTH_LONG).show();
}
else if(prezimeNarucioca.equals("")){
Toast.makeText(Narudzbina.this,"Unesite Prezime", Toast.LENGTH_LONG).show();
}
else if(telefonNarucioca.equals("")){
Toast.makeText(Narudzbina.this,"Unesite kontakt telefon", Toast.LENGTH_LONG).show();
}
else if(adresaNarucioca.equals("")){
Toast.makeText(Narudzbina.this,"Unesite adresu",Toast.LENGTH_LONG).show();
}
else if(gradNarucioca.equals("")){
Toast.makeText(Narudzbina.this, "Navedite grad", Toast.LENGTH_LONG).show();
}
else if(narucenaKolicina.equals("")){
Toast.makeText(Narudzbina.this, "Navedite zeljenu kolicinu", Toast.LENGTH_LONG).show();
}
else{
startActivity(smsIntent);}
}
As already mentioned, you check to make sure it isn't null or empty.
if(imeNarucioca!=null && imeNarucioca.equals("")){
Toast.makeText(Narudzbina.this, "Unesite ime", Toast.LENGTH_LONG).show();
}
else if(prezimeNarucioca!=null && prezimeNarucioca.equals("")){
Toast.makeText(Narudzbina.this,"Unesite Prezime", Toast.LENGTH_LONG).show();
}
else if(telefonNarucioca!=null && telefonNarucioca.equals("")){
Toast.makeText(Narudzbina.this,"Unesite kontakt telefon", Toast.LENGTH_LONG).show();
}
else if(adresaNarucioca!=null && adresaNarucioca.equals("")){
Toast.makeText(Narudzbina.this,"Unesite adresu",Toast.LENGTH_LONG).show();
}
else if(gradNarucioca!=null && gradNarucioca.equals("")){
Toast.makeText(Narudzbina.this, "Navedite grad", Toast.LENGTH_LONG).show();
}
else if(narucenaKolicina!=null && narucenaKolicina.equals("")){
Toast.makeText(Narudzbina.this, "Navedite zeljenu kolicinu", Toast.LENGTH_LONG).show();
}
else{
startActivity(smsIntent);
}
This can be converted into a method to prevent as much text:
public boolean isETEmpty(EditText et){
return (et != null && (et.equals("") || et.equals(" ")));//the final piece checks if the edittext is empty or just contains a space. It is or between
//in order to ensure that one of those are true. Thus the parenthesis
}
(how the above works)
Now, for the required fields you can use HTML to format the text:
/*your view*/.setText(Html.fromHtml("Your title. <font color='red'>*</font>"));
The above code formats the code by adding a red star after the required fields. Later down you can do this:
/*your view*/.setText(Html.fromHtml("<font color='red'>*</font> Required field"));
The comment /*your view*/ you replace with a textview reference, edittext or whatever you use to set text
Further reading:
https://stackoverflow.com/a/9161958/6296561
The string of empty edittext might be null, which causes the issue. Try the following code.
if(imeNarucioca==null || imeNarucioca.equals("")){
Toast.makeText(Narudzbina.this, "Unesite ime", Toast.LENGTH_LONG).show();
}
else if(prezimeNarucioca==null || prezimeNarucioca.equals("")){
Toast.makeText(Narudzbina.this,"Unesite Prezime", Toast.LENGTH_LONG).show();
}
else if(telefonNarucioca==null || telefonNarucioca.equals("")){
Toast.makeText(Narudzbina.this,"Unesite kontakt telefon", Toast.LENGTH_LONG).show();
}
else if(adresaNarucioca==null || adresaNarucioca.equals("")){
Toast.makeText(Narudzbina.this,"Unesite adresu",Toast.LENGTH_LONG).show();
}
else if(gradNarucioca==null || gradNarucioca.equals("")){
Toast.makeText(Narudzbina.this, "Navedite grad", Toast.LENGTH_LONG).show();
}
else if(narucenaKolicina==null || narucenaKolicina.equals("")){
Toast.makeText(Narudzbina.this, "Navedite zeljenu kolicinu", Toast.LENGTH_LONG).show();
}
else{
startActivity(smsIntent);}
}
You should use isEmpty method provided in android.text.TextUtils. The whole description and implement of this method:
/**
* Returns true if the string is null or 0-length.
* #param str the string to be examined
* #return true if str is null or zero length
*/
public static boolean isEmpty(#Nullable CharSequence str) {
if (str == null || str.length() == 0)
return true;
else
return false;
}
So, to validate null or empty user input, you can do something like this:
if(android.text.TextUtils.isEmpty(imeNarucioca)){
// ...
}
So i'm using this, you can do with it what you like:
This is the method:
public static boolean checkEditTextIsEmpty(EditText... editTexts)
{
try
{
for (EditText editText : editTexts)
{
if (editText.getText().toString().trim().length() == 0)
{
Drawable d = _application.currentActivity.getResources().getDrawable(android.R.drawable.ic_dialog_alert);
d.setBounds(0, 0, d.getIntrinsicWidth()/2, d.getIntrinsicHeight()/2);
editText.requestFocus();
editText.setError(editText.getHint() + " is empty", d);
return false;
}
}
}
catch (Exception ignored)
{
return false;
}
return true;
}
This is a preview: (ignore my style and background)
This is how i implemented it:
if(checkEditTextIsEmpty(txtEmail, txtPassword))
{
//Do whatever if EditTexts is not empty
}
Just add this line in your Java file pro-grammatically,
adding mandatory field near Your Text view.
tv.setText (Html.fromHtml(YourText
+ " <font color='"
+ getResources().getColor(R.color.colorAccent) + "'>" + " * "
+ "</font>"));
add Required field instead of yourText field,
then use the required color from colors.xml
I tried to increase++ a number (i) each time the distance between the camera and my face is between 40 cm and 80 cm. Unfortunately when it happen the textview shows (The number of occurrence is: 50). Help me please
public void update(final Messsage msg) {
for(int i = 0; i < 50; ++i) {
if (msg.getDistanceToFace() > 40 && msg.getDistanceToFace() < 80) {
textView.setText("The number of occurrence is: " + i);
textView.setTextColor(Color.GREEN);
}
}
}
you should probably add a break after you set the text, the way you coded it will set a text for all the iteration of i but you will only see the last one (50)
If you only want to increase the number when the face is a certain length away, shouldn't you do something more on the lines of this?
public void update(final Messsage msg) {
int i = 0;
if (msg.getDistanceToFace() > 40 && msg.getDistanceToFace() < 80) {
i++;
textView.setText("The number of occurrence is: " + i);
textView.setTextColor(Color.GREEN);
}
}
Maybe you'll need to have that i a global variable or an argument to the function, not sure without having more of the code.
If you don't want the i to increase really fast (because it increments each time the update function is called and the phone is close to the face), a simple code to do that would be something like
public void update(final Messsage msg) {
boolean isCloseToFace = false;
int i = 0;
if (msg.getDistanceToFace() > 40 && msg.getDistanceToFace() < 80) {
if (!isCloseToFace) {
i++;
isCloseToFace = true;
}
textView.setText("The number of occurrence is: " + i);
textView.setTextColor(Color.GREEN);
} else {
isCloseToFace = false;
}
}
I have three EditText controls and I need to make sure that each is the correct number input.
The first has to be a number between 0 and 23
The second has to be a number between 0 and 59
And the third has to be a number between 0 and 1500
I saw someone make a post about an easy EditText validation using setError, example:
EditText firstName = (EditText)findViewById(R.id.first_name);
if (firstName.getText().toString().length() == 0)
firstName.setError("First name is required!");
So is there an easy way to do it like above, but making sure a number isn't > 23, 59, or 1500 (individually)?
EditText firstEditText = (EditText)findViewById(R.id.first_edit_text);
EditText secondEditText = (EditText)findViewById(R.id.second_edit_text);
EditText thirdEditText= (EditText)findViewById(R.id.third_edit_text);
int value;
value = Integer.parseInt(firstEditText .getText().toString());
if (! value > 0 && value < 23)
firstEditText.setError("Error");
value = Integer.parseInt(secondEditText .getText().toString());
if (! value > 0 && value < 59)
secondEditText.setError("Error");
value = Integer.parseInt(thirdEditText.getText().toString());
if (! value > 0 && value < 1500)
thirdEditText.setError("Error");
Integer.parseInt(String s)can convert string to integer.Then, you validate it with if, else.
However, the input may not be an integer, and you have to set android:numeric="integer" in <EditText /> tag in the .xml file.
Be careful about this, if the input string is not integer, Integer.parseInt() will throw an exception, which will cause a crash.
You want to make sure you're performing some error checking since the value is coming from the user. Try something like this:
EditText firstText = (EditText) findViewById(R.id.first);
try
{
long firstVal = Long.parseLong(firstText.getText());
if (firstVal < 0 || firstVal > 23)
firstText.setError("The value must be between 0 and 23!");
}
catch (NumberFormatException e)
{
firstText.setError("Enter an integer value!");
}
// very similar for your remaining cases
String value = firstName.getText().toString();
int int_value = Integer.parseInt(value);
if (firstName.getText().toString().length() != 0)
if (int_value < 1500) {
// do what you want
}
else if (int_value < 59) {
// do what you want
}
else if (int_value < 23) {
// do what you want
}
}else {
firstName.setError("First name is required!");
}
I have a hangman-app which I fetch a random word from Db i created, then I save it to randomedWord and then i make another String for holding randomedWord but replaced with only "_". This hiddenWord is displayed so the user knows how many chars there is.
When a user hits Enter a onlicklistener fires guess() method:
I have following code which initates a local String which has the value of a TextView(userInput). Then if randomedWord contains the guess I want to put in guess into the same position as it is in the randomedWord, but now to hiddenWord and then update the TextView again.
Guess method:
public void guess()
{
String guess = userInput.getText().toString();
if(randomedWord.contains(guess))
{
hiddenWord = hiddenWord.replaceAll(guess, guess);
this.wordHolder.setText(hiddenWord);
} else
{
showImages();
}
}
The problem I think is this line:
hiddenWord = hiddenWord.replaceAll(guess, guess);
because hiddenWord just contains "_" and therefore I can't replace with (guess, guess) where the first is WHAT to be replaced and last is WITHWHAT.
How do I replace the same POSITION as it is in randomedWord with guess into hiddenWord?
I would change your approach slightly. When a user inputs and guess() is called, find all occurences of that guess in randomedWord and then set the characters in hiddenWord to guess. Using StringBuilder and String.indexOf(), it would look something like this. Also, guess will need to be a char:
StringBuilder builder = new StringBuilder(hiddenWord);
int index = word.indexOf(guess);
while (index >= 0) {
builder.setCharAt(index, guess);
index = word.indexOf(guess, index + 1);
}
hiddenWord = builder.toString();
My solution to the problem looks like this:
// INVWORD METHOD WHICH TURNS THE FETCHED WORD INTO A COPY BUT ONLY "_"
public void invWord()
{
hiddenWord = randomedWord;
hiddenWord = hiddenWord.replaceAll(".", "_");
}
// GUESS METHOD WHICH IS CALLED WHEN ENTER-BUTTON ISCLICKED
public void guess() throws IndexOutOfBoundsException
{
char guess = userInput.getText().charAt(0);
StringBuilder builder = new StringBuilder(hiddenWord);
String j = ""+guess;
int index = randomedWord.indexOf(guess);
if (randomedWord.contains(j))
{
while (index >= 0)
{
builder.setCharAt(index, guess);
index = randomedWord.indexOf(guess, index + 1);
hiddenWord = builder.toString().trim();
wordHolder.setText(hiddenWord);
if (hiddenWord.trim().contains(randomedWord))
{
winner();
}
}
}
else
{
showImages();
}
}
Problem is that I would need to add a +" " to the hiddenWord = hiddenWord.replaceAll(".", "_"); to make the word be like _ _ _ _ _ and makes the user see how many ketters the word is. In my solution it will only be long ____, but it works. If I set index*2 at builder.setCharAt(index, guess); the formatting will be good but then winner(); is never run, I guess because the " " makes the hiddenWord no longer = ranomedWord.
How can I solve this?
Got it all solved! The feeling when everything works smoothly.... :)
Heres the code:
// Set listener to enter-button and do guess when textfield is not empty and toast that input need if it is
enterLetterButton.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
if (!(userInput.getText().toString().isEmpty()) )
{
guess();
} else if (userInput.getText().toString().isEmpty())
{
Toast toast = Toast.makeText(getApplicationContext(), "You need to insert a letter", Toast.LENGTH_SHORT);
toast.show();
}
}
});
// invWord() method. Converts the randomedWord to a string of "_".
public void invWord()
{
hiddenWord = randomedWord;
hiddenWord = hiddenWord.replaceAll(".", "_" +" ");
}
//guess() method. Puts the guess(char) at the index fetched and if the hiddenWord contains no more "_" winner() is called
public void guess() throws IndexOutOfBoundsException
{
char guess = userInput.getText().charAt(0);
StringBuilder builder = new StringBuilder(hiddenWord);
String j = ""+guess;
int index = randomedWord.indexOf(guess);
if (randomedWord.contains(j))
{
while (index >= 0)
{
builder.setCharAt(index*2, guess);
index = randomedWord.indexOf(guess, index + 1);
hiddenWord = builder.toString().trim();
wordHolder.setText(hiddenWord);
if (!(hiddenWord.toString().contains("_".toString())) )
{
winner();
}
}
}
else
{
showImages();
}
}
I've decided I have to write my own syntax highlighter. So far it's working but it's realtime (you type, it highlights) and it's slow.
I'll try to explain how it works. Each time the user types something into the EditText it runs the highlighter (via TextWatcher). The highlighter searches through the text until it finds the beginning of a word and then searches until it finds the end of the same word. Once it finds a word it searches through an array of keywords, if it finds a match it sets a spannable at that location. It keeps looping until it reaches the end of the document.
Again, it works so far (just trying out this idea before I continue with this method), but it's so slow. Some times it can take over a second just to go through a few lines. It slows down how fast the text appears in the EditText. - I also set where the highlighter starts after text is entered at the last position where the user typed so it doesnt have to go through the whole doc each time, it helps a little but not much.
Here's the basic of my EditText:
public class CodeView extends EditText {
private int mTxtChangeStart;
String mStructures[] = this.getResources().getStringArray(R.array.structures);
public CodeView(Context context, AttributeSet attrs) {
super(context, attrs);
addTextChangedListener(inputTextWatcher);
...
}
TextWatcher inputTextWatcher = new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
syntaxHighlight();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
//Set where we should start highlighting
mTxtChangeStart = start;
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
};
private void syntaxHighlight() {
//Time how long it takes for debugging
long syntime = System.currentTimeMillis();
Log.d("", "Start Syntax Highlight");
//Get the position where to start searching for words
int strt = mTxtChangeStart;
//Get the editable text
Editable txt = getText();
//Back up the starting position to the nearest space
try {
for(;;) {
if(strt <= 0) break;
char c = txt.charAt(strt);
if(c != ' ' && c != '\t' && c != '\n' && c != '\r') {
strt--;
} else {
break;
}
}
} catch (IndexOutOfBoundsException e) {
Log.e("", "Find start position failed: " + e.getMessage());
}
//Just seeing how long this part took
long findStartPosTime = System.currentTimeMillis();
Log.d("", "Find starting position took " + String.valueOf(System.currentTimeMillis() - findStartPosTime) + " milliseconds");
//the 'end of a word' position
int fin = strt;
//Get the total length of the search text
int totalLength = txt.length();
//Start finding words
//This loop is to find the first character of a word
//It loops until the current character isnt a space, tab, linebreak etc.
while(fin < totalLength && strt < totalLength) {
for(;;) {
//Not sure why I added these two lines - not needed here
//fin++;
//if(fin >= totalLength) { break; } //We're at the end of the document
//Check if there is a space at the first character.
try {
for(;;) { //Loop until we find a useable character
char c = txt.charAt(strt);
if (c == ' ' || c == '\t' || c == '\n' || c == '\r'){
strt++; //Go to the next character if there is a space
} else {
break; //Found a character (not a space, tab or linebreak) - break the loop
}
}
}catch(IndexOutOfBoundsException e) {
Log.e("", e.getMessage());
break;
}
//Make sure fin isnt less than strt
if(strt > fin) { fin = strt; }
//Now we search for the end of the word
//Loop until we find a space at the end of a word
try {
for(;;) {
char c = txt.charAt(fin);
if(c != ' ' && c != '\t' && c != '\n' && c != '\r') {
fin++; //Didn't find whitespace here, keep looking
} else {
break; //Now we found whitespace, end of a word
}
}
break;
} catch (IndexOutOfBoundsException e) {
//If this happens it should mean it just reached the end of the document.
Log.e("", "End of doc? : " + e.getMessage());
break;
}
}
Log.d("", "It took " + String.valueOf(System.currentTimeMillis() - findStartPosTime) + " milliseconds to find a word");
//Make sure fin isnt less that start, again
if(strt > fin) { fin = strt; }
//Debug time, how long it took to find a word
long matchTime = System.currentTimeMillis();
//Found a word, see if it matches a word in our string[]
try {
for(String mStruct : mStructures) {
if(String.valueOf(txt.subSequence(strt, fin)).equals(mStruct)) {
//highlight
Spannable s = (Spannable) txt;
s.setSpan(new ForegroundColorSpan(Color.RED), strt, fin, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//Can someone explain why this is still setting the spannable to the main editable???
//It should be set to txt right???
break;
} else {
/*Spannable s = (Spannable) txt;
s.setSpan(new ForegroundColorSpan(Color.BLACK), strt, fin, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
txt.removeSpan(s);*/
}
}
}catch (IndexOutOfBoundsException e) {
e.printStackTrace();
Log.e("", "word match error: " + e.getMessage());
}
//Finally set strt to fin and start again!
strt = fin;
Log.d("", "match a word time " + String.valueOf(System.currentTimeMillis() - matchTime) + " milliseconds");
}//end main while loop
Log.d("", "Syntax Highlight Finished in " + (System.currentTimeMillis() - syntime) + " milliseconds");
mTextChanged = false;
}
}
"structures" resource (php.xml)
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="structures">
<item>if</item>
<item>else</item>
<item>else if</item>
<item>while</item>
<item>do-while</item>
<item>for</item>
<item>foreach</item>
<item>break</item>
<item>continue</item>
<item>switch</item>
<item>declare</item>
<item>return</item>
<item>require</item>
<item>include</item>
<item>require_once</item>
<item>include_once</item>
<item>goto</item>
</string-array>
</resources>
Anyone have any suggestions how to make this search faster? I know I have a lot of loops but I'm not sure how else to do it.
Thanks a lot!
Can you split the string on the delimiters you have there rather than looking at each character? That would speed it up some. (String.split())