Search code examples
androidgoogle-mapsexceptionandroid-edittextnumberformatexception

Android Number formatting exception when taking information from edit text


here i take the latude and longtude from the user then i converted it into integer and here is the problem the log cat msg is :

unable to convert 30.01 into int ! then i enter the lat and lon into my table in the database:

  public class newMission extends Activity 
  implements OnClickListener{
SQLiteDatabase sql;
EditText e1,e2,e3,e4;
Button b;
MaptoDo obj;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    Intent in =getIntent();
    setContentView(R.layout.newmission);
    e1=(EditText) findViewById(R.id.edn1);
    e2=(EditText) findViewById(R.id.edn2);
    e3=(EditText) findViewById(R.id.edn3);
    e4=(EditText) findViewById(R.id.edn4);
    b=(Button) findViewById(R.id.btnew);
    b.setOnClickListener(this);
    obj=new MaptoDo();
    sql=openOrCreateDatabase("db",0, null);
    sql.execSQL("CREATE TABLE Mission" +
            "" +
            " (emp integer REFERENCES Employee2 (password)," +
            "oper_n text,cust_n text,lat double," +
            "long double,oper_id integer PRIMARY KEY AUTOINCREMENT)");
}
@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    String opN=e1.getText().toString();
    String cuN=e2.getText().toString();
    String lats=e3.getText().toString();
    String lons=e4.getText().toString();
     try {
  int lat=Integer.parseInt(lats);
  int lon=Integer.parseInt(lons);
  sql.execSQL("insert into Mission (oper_n,cust_n,lat,long)values('"+opN+"','"+cuN+"',"+lat+","+lon+");");
  Toast.makeText(this,"Data Inserted",2000).show();
  obj.addMission(lat, lon); 
    //add to ToDo list too 
}catch (NumberFormatException nfe) {
    Toast.makeText(this, "Please Enter Valid Data",2000).show();
}}

}


Solution

  • Try using the double datatype first.

    double dLat=Double.parseDouble(lats);
    double dLon=Double.parseDouble(lons);
    

    Then its a matter of getting the value before the decimal point:

    int lat = (int)Math.floor(dLat);
    int lon = (int)Math.floor(dLon);
    

    Or if you want - you can run a regular expression on the input first to make sure it has digits [dot] digits otherwise the extraction of the inputs to numeric will fail, but having said that, that would be dependent on how the layout for the EditText has it set up for certain input types - android:inputType within the XML layout.