java.lang.NumberFormatException: Invalid int: “” error android - java

I am making an app where user must enter basic info about self.First name,second name, city and quantity that he or she wish to order.If he or she skip one field toast will pop up with message what field is skipped. And that is ok.That works, but if he skips quantity field I got error on my phone and it send user back on previously activity.When I inspect my LogCat I see error message
java.lang.NumberFormatException: Invalid int: “” error
Now I know why that message appears.Because it expected to find Integer,in if statment. but actually finds String. But do not know how to fix it.The last if/else statemen is an Issue:
Now what i tried so far:
1) Tried to set primitive int as object Integer
2)Tried to use kolicina==0;
3)Tried to use kolicina.equals(null) / kolicina.equals(0);
4)Tried to use .isEmty();
my code:
package com.dsk.android.decijisvetknjiga;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class Narudzbina extends AppCompatActivity {
String porukaGreska="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.narudzbina);
}
public boolean praznoPolje(EditText et){
return (et != null && (et.equals("") || et.equals(" ")));
}
public void kreiranjeNarudzbine(View v) {
EditText editTextIme = (EditText) findViewById(R.id.ime);
String imeNarucioca = editTextIme.getText().toString();
praznoPolje(editTextIme);
EditText editTextPrezime = (EditText) findViewById(R.id.prezime);
String prezimeNarucioca = editTextPrezime.getText().toString();
praznoPolje(editTextIme);
EditText editTelefonNarucioca = (EditText) findViewById(R.id.telefon);
String telefonNarucioca = editTelefonNarucioca.getText().toString();
praznoPolje(editTelefonNarucioca);
EditText editAdresaNarucioca = (EditText) findViewById(R.id.adresa);
String adresaNarucioca = editAdresaNarucioca.getText().toString();
praznoPolje(editAdresaNarucioca);
EditText editGradNarucioca = (EditText) findViewById(R.id.grad);
String gradNarucioca = editGradNarucioca.getText().toString();
praznoPolje(editGradNarucioca);
EditText editKolicina = (EditText) findViewById(R.id.kolicina);
String narucenaKolicina = editKolicina.getText().toString();
int kolicina = Integer.parseInt(narucenaKolicina);
praznoPolje(editKolicina);
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", "+1111111");
smsIntent.putExtra("sms_body", poruka);
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);
}
}
English is not my native language so do apologize for spelling mistakes or some lack of clarity in the matter, I'd be happy to explain it if necessary.

Your problem is on this line
int kolicina = Integer.parseInt(narucenaKolicina);
If the input is empty, it will try to parse an empty string "". You need to wrap this in an if statement to check if narucenaKolicina is empty or a valid int before you try to parse it.

Tip for you to ignore this exeception:
EditText editKolicina = (EditText) findViewById(R.id.kolicina);
String narucenaKolicina = editKolicina.getText().toString();
if(!narucenaKolicina.isEmpty())
int kolicina = Integer.parseInt(narucenaKolicina);
else
Toast.makeText(Narudzbina.this, "Don't leave this field empty", Toast.LENGTH_LONG).show();

You need to check if your string have empty text, not only null value or 0.
You have to do something like this
kolicina.equals("");

The exception is caused by the parseInt() method so change kolicina to integer is not useful
You should try something like this :
if (narucenaKolicina != null && !narucenaKolicina.toString().trim().equals(""))
As condition to avoid "" string.

Related

Unable to get method to access characters in a String

I am trying to make a Caesar Cipher app on Android Studio. I have the XML file and most of the other code ready but was unable to continue past the point in the code where I must access each element of the string. I have tried using the charAt() function.
Also I just want the character at the point in the array to increase by the number specified, I say this because I saw that after 'z' special characters like '|' appear and that is fine by me. This is my first app and could really use some help. The error is at line 47 and 61.
Here is my code:
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity
{
EditText input;
EditText output;
EditText num;
String inp;
String out;
int choice;
Character c;
Button enc, dec;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
input = (EditText) findViewById(R.id.input);
output= (EditText) findViewById(R.id.output);
num = (EditText) findViewById(R.id.num);
enc = (Button) findViewById(R.id.enc);
dec = (Button) findViewById(R.id.dec);
enc.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
inp=input.getText().toString();
choice= Integer.parseInt(num.getText().toString());
for(int i=0;i<input.length();i++)
{
inp.charAt(i)= (char) (inp.charAt(i)+choice);
}
}
});
dec.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v1)
{
inp=input.getText().toString();
choice= Integer.parseInt(num.getText().toString());
for(int i=0;i<input.length();i++)
{
inp.charAt(i)= (char) (inp.charAt(i)-choice);
}
}
});
}
}
Building on #corsiKa's answer, I suggest the following. First, convert your input string into a char[]:
char[] array = inp.toCharArray();
Now you can iterate over the array and modify its contents:
array[i] = array[i] + choice;
And, at the end, you can build your output string from that array:
output.setText(new String(array));
I believe your first problem is here:
inp.charAt(i)= (char) (inp.charAt(i)+choice);
You are trying to assign a value to a method return. This is not possible in Java.
Strings are immutable in Java - if you'd like to replace a value in a String, you must build a new String and resassign the reference that points to the old String to instead point to the new String.
There may be other issues that I have not had a chance to get to, but I believe this is the real issue. I don't fully understand what you're trying to do, so unfortunately I can't make a suggestion for what you should use instead.

I have two EditText entries, one for a name and the other for an age receive errors for TextUtils on the second

I have two EditText fields in an app. The first EditText is set up to accept strings, in my case a name:
EditText nameField = (EditText) findViewById(R.id.nameOfCustomer);
String name = nameField.getText().toString();
I have two EditText fields in an app. The first EditText is set up to accept strings, in my case a name:
EditText nameField = (EditText) findViewById(R.id.nameOfCustomer);
String name = nameField.getText().toString();
I then added the following java code for the first EditText to check for nulls:
if(TextUtils.isEmpty(name))
{
Toast.makeText(this, "Please Enter Name ",Toast.LENGTH_LONG).show();
return;
}
This works just fine and when the TextUtils.isEmpty is true it causes the toast to display if no entry is made in the first EditText field.
The second EditText has the input type set to android:inputType="number" since I want to have the user enter a number only
I have duplicated this same code for the second EditText:
EditText nameField2 = (EditText) findViewById(R.id.ageOfPatient);
String name2 = nameField2.getText().toString();
and I check it for nulls before I parse to an integer:
if(TextUtils.isEmpty(name2)){
Toast.makeText(this, "Please Enter Patient Age ",Toast.LENGTH_SHORT).show();
return;
}
int val = Integer.parseInt( nameField2.getText().toString() );
However, it does not identify a null condition and causes the application to crash. I could not find anything that works.
Any suggestions would be most apprecited !
I then added the following java code for the first EditText to check for nulls:
if(TextUtils.isEmpty(name)) {
Toast.makeText(this, "Please Enter Name ",Toast.LENGTH_LONG).show();
return;
}
This works just fine and when the TextUtils.isEmpty is true it causes the toast to display if no entry is made in the first EditText field.
The second EditText has the input type set to android:inputType="number" since I want to have the user enter a number only
I have duplicated this same code for the second EditText:
EditText nameField2 = (EditText) findViewById(R.id.ageOfPatient);
String name2 = nameField2.getText().toString();
and I check it for nulls before I parse to an integer:
if(TextUtils.isEmpty(name2)){
Toast.makeText(this, "Please Enter Patient Age ",Toast.LENGTH_SHORT).show();
return;
}
int val = Integer.parseInt( nameField2.getText().toString() );
However, it does not identify a null condition and causes the application to crash. I could not find anything that works. Any suggestions would be most apprecited !
I think you are looking for below code. If you will provide error log, it will be more clearer. Most likely you are submitting the form even after validation of the form is failed.
public class OPDForm extends AppCompatActivity implements View.OnClickListener {
private EditText nameOfCustomer;
private EditText ageOfPatient;
private Button addButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_opd_form);
nameOfCustomer = (EditText) findViewById(R.id.nameOfCustomer);
ageOfPatient = (EditText) findViewById(R.id.ageOfPatient);
addButton = (Button) findViewById(R.id.addButton);
addButton.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (view == addButton) {
addButton.requestFocus();
if(isValidForm()) {
//Submit Form Here
//Most likely you are invoking below line even after validation fails, but now we are it will be called only when your form validation will get success
int val = Integer.parseInt( ageOfPatient.getText().toString() );
}
}
}
private boolean isValidForm() {
if(TextUtils.isEmpty(nameOfCustomer.getText().toString())) {
Toast.makeText(this, "Please Enter Name ", Toast.LENGTH_LONG).show();
return false;
} else if(TextUtils.isEmpty(ageOfPatient.getText().toString())) {
Toast.makeText(this, "Please Enter Patient Age ", Toast.LENGTH_LONG).show();
return false;
}
return true;
}
}
I discovered that I had android:text for the second EditText instead of Android:hint so the null checker was seeing text instead of what I thought was the hint, duh. I stumbled across this when I deleted the text in test mode and found the code worked just fine, so I went back to compare the code on both EditText fields and sure enought, the second text had android:text instead of android:hint. Thanks to all who helped me out. As I stated, I am a novice, but quickly learning. Thanks again to all ! Tom

Pythagoras in android application

Hey guys I would really like to calculate not only the c=hypotenuse but also a or b out from what was given in the 3 EditText-Views. But it crashes and won't output a result. Any suggestions? I'm pretty new to this stuff. :)
package net.starostka.somefunctions;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Pythagoras extends AppCompatActivity implements View.OnClickListener {
EditText aNumPyt;
EditText bNumPyt;
EditText cNumPyt;
Button pythagorasCalcu;
TextView pythagorasResultFinal;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pythagoras);
aNumPyt = (EditText) findViewById(R.id.aNumPyt);
bNumPyt = (EditText) findViewById(R.id.bNumPyt);
pythagorasCalcu = (Button) findViewById(R.id.pythagorasCalcu);
pythagorasResultFinal = (TextView) findViewById(R.id.pythagorasResultFinal);
// set a listener
pythagorasCalcu.setOnClickListener(this);
}
#Override
public void onClick(View v) {
double a=0,b=0,c=0;
double hypot = 0.0;
/*
// check if the fields are empty
if (TextUtils.isEmpty(aNumPyt.getText().toString()) || TextUtils.isEmpty(bNumPyt.getText().toString()) || TextUtils.isEmpty(cNumPyt.getText().toString())) {
return;
}
*/
// read EditText and fill variables with numbers
a = Double.parseDouble(aNumPyt.getText().toString());
b = Double.parseDouble(bNumPyt.getText().toString());
c = Double.parseDouble(cNumPyt.getText().toString());
if (a>b && a>c){
hypot=a;
if(hypot*hypot==(b*b+c*c)){
//result = Math.sqrt(Math.pow(a,2)+Math.pow(b,2));
pythagorasResultFinal.setText(String.valueOf(hypot));
}
} else if (b>a && b>c){
hypot=b;
if(hypot*hypot==(a*a+c*c)){
//result = Math.sqrt(Math.pow(a,2)+Math.pow(b,2));
pythagorasResultFinal.setText(String.valueOf(hypot));
}
} else if (c>a && c>b){
hypot=c;
if(hypot*hypot==(a*a+b*b)){
//result = Math.sqrt(Math.pow(a,2)+Math.pow(b,2));
pythagorasResultFinal.setText(String.valueOf(hypot));
}
}
}
}
The XML file
</LinearLayout>
<TextView
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_marginLeft="5pt"
android:layout_marginRight="5pt"
android:textSize="12pt"
android:layout_marginTop="3pt"
android:id="#+id/pythagorasResultFinal"
android:gravity="center_horizontal">
</TextView>
Before crash:
After crash:
EDIT
Interesting that no one pointed this out earlier, but I just realized you never initialize cNumPyt. You initialize the other EditTexts but never C. So when you try to get the text, you get NullPointerException because you try to get information from nothing.
Initialize the correct text box in your onCreate method.
In your image, you show that you are leaving input blank for one of the text boxes (in the "after crash" image, we see that you entered 3, 4, and then nothing). This means that there is no Double to be parsed, because "" is not a number.
From the Double documentation:
public static double parseDouble(String s) throws NumberFormatException
[...]
Throws:
NullPointerException - if the string is null
NumberFormatException - if the string does not contain a parsable double.
If your input is blank, you'll get an exception. Since it's not in a try-catch block, your application will crash.
To be more specific:
//cNumPyt is empty, and "" is not a parseable number, so NumberFormatException
c = Double.parseDouble(cNumPyt.getText().toString());
Sample block (you will need to do this for every variable separately so you can tell which variable was empty):
try{
a = Double.parseDouble(aNumPyt.getText().toString());
}catch (NumberFormatException e){
//oops, no number available
a = 0; //default to 0 (or whatever you choose)
}
#Override
public void onClick(View v) {
double a=0,b=0,c=0;
if (!TextUtils.isEmpty(aNumPyt.getText().toString()) &&
!TextUtils.isEmpty(bNumPyt.getText().toString()) &&
!TextUtils.isEmpty(cNumPyt.getText().toString()))
{
a = Double.parseDouble(aNumPyt.getText().toString());
b = Double.parseDouble(bNumPyt.getText().toString());
c = Double.parseDouble(cNumPyt.getText().toString());
if((a*a)==((b*b)+(c*c))){
pythagorasResultFinal.setText(String.valueOf(a));
}
else if ((b*b)==((a*a)+(c*c))){
pythagorasResultFinal.setText(String.valueOf(b));
}
else if ((c*c)==((a*a)+(b*b))){
pythagorasResultFinal.setText(String.valueOf(c));
}
}
}
I found the problem.. Arc676's solution worked as seen in the code below:
#Override
public void onClick(View v) {
double a=0.0,b=0.0,c=0.0;
double hypot = 0.0;
try{
a = Double.parseDouble(aNumPyt.getText().toString());
}catch (NumberFormatException e){
//oops, no number available
a = 0.0; //default to 0 (or whatever you choose)
}
try{
b = Double.parseDouble(bNumPyt.getText().toString());
}catch (NumberFormatException e){
//oops, no number available
b = 0.0; //default to 0 (or whatever you choose)
}
try{
c = Double.parseDouble(cNumPyt.getText().toString());
}catch (NumberFormatException e){
//oops, no number available
c = 0.0; //default to 0 (or whatever you choose)
}
if (c == 0.0){
hypot = Math.sqrt((Math.pow(a,2))+(Math.pow(b,2)));
pythagorasResultFinal.setText("Finding C\n" + String.valueOf(hypot));
}else if (a == 0.0){
hypot = Math.sqrt((Math.pow(c,2))-(Math.pow(b,2)));
pythagorasResultFinal.setText("Finding A\n" + String.valueOf(hypot));
}else if (b == 0.0) {
hypot = Math.sqrt((Math.pow(c,2))-(Math.pow(a,2)));
pythagorasResultFinal.setText("Finding B\n" + String.valueOf(hypot));
}
}
Another essential problem i found was i did not define the id for the c View.. Really small problem causing it all to crash..
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pythagoras);
aNumPyt = (EditText) findViewById(R.id.aNumPyt);
bNumPyt = (EditText) findViewById(R.id.bNumPyt);
cNumPyt = (EditText) findViewById(R.id.cNumPyt); //Forgot to add this line of code
pythagorasCalcu = (Button) findViewById(R.id.pythagorasCalcu);
pythagorasResultFinal = (TextView) findViewById(R.id.pythagorasResultFinal);
// set a listener
pythagorasCalcu.setOnClickListener(this);
}
Thanks for the fast response and help! (y)

Creating app in Android studio but keep getting an error Required Boolean found int

So I'm creating an app that validates a users input but when I did it for the password all it says is Required boolean found int
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user);
submit = (Button)findViewById(R.id.submit);
name = (EditText)findViewById(R.id.name);
pass = (EditText)findViewById(R.id.pass);
number = (EditText)findViewById(R.id.number);
email = (EditText)findViewById(R.id.email);
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final String Name = name.getText().toString();
final String Pass = pass.getText().toString();
if(name.length()==0)
{
name.requestFocus();
name.setError("Field cannot be empty");
}
else if(!Name.matches("[a-zA-Z]+"))
{
name.requestFocus();
name.setError("ENTER ONLY ALPHABETICAL CHARACTERS");
}
else if (pass.length())
{
pass.requestFocus();
pass.setError("FIELD CANNOT BE EMPTY");
}
else {
Context context = getApplicationContext();
CharSequence text = "Thank you, your request is being processed!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
});
}
The error is happening on the line where it says pass.length. Could anyone please help in what the problem is
Use
else if (pass.length()>0)
instead so that you get a boolean value to use inside the if condition
While using conditional statements you have to use boolean variable to check the condition is valid or not.
else if (pass.length())
Here pass.length() returns the length of the variable, which is an integer. You should not use the integer to check the condition.
In contrast with e.g. C/C++ language, Java does not allow numeric values to be used instead of boolean values (0/1 != false/true).

Comparing strings in Java

Im trying to compare the values of two edittext boxes. What i would like is to just compare passw1 = passw2. As my code is now comparing two strings i have entered as i could not get to compare them.
final EditText passw1= (EditText) findViewById(R.id.passw1);
final EditText passw2= (EditText) findViewById(R.id.passw2);
Button buttoks = (Button) findViewById(R.id.Ok);
buttoks.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (passw1.toString().equalsIgnoreCase("1234") && passw2.toString().equalsIgnoreCase("1234")){
Toast.makeText(getApplication(),"Username and password match", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(getApplication(),"Username and password doesn't match", Toast.LENGTH_SHORT).show();
}
} });
Using the == operator will compare the references to the strings not the string themselves.
Ok, you have to toString() the Editable. I loaded up some of the code I had before that dealt with this situation.
String passwd1Text = passw1.getText().toString();
String passwd2Text = passw2.getText().toString();
if (passwd1Text.equals(passwd2Text))
{
}
[EDIT]
I made a mistake earlier, because, to get the text, you need to use .getText().toString().
Here is a full working example:
package com.psegina.passwordTest01;
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.LinearLayout;
import android.widget.Toast;
public class Main extends Activity implements OnClickListener {
LinearLayout l;
EditText user;
EditText pwd;
Button btn;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
l = new LinearLayout(this);
user = new EditText(this);
pwd = new EditText(this);
btn = new Button(this);
l.addView(user);
l.addView(pwd);
l.addView(btn);
btn.setOnClickListener(this);
setContentView(l);
}
public void onClick(View v){
String u = user.getText().toString();
String p = pwd.getText().toString();
if( u.equals( p ) )
Toast.makeText(getApplicationContext(), "Matches", Toast.LENGTH_SHORT).show();
else
Toast.makeText(getApplicationContext(), user.getText()+" != "+pwd.getText(), Toast.LENGTH_SHORT).show();
}
}
Original answer (Will not work because of the lack of toString())
Try using .getText() instead of .toString().
if( passw1.getText() == passw2.getText() )
#do something
.toString() returns a String representation of the whole object, meaning it won't return the text you entered in the field (see for yourself by adding a Toast which will show the output of .toString())
In onclik function replace first line with this line u will definitely get right result.
if (passw1.getText().toString().equalsIgnoreCase("1234") && passw2.getText().toString().equalsIgnoreCase("1234")){
You can compare the values using equals() of Java :
public void onClick(View v) {
// TODO Auto-generated method stub
s1=text1.getText().toString();
s2=text2.getText().toString();
if(s1.equals(s2))
Show.setText("Are Equal");
else
Show.setText("Not Equal");
}
You need both getText() - which returns an Editable and toString() - to convert that to a String for matching.
So instead of: passw1.toString().equalsIgnoreCase("1234")
you need passw1.getText().toString().equalsIgnoreCase("1234").
ou can use String.compareTo(String) that returns an integer that's negative (<), zero(=) or positive(>).
Use it so:
You can use String.compareTo(String) that returns an integer that's negative (<), zero(=) or positive(>).
Use it so:
String a="myWord";
if(a.compareTo(another_string) <0){
//a is strictly < to another_string
}
else if (a.compareTo(another_string) == 0){
//a equals to another_string
}
else{
// a is strictly > than another_string
}
Try to use .trim() first, before .equals(), or create a new String var that has these things.
did the same here needed to show "success" twice
response is data from PHP
String res=response.toString().trim;
Toast.makeText(sign_in.this,res,Toast.LENGTH_SHORT).show();
if ( res.compareTo("success")==0){
Toast.makeText(this,res,Toast.LENGTH_SHORT).show();
}
String password=passw1.trim();
if (password.equalsIgnoreCase("1234")){
Toast.makeText(getApplication(),"Username and password match", Toast.LENGTH_SHORT).show();
}
You need to use the trim method in the String

Categories