Search code examples
javaandroidsqliteandroid-sqlite

Not able to INSERT to SQLite database


I am taking a location's latitude and longitude information and add them to SQLite. Looks like I have no problem with creating database but my inserting does not work. Here is my code:

private GoogleMap mMap;
    Button button;
    double _lat,_lon;
    Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
        intent = getIntent();
        _lat = intent.getDoubleExtra("yenie",0);
        _lon = intent.getDoubleExtra("yenib",0);
        button = findViewById(R.id.kaydet);
        SQLiteDatabase database = this.openOrCreateDatabase("Konumlar",MODE_PRIVATE,null);
        database.execSQL("CREATE TABLE IF NOT EXISTS knm (lat DOUBLE,lon DOUBLE)");
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try{
                    database.execSQL("INSERT INTO knm (lat,lon) VALUES (_lat,_lon)");
                    Toast.makeText(getApplicationContext(),"sa",Toast.LENGTH_LONG);
                }
                catch (Exception e){
                    
                }
            }
        });
    }

As I understand by debugging, in onClick() method, insertion fails and it goes to catch. What could be my problem? Thanks in advance.


Solution

  • The type of lat and lon fields in your CREATE TABLE query is specified as DOUBLE, whereas in your INSERT query you are trying to insert String(_lat & _lon) values.

    I believe, you are trying to insert the values from the Bundle, i.e. values of _lat and _lon.

    Thus, to resolve your error, please rewrite your INSERT query as below.

    database.execSQL("INSERT INTO knm (lat,lon) VALUES (" + _lat + "," + _lon + ")");