NumberFormatException error - Android - android

I get NumberFormatException error at this line of my code. What should i do?
String employ = intent.getStringExtra("employeeid").trim();
spinEmployee.setSelection(Integer.parseInt(employ)-1);

You can handle this by adding try catch block.
Create one method to get valid int from string like this
public int getValidIntFromString(String inputstring) {
if (inputstring!= null) {
if (!inputstring.equals("")) {
try {
return Integer.parseInt(inputstring);
} catch (NumberFormatException e) {
// TODO: handle exception
Log.e("Error-- > ", e.toString());
return 0;
}
} else {
return 0;
}
} else {
return 0;
}
}
Now you can convert string to int by calling this
int intemploy = getValidIntFromString(employ);
Here employ will be your String from where you want to parse Int from String.
Note: if you get employ data from EditText then please set inputType="number" in xml file to avoid such kind of Exception.
Just like this
<EditText
android:id="#+id/myEditText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="number" />

The exception says the format of EMPLOY is not valid,maybe it's a String like '2d','33a'

Related

Android - JSON No value for 1 - but there is using Log

I'm stuck at trying to get a simple string from a JsonObject.
Here is the basic code. result is a JsonObject returned from an Asynctask. I've done dozens of the same way, and here it doesn't work.
Response:{"status":200}
Error: An error is thrown saying "No value for 1"
When I Log the content of the JsonObject, I get this: 200, which is what I want. For which reason could this return null when there is a value?
Edit if I use the result.has("status"); true is returned. I don't understand.
Log.e("TAG", result.get("status").toString());
try{
String status = result.getString("status");
} catch (Exception e){
e.getMessage();
}
You are getting int value in the object and you are holding in string which causes the error
You are getting int value in status
{
"status":200
}
if it is like
{
"status":"200"
}
Your code works perfectly.
Try this
Log.e("TAG", result.get("status").toString());
try{
int status = result.getInt("status");
} catch (Exception e){
e.getMessage();
}

Empty EditText error (Lots of EditTexts)

The activity contains a lot of EditTexts (about 40) where the user enters numbers, and then they're added. But when one of these EditTexts is empty, it gives an error and the app stops. I've read lots of solutions, but I don't want to write code for each EditText.
Here is some code (Wrote 450 lines, don't gonna show them all, but all of them are similar)
EditText mark1;
EditText mark2;
EditText mark3;
EditText mark4;
EditText mark5;
TextView marksem1;
Button calcsem1;
double mark1calc=0;
double mark2calc=0;
double mark3calc=0;
double mark4calc=0;
double mark5calc=0;
double totalsem1=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.etsia_gia_ata_layout);
initControls();
private void initControls() {
// Course 1 sem 1 calc
mark1=(EditText)findViewById(R.id.mark1);
mark2=(EditText)findViewById(R.id.mark2);
mark3=(EditText)findViewById(R.id.mark3);
mark4=(EditText)findViewById(R.id.mark4);
mark5=(EditText)findViewById(R.id.mark5);
marksem1=(TextView)findViewById(R.id.total1calc);
calcsem1=(Button)findViewById(R.id.total1);
calcsem1.setOnClickListener(new Button.OnClickListener()
{public void onClick
(View v) {calcsem1();}
private void calcsem1() {
mark1calc=Double.parseDouble(mark1.getText().toString());
mark2calc=Double.parseDouble(mark2.getText().toString());
mark3calc=Double.parseDouble(mark3.getText().toString());
mark4calc=Double.parseDouble(mark4.getText().toString());
mark5calc=Double.parseDouble(mark5.getText().toString());
totalsem1=(9*mark1calc+6*mark2calc+6*mark3calc+6*mark4calc+3*mark5calc)/30;
marksem1.setText(Double.toString(totalsem1));
marksem1.setText(String.format("%.2f", totalsem1));
}});
}
}
Hope there's a solution. Thank you very much!
Your problem comes from the fact that Double.parseDouble(...) on an empty string will throw a NumberFormatException. You could replace each line with somthing like this:
try {
mark1calc = Double.parseDouble(mark1.getText().toString());
} catch (NumberFormatException e) {
mark1calc = 0;
}
This is a lot of extra code, so I'd suggest implementing something like this:
public static Double safeParse(String input) {
try {
return Double.parseDouble(input);
} catch (NumberFormatException e) {
return 0d;
}
}
// ...
mark1calc = safeParse(mark1.getText().toString());
mark2calc = safeParse(mark2.getText().toString());
mark3calc = safeParse(mark3.getText().toString());
// ...
(This assumes you want an empty box to be worth 0; you can adjust the default value to your needs)
I assume your problem is with parseDouble. You can write your own protected parseDouble, which will try-catch to parse the text, and if an exception is thrown, will just return zero.
Something like this:
private static double safeParseDouble(String text)
{
try
{
double result = Double.parseDouble(text);
return result;
}
catch (Exception ex)
{
return 0;
}
}
Double.parseDouble() can throw exceptions so you will need to use try-catch block.
try {
mark1calc=Double.parseDouble(mark1.getText().toString());
mark2calc=Double.parseDouble(mark2.getText().toString());
mark3calc=Double.parseDouble(mark3.getText().toString());
mark4calc=Double.parseDouble(mark4.getText().toString());
mark5calc=Double.parseDouble(mark5.getText().toString());
totalsem1=(9*mark1calc+6*mark2calc+6*mark3calc+6*mark4calc+3*mark5calc)/30;
marksem1.setText(Double.toString(totalsem1));
marksem1.setText(String.format("%.2f", totalsem1));
} catch (Exception e) {
// handle errors...
}
you can replace your parsing statement with terinary statement as below:
mark2calc = mark4.getText().toString().equals("") ? 0 : Double.parseDouble(mark4.getText().toString());

Eclipse - Functions issue [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I'm trying to get text from server and then check it a to know what actions to take with the text adopted. The problem is that when I try to check if the received text for example is "Exited" the query always return the value "false" when the received text is really "Exited".
Here is the code :
class Get_Message_From_Server implements Runnable
{
public void run()
{
InputStream iStream = null;
try
{
iStream = Duplex_Socket_Acceptor.getInputStream();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
//Create byte array of size image
byte[] Reading_Buffer = null;
try
{
Reading_Buffer = new byte [Duplex_Socket_Acceptor.getReceiveBufferSize()];
//New_Buffer = new byte [100];
}
catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
byte[] Byte_Char_1 = new byte[1];
int Byte_String_Lenght = 0;
//read size
try
{
iStream.read(Reading_Buffer);
String Reading_Buffer_Stream_Lenghtor = new String(Reading_Buffer);
//System.out.println("full : " + Reading_Buffer_Stream_Lenghtor);
Byte_String_Lenght = Reading_Buffer_Stream_Lenghtor.indexOf(new String(Byte_Char_1));
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
//Convert to String
Meassage = new String(Reading_Buffer);
Meassage = Meassage.substring(0, Byte_String_Lenght);//The text that received
Message_Getted = 1;
}
}
The query :
if(Message_1 != "Exited")//the message query
{
System.out.println("Continued 253");
continue;
}
Its always return the value - false
its important to know that the message is in Utf - 8 encoding
so how i can to fix the issue ?
If you compare strings by using oparators, Java will not look at the contents of the string but at the reference in memory. To compare String content in Java, you should use the following:
String Message_1; // Hopefully has a value sent by the server
if(Message_1.equals("Exited")) {
// Do stuff when exited
} else {
// Do stuff when not exited
}
String is a variable - and variables should start with lower Case letter - Please read Java Code conventions. Also to check if your message contains string you thing it should just do System.out.println(Message_1); and if the message contains what you expect you compare string doing
if(Message_1.equals("Exited")) {
System.out.println("Yes they are equal");
} else {
System.out.println("No they are not");
}
If this will print "No they are not" that simply means that your variable Message_1 is not what you think it is.. As simple as that. There is no such a thing as .equals method does not work. Its your variable that doesn't ;)

unable to convert EditText to int using parseInt

The logcat shows that the Integer.Parse() function was not able to convert the string to int or float whereas i have linked the xml file in java. Also, i have set the input Type of the rate and quantity column as number so there is no chance that the user can enter anything other than an int or float. Plz help. I have been trying to get this code working for a long time. But i cant find the solution.
Attached is the code:
public int initializeVars(){
int i;
for(i=0;i<9;i++){
//items[i] is the AutoCompleteTextView array
item[i]=items[i].getText().toString();
iquant[i]=Integer.valueOf(quant[i].getText().toString());
irate[i]=Float.valueOf(rates[i].getText().toString());
if(item[i]=="")
break;
}
return i;
}
}
To avoid these kind of circumstances use these two functions.
For Int
private int getIntFromString(String str){
try{
return Integer.parseInt(str);
}catch(Exception e){
return 0;
}
}
For float
private float getFloatFromString(String str){
try{
return Float.parseFloat(str);
}catch(Exception e){
return 0f;
}
}
Call these methods at required places
Try to use the parseInt method instead of valueOf and also keep that parsing code in try{}...catch{} block of NumberFormateException.
try{
iquant[i]=Integer.parseInt(quant[i].getText().toString());
irate[i]=Float.parseFloat(rates[i].getText().toString());
}
catch(NumberFormateException e){}
INT
try {
myInt = Integer.parseInt(myString);
} catch(NumberFormatException e) {
}
FLOAT
try {
myFloat = Float.parseFloat(myString);
} catch(NumberFormatException e) {
}
Maybe instead of valueOf you can try parsing it directly via
yourInt = Integer.parseInt(yourString);
youtFloat = Float.parseFloat(yourString);
I always do it this way and it works. In the float variable make sure that decimals are marked by "." not ",".
You may also want to try and catch NumberFormatException to avoid problems while parsing.

Using fractions on android editText

I'd like an inputType in the edit text that i can input fractional number like this: 2/4 (i want print the "/").
The program is about calculating things and i need to type fractional insted of decimal. Thanks. Sorry my bad english.
I think the best way would be to use a string for your input text, then to parse the string to figure out what kind of things the user entered.
When the user has finished their input, you can check the string with something like this:
public float testInputString(String testString) {
boolean goodInput = true;
float result = 0;
if (testString.contains("/")) {
//possible division
String pieces[] = testString.split("/");
if (pieces.length != 2) {
goodInput = false;
} else {
try {
float numerator = Float.parseFloat(pieces[0]);
float denominator = Float.parseFloat(pieces[1]);
result = numerator/denominator;
} catch (Exception e) {
goodInput = false;
}
}
} else if (testString.contains(".")) {
try {
result = Float.parseFloat(testString);
} catch (Exception e) {
goodInput = false;
}
}
//TODO something here if bad input, maybe an alert or something
return result;
}
Also, you can check while they are typing for valid input if you use a keylistener like this. You could modify that to allow only numbers . and /.
put this property in xml node of Edittext and use Double notation instead of "/"
android:digits="1234567890.-"

Categories

Resources