0

I'm trying to insert data to an Android database table.

The database is created. I get no errors, but no data gets inserted.

I added exception and I got some errors.

MainActivity

package com.example.shaz.geotag;

import android.app.Dialog;
import android.content.pm.PackageManager;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.identity.intents.Address;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
 import com.google.android.gms.maps.OnMapReadyCallback;
 import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import java.io.IOException;
import java.util.List;

public class MainActivity extends AppCompatActivity implements                     OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,    GoogleApiClient.OnConnectionFailedListener,       com.google.android.gms.location.LocationListener {
//to access map fragment
GoogleMap mGoogleMap;
GoogleApiClient mGoogleApiClient;
DatabaseHelper myDb;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


    if (googleServicesAvailable()) {
        Toast.makeText(this, "Started", Toast.LENGTH_LONG).show();
        setContentView(R.layout.activity_main);
        initMap();
    } else {
        //No google map layout
    }

}


public boolean googleServicesAvailable() {
    GoogleApiAvailability api = GoogleApiAvailability.getInstance();
    int isAvailable = api.isGooglePlayServicesAvailable(this);
    if (isAvailable == ConnectionResult.SUCCESS) {
        return true;
    } else if (api.isUserResolvableError(isAvailable)) {
        Dialog dialog = api.getErrorDialog(this, isAvailable, 0);
        dialog.show();
    } else {
        Toast.makeText(this, "Cant connect to play services", Toast.LENGTH_LONG).show();
    }
    return false;

}


private void initMap() {
    MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.mapFragment);
    mapFragment.getMapAsync(this);//it gets map details and



}



@Override
public void onMapReady(GoogleMap googleMap) {
    mGoogleMap = googleMap;
    myDb=new DatabaseHelper(this);




    if(mGoogleMap!=null){
        mGoogleMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter(){

            @Override
            public View getInfoWindow(Marker marker) {
                return null;
            }

            @Override
            public View getInfoContents(Marker marker) {
                View v = getLayoutInflater().inflate(R.layout.info_window,null);

                TextView tvLat= (TextView) v.findViewById(R.id.tv_lat);
                TextView tvLng= (TextView) v.findViewById(R.id.tv_lng);

                LatLng ll=marker.getPosition();

                tvLat.setText("Latitude "+ ll.latitude);
                tvLng.setText("Longitude "+ll.longitude);

                return v;
            }
        });
    }






    if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
    }
        mGoogleApiClient.connect();



}

private void goToLocationZoom(double lat, double lng, float zoom) {
    LatLng ll = new LatLng(lat, lng);
    CameraUpdate update = CameraUpdateFactory.newLatLngZoom(ll, zoom);
    mGoogleMap.moveCamera(update);
}

Marker marker;



public void geoLocate(View view) throws IOException {
                //       
       //            if(marker!=null)

       //        {

           //            marker.remove();

                  //        }

        MarkerOptions options =new MarkerOptions()

                .position(new LatLng(lat,lng))
                    .icon(BitmapDescriptorFactory.
             defaultMarker(BitmapDescriptorFactory.HUE_GREEN));

             marker = mGoogleMap.addMarker(options);


    boolean isInserted = myDb.insertData(Double.toString(lat),Double.toString(lng));
    if(isInserted==true){
        Toast.makeText(MainActivity.this,"Data Inserted",Toast.LENGTH_LONG).show();
    }
    else
        Toast.makeText(MainActivity.this,"Data not Inserted",Toast.LENGTH_LONG).show();

         }

LocationRequest mLocationRequest;

@Override
public void onConnected(Bundle bundle) {
    mLocationRequest = LocationRequest.create();
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    mLocationRequest.setInterval(1000);


    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    else {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest,this);
    }
}
@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}

    double lat;
    double lng;
@Override
public void onLocationChanged(Location location) {
    if(location == null){
        Toast.makeText(this, "Cant get current location", Toast.LENGTH_LONG).show();
    } else {
        lat=location.getLatitude();
        lng=location.getLongitude();
        LatLng ll = new LatLng(lat, lng);
        CameraUpdate update = CameraUpdateFactory.newLatLngZoom(ll, 17);
        mGoogleMap.animateCamera(update);
    }
}
   }

DatabaseHelper
Here is my database class. I think it is fine but still errors.

  package com.example.shaz.geotag;

   import android.content.ContentValues;
   import android.content.Context;
     import android.database.SQLException;
       import android.database.sqlite.SQLiteDatabase;
     import android.database.sqlite.SQLiteOpenHelper;
      import android.util.Log;
     import android.widget.Toast;


     public class DatabaseHelper extends SQLiteOpenHelper {
      public static final String DATABASE_NAME="GEOTAG";
      public static final String TABLE_NAME="GEOTAG_table";
      public static final String CoL_1="ID";
       public static final String CoL_2="LATITUDE";
      public static final String CoL_3="LONGITUDE";
       public static Context c;




public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, 1);
    c=context;
    Toast.makeText(c, "Database", Toast.LENGTH_LONG).show();
}

@Override
public void onCreate(SQLiteDatabase db) {
    try {
        db.execSQL("CREATE TABLE " + TABLE_NAME + "(" + CoL_1 + "INTEGER PRIMARY KEY AUTOINCREMENT, " + CoL_2 + " TEXT, " + CoL_3 + " TEXT);");

    } catch (SQLException e) {
        Log.e("HEY","Error creating");
        e.printStackTrace();
    }

    Toast.makeText(c, "Database Created", Toast.LENGTH_LONG).show();


}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
    onCreate(db);

}

public boolean insertData (String lat,String lng){
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues =new ContentValues();
    contentValues.put(CoL_2,lat);
    contentValues.put(CoL_3,lng);
    long res =db.insert(TABLE_NAME,null,contentValues);
    if (res==-1)
        return false;
    else
        return true;


}

      }

LOG
And finally log.

   E/SQLiteDatabase: Error inserting LONGITUDE=71.4924987 LATITUDE=30.2575152
              android.database.sqlite.SQLiteException: no such table: GEOTAG_table (Sqlite code 1): , while compiling: INSERT INTO GEOTAG_table(LONGITUDE,LATITUDE) VALUES (?,?), (OS error - 2:No such file or directory)
                  at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                  at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:897)
                  at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:508)
                  at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
                  at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:63)
                  at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
                  at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1504)
                  at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1371)
                  at com.example.shaz.geotag.DatabaseHelper.insertData(DatabaseHelper.java:59)
                  at com.example.shaz.geotag.MainActivity$override.geoLocate(MainActivity.java:187)
                  at com.example.shaz.geotag.MainActivity$override.access$dispatch(MainActivity.java)
                  at com.example.shaz.geotag.MainActivity.geoLocate(MainActivity.java:0)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
                  at android.view.View.performClick(View.java:5273)
                  at android.view.View$PerformClick.run(View.java:21315)
                  at android.os.Handler.handleCallback(Handler.java:743)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:150)
                  at android.app.ActivityThread.main(ActivityThread.java:5665)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:799)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:689)
          I/art: GC statistics: 19 time(s), freed 198661(66MB) objects, paused 22.298ms total 447.358ms
        W/InputMethodManager: Current bind isn't success!

I cant figure out why table is not created. There is no syntax error.

M. le Rutte
  • 3,525
  • 3
  • 18
  • 31
Shazil
  • 11
  • 6
  • Refer this: http://stackoverflow.com/questions/25081316/table-not-getting-created-sqlite-android – phoenix Feb 19 '17 at 07:10

3 Answers3

1

From your error log no table like "GEOTAG_table" if you are using emulator you can pull the db file and check if the table is created or not, if you are using a device you can use this command

cd /D D:\Android\SDK\platform-tools // android sdk path

adb -d shell

run-as com.pkg.pkgname

cat /data/data/com.pkg.pkgname/databases/UR_DB_NAME >/sdcard/UR_DB_NAME

it will copy your db file to device sd card. Using Sqlite browser you can open the db file and check the table is created or not

remove this myDb=new DatabaseHelper(this); from onMapReady(GoogleMap googleMap)method and use it in activities oncreate method

sajan
  • 389
  • 5
  • 11
  • i already checked using Sqlite browser Database was created but table was not created – Shazil Feb 19 '17 at 07:17
  • try after this change remove this myDb=new DatabaseHelper(this); from onMapReady(GoogleMap googleMap)method and use it in activities oncreate method – sajan Feb 19 '17 at 07:18
  • still table is not created and data is not inserted – Shazil Feb 19 '17 at 07:25
  • in your db oncreate `db.execSQL("CREATE TABLE " + TABLE_NAME + "(" + CoL_1 + "INTEGER PRIMARY KEY AUTOINCREMENT, " + CoL_2 + " TEXT, " + CoL_3 + " TEXT);");` one space is missing between `CoL_1 +` and `"INTEGER PRIMARY KEY AUTOINCREMENT` as per below answer. Change it to `db.execSQL("CREATE TABLE " + TABLE_NAME + "(" + CoL_1 + " INTEGER PRIMARY KEY AUTOINCREMENT, " + CoL_2 + " TEXT, " + CoL_3 + " TEXT);");` – sajan Feb 19 '17 at 07:28
  • you getting these toasts `Toast.makeText(c, "Database", Toast.LENGTH_LONG).show();` and `Toast.makeText(c, "Database Created", Toast.LENGTH_LONG).show();` ?? – sajan Feb 19 '17 at 07:58
  • first uninstall the application from device then install and check – sajan Feb 19 '17 at 08:57
  • Did that but no progress – Shazil Feb 19 '17 at 09:58
0

I plugged your code in and it looks like the CREATE TABLE needs a space here "(" + CoL_1 + " INTEGER. It tried to create a column called IDINTEGER and then specified no datatype. Here it is fixed (and worked in my quick test).

@Override
public void onCreate(SQLiteDatabase db) {
    try {
        db.execSQL("CREATE TABLE " + TABLE_NAME + "(" + CoL_1 + " INTEGER PRIMARY KEY AUTOINCREMENT, " + CoL_2 + " TEXT, " + CoL_3 + " TEXT);");
    } catch (SQLException e) {
        Log.e("HEY","Error creating");
        e.printStackTrace();
    }
    Toast.makeText(c, "Database Created", Toast.LENGTH_LONG).show();
}
chris g
  • 1,088
  • 10
  • 18
0

Finally..Its working I added extension .db in database name And changed the code in onCreate function as

   "CREATE TABLE " + TABLE_NAME + " (" + CoL_1 + " INTEGER PRIMARY KEY AUTOINCREMENT, " + CoL_2 +" TEXT,"+ CoL_3 +" TEXT)"

I removed semicolon and added space for brackets too

Shazil
  • 11
  • 6