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
Related
I want to use if statement in android studio but without using setText
dayText.setText(forecast.getDay());
if (forecast.getDay().equals("Mon")){
dayText.setText("السبت");
}else if (forecast.getDay().equals("Tue")){
dayText.setText("الاحد");
}else if (forecast.getDay().equals("Wed")){
dayText.setText("الاثنين");
}else if (forecast.getDay().equals("Thu")){
dayText.setText("الثلاثاء");
}else if (forecast.getDay().equals("Fri")){
dayText.setText("الاربعاء");
}else if (forecast.getDay().equals("Sat")){
dayText.setText("الخميس");
}else if (forecast.getDay().equals("Sun")){
dayText.setText("الجمعة");
}
if there is any example
I can't get what you are looking to do but first initialize the String as public String getDay; after you can check the if statement like, if you add more code maybe i can help you more.
if(getDay.equals("Mon")) {
/** do something **/
}
getDay = day;
Is this what you want
public String getDay() {
if (getDay().equals("Mon")){
Log.e("Success","Mon");
}
return;
}
If I understood, what you want is not to have so many setTexts? This will work for that purpose.
String finalText = "";
if (forecast.getDay().equals("Mon")){
finalText = "السبت";
}else if (forecast.getDay().equals("Tue")){
finalText = "الاحد";
}else if (forecast.getDay().equals("Wed")){
finalText = "الاثنين";
}else if (forecast.getDay().equals("Thu")){
finalText = "الثلاثاء";
}else if (forecast.getDay().equals("Fri")){
finalText = "الاربعاء";
}else if (forecast.getDay().equals("Sat")){
finalText = "الخميس";
}else if (forecast.getDay().equals("Sun")){
finalText = "الجمعة";
}
dayText.setText(finalText);
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
}
}
Have a problem with this code!
I want to check the editText values, if it is null or not...
But it gets stuck at the if segment, doesnt mather if it is a value in the editText or not.
If there is a value in the editText string it should go further and calculate the values.
Second problem I have is the toast, it doesnt show the text in the string variable, it just prints the string link.
private EditText fp;
private EditText fC;
private EditText drive;
private TextView totalcost;
public void CalcButton(View button) {
// Converting strings to float and check if each is NULL (empty)
if (!(fp.getText().equals(null)) || (fC.getText().equals(null)) || (drive.getText().equals(null)))
{
Toast.makeText(getApplicationContext(), "#string/toast", Toast.LENGTH_LONG).show();
}else {
String n1 = fp.getText().toString();
float no1 = Float.parseFloat(n1);
String n2 = fC.getText().toString();
float no2 = Float.parseFloat(n2);
String n3 = drive.getText().toString();
float no3 = Float.parseFloat(n3);
// Calculates the floats
float calc = no1 * no2 * no3;
// Converting and prints out the result
String sum = Float.toString(calc);
totalcost.setText(sum);
}
You should not do it this way, do this instead:
if (!fp.getText().toString().equals("")) {
}
To problem with Toast - use this:
Toast.makeText(getApplicationContext(), R.string.toast, Toast.LENGTH_LONG).show();
Try to use TextUtils.isEmpty() instead, it checks for null and 0-length String.
On your if statement it should look like:
if (!TextUtils.isEmpty(fp.getText().toString())) {
// Code
}
And on your Toast, change "#string/toast" to R.string.toast or getApplicationContext().getString(R.string.toast);
The code should look like:
// Converting strings to float and check if each is NULL (empty)
if (! (TextUtils.isEmpty(fp.getText().toString()) ||
(TextUtils.isEmpty(fC.getText().toString())) ||
(TextUtils.isEmpty(drive.getText().toString()))))
{
Toast.makeText(getApplicationContext(), getApplicationContext().getString(R.string.toast), Toast.LENGTH_LONG).show();
}
More on the getString() method here.
EDIT: I've seen that your code also was missing a pair of parenthesis ( ). So your "not" was only applying to the first test.
Something like:
!(test1) || test2 || test3
Instead of
!((test1) || (test2) || (test3))
To check if EditText is empty you do editText.getText().toString().equals("")
So, Your if-statement will look like this:
if (!(fp.getText().toString().equals("")) ||
(fC.getText().toString().equals("")) ||
(drive.getText().toString().equals("")))
And your Toast would be like this:
Toast.makeText(getApplicationContext(), R.string.toast, Toast.LENGTH_LONG).show();
function isNull(int resourceId, boolean getError){
EditText editText= (EditText) findViewById(resourceId);
String strEditText = String.valueOf(editText.getText());
if(TextUtils.isEmpty(strEditText)) {
if(getError) editText.setError("this is null!");
return true;
}else{
return false;
}
}
May be this block gives you a few clues about yours
about If Conditions;
In your 'IF conditions', parentheses seems less than the count it is necessary.
Try to add one more after (!)
I guess it should be like this;
for Negative
if (!(
(String.valueOf(fp.getText()).equals("")) ||
(String.valueOf(fC.getText()).equals("")) ||
(String.valueOf(drive.getText()).equals(""))
))
for Positive
if (
(String.valueOf(fp.getText()).equals("")) ||
(String.valueOf(fC.getText()).equals("")) ||
(String.valueOf(drive.getText()).equals(""))
)
I have an EditText in android for users to input their AGE. It is set an inputType=phone.
I would like to know if there is a way to check if this EditText is null.
I've already looked at this question: Check if EditText is empty. but it does not address the case where inputType=phone.
These, I've checked already and do not work:
(EditText) findViewByID(R.id.age)).getText().toString() == null
(EditText) findViewByID(R.id.age)).getText().toString() == ""
(EditText) findViewByID(R.id.age)).getText().toString().matches("")
(EditText) findViewByID(R.id.age)).getText().toString().equals("")
(EditText) findViewByID(R.id.age)).getText().toString().equals(null)
(EditText) findViewByID(R.id.age)).getText().toString().trim().length() == 0
(EditText) findViewByID(R.id.age)).getText().toString().trim().equals("")
and isEmpty do not check for blank space.
Thank you for your help.
You can check using the TextUtils class like
TextUtils.isEmpty(ed_text);
or you can check like this:
EditText ed = (EditText) findViewById(R.id.age);
String ed_text = ed.getText().toString().trim();
if(ed_text.isEmpty() || ed_text.length() == 0 || ed_text.equals("") || ed_text == null)
{
//EditText is empty
}
else
{
//EditText is not empty
}
First Method
Use TextUtil library
if(TextUtils.isEmpty(editText.getText().toString())
{
Toast.makeText(this, "plz enter your name ", Toast.LENGTH_SHORT).show();
return;
}
Second Method
private boolean isEmpty(EditText etText)
{
return etText.getText().toString().trim().length() == 0;
}
Add Kotlin getter functions
val EditText.empty get() = text.isEmpty() // it == ""
// and/or
val EditText.blank get() = text.isBlank() // it.trim() == ""
With these, you can just use if (edittext.empty) ... or if (edittext.blank) ...
If you don't want to extend this functionality, the original Kotlin is:
edittext.text.isBlank()
// or
edittext.text.isEmpty()
EditText textAge;
textAge = (EditText)findViewByID(R.id.age);
if (TextUtils.isEmpty(textAge))
{
Toast.makeText(this, "Age Edit text is Empty", Toast.LENGTH_SHORT).show();
//or type here the code you want
}
I use this method for same works:
public boolean checkIsNull(EditText... editTexts){
for (EditText editText: editTexts){
if(editText.getText().length() == 0){
return true;
}
}
return false;
}
Simply do the following
String s = (EditText) findViewByID(R.id.age)).getText().toString();
TextUtils.isEmpty(s);
I found that these tests fail if a user enters a space so I test for a missing hint for empty value
EditText username = (EditText) findViewById(R.id.editTextUserName);
EditText password = (EditText) findViewById(R.id.editTextPassword);
// these hint strings reflect the hints attached to the resources
if (username.getHint().equals("Enter your username") || password.getHint().equals("Enter Your Password")){
// enter your code here
} else {
// alls well
}
editText.length() usually works for me
try this one
if((EditText) findViewByID(R.id.age)).length()==0){
//do whatever when the field is null`
}
Java: Check if EditText is Empty
1) find the EditText
ourEditText = view.findViewById(R.id.edit_text);
2) Get String value of EditText
String ourEditTextString = ourEditText.getText().toString();
3) Remove all spaces
Incase user inputs only blank spaces.
String ourEditTextNoSpaces = ourEditTextString.replaceAll(" ","");
3) Check if empty
boolean isOurEditTextEmpty = ourEditTextNoSpaces.isEmpty();
Try this. This is the only solution I got
String phone;
try{
phone=(EditText) findViewByID(R.id.age)).getText().toString();
}
catch(NumberFormatException e){
Toast.makeText(MainActivity.this, "plz enterphone Number ", Toast.LENGTH_SHORT).show();
return;
}
public boolean saveTheUpdate(int position)
{
System.out.println("In update Save Method");
String strOut=objEditText.getText().toString();
if(strOut !=null && strOut.length() !=0 && arrlstCo_ordinate.size() !=0)
{
mapDefect.put(objEditText.getId(),strOut);
Log.d("Err", "Map Size :"+mapDefect.size() +"Arr List Size :"+arrlstCo_ordinate.size());
db.updateDefectDescription(arrlstCo_ordinate, mapDefect,position);
Toast.makeText(FragmentActivity.this, "Defect updated", Toast.LENGTH_SHORT).show();
count=1;
removeLocalView();
fechCoordinate();
addViewEditText();
return true;
}else
{
Toast.makeText(FragmentActivity.this, "Please log the defect before saving", Toast.LENGTH_SHORT).show();
return false;
}
}
So, I have an EditText open. The data inside this is stored in SortedMap - mapDefect. This is used later to insert in a database. However, at random times String strOut=objEditText.getText().toString(); is not working.
There are actually many EditTexts. It fetches information from the wrong EditText even though they have been invisible. The data is to be picked from the EditText that is currenytly visble. It works fine sometimes and sometimes it doesn't - It fetches form the correct EditText sometimes and sometimes not.
if(!strOut.equalsIgnoreCase("")&& strOut.length() !=0 && arrlstCo_ordinate.size() !=0)
{
}
replace with
if(strOut !=null && strOut.length() >0 && arrlstCo_ordinate.size() >0)
{
}