Search code examples
androidandroid-edittextnumberformatexception

Not able to set focus on the first edittext field?


I am not able to set focus on the first edittext field (among other 3 below it).Code is:

k1_e=(EditText)findViewById(R.id.k1_editText);
k1_e.requestFocusFromTouch();
try{
k1=Float.parseFloat(k1_e.getText().toString());
}catch(Exception e) {
    Log.e("logtag", "Exception: " + e.toString());
}
k2_e=(EditText)findViewById(R.id.k2_editText);
try{
    k2=Float.parseFloat(k2_e.getText().toString());
}catch(Exception e) {
    Log.e("logtag", "Exception: " + e.toString());
}
al_e=(EditText)findViewById(R.id.al_editText);
try{
    al=Float.parseFloat(al_e.getText().toString());
}catch(Exception e) {
    Log.e("logtag", "Exception: " + e.toString());
}
alconst_e=(EditText)findViewById(R.id.al_const_editText);
try{
    al_const=Float.parseFloat(alconst_e.getText().toString()); 
}catch(Exception e) {
    Log.e("logtag", "Exception: " + e.toString());
}

when app is executed on emulator it automatically sets focus to last edittext field and an exception is thrown as:

12-29 08:10:05.241: E/logtag(769): Exception: java.lang.NumberFormatException: Invalid float: ""
12-29 08:10:05.261: E/logtag(769): Exception: java.lang.NumberFormatException: Invalid float: ""
12-29 08:10:05.261: E/logtag(769): Exception: java.lang.NumberFormatException: Invalid float: ""
12-29 08:10:05.271: E/logtag(769): Exception: java.lang.NumberFormatException: Invalid float: ""

what is the error.I am a beginner.pls help


Solution

  • Your k1_e.getText().toString() returns String which cant converted Float

    Try this for all:

    Do this, make int flag = 0; gobal to your class. and when you getview executed for the first time then make the flag as 1;

    Like this:

    int flag = 0;
    
      getView()
    {
    if(flag == 0)
    {
    k1_e.requestFocusFromTouch();flag = 1;
    }
      string abc = k1_e.getText().toString()
            if(abc != null && !abc.equals(""))
            {
             k1=Float.parseFloat(k1_e.getText().toString());
            }
        else
        {
          k1 = 0.0;
        }
    
    }