Reputation: 31
Writing my first android app. Almost everything works except this function. Even when all the text boxes have some numeric value, the app crashes in this function. Also, is there a better way to retrieve all the values in these text boxes and convert it to int. Note that all the textboxes are input type number on the activity.xml file.
public int updateclks()
{
try{
EditText v1= (EditText) findViewById(R.id.editText1);
EditText v2 = (EditText) findViewById(R.id.EditText01);
EditText v3 = (EditText) findViewById(R.id.EditText02);
EditText v4 = (EditText) findViewById(R.id.EditText03);
EditText c1= (EditText) findViewById(R.id.EditText04);
EditText c2 = (EditText) findViewById(R.id.EditText05);
EditText c3 = (EditText) findViewById(R.id.EditText06);
EditText c4 = (EditText) findViewById(R.id.EditText07);
try{ //error occurs somewhere around this block
vsel[1]= Integer.parseInt(v1.getText().toString());
vsel[2]= Integer.parseInt(v2.getText().toString());
vsel[3]= Integer.parseInt(v3.getText().toString());
vsel[4]= Integer.parseInt(v4.getText().toString());
clk[1]= Integer.parseInt(c1.getText().toString());
clk[2]= Integer.parseInt(c2.getText().toString());
clk[3]= Integer.parseInt(c3.getText().toString());
clk[4]= Integer.parseInt(c4.getText().toString());
}
catch(NumberFormatException e)
{
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, "Fields cannot be empty", duration);
toast.show();
return 1;
}
return 0;
}
Upvotes: 0
Views: 1320
Reputation: 481
I also got the same problem and u can solve it by using trim function.
clk[1]= Integer.parseInt(c1.getText().toString().trim());
Upvotes: 0
Reputation: 15477
parseInt() is not crashing your app.Because if any exception occurs for this parseInt it will be caught as you handled it.Since your application is still crashing see vse1 and clk1 array whether you created these correctly or not.
Also notice about array length if you created vse1 array of length 4.Then You may want to start with index 0 rather than 1.Otherwise ArrayIndexOutOfBounds will crash your application.
Upvotes: 1