创建 table 并插入数据

Creating table and inserting data

我正在尝试将数据插入 Android 数据库 table。

数据库已创建。我没有收到任何错误,但没有插入任何数据。

我添加了异常,但出现了一些错误。

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);
    }
}
   }

数据库助手
这是我的数据库 class。我觉得还好,还是报错。

  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;


}

      }

日志
最后登录。

   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!

我不明白为什么没有创建 table。没有语法错误。

从你的错误日志中没有 table 像 "GEOTAG_table" 如果您使用的是模拟器,您可以拉取 db 文件并检查是否创建了 table,如果您使用的是设备,则可以使用此命令

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

adb -d shell

run-as com.pkg.pkgname

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

它将您的数据库文件复制到设备的 SD 卡。使用 Sqlite 浏览器,您可以打开 db 文件并检查 table 是否已创建

onMapReady(GoogleMap googleMap) 方法中删除此 myDb=new DatabaseHelper(this); 并在活动 oncreate 方法中使用它

我插入了你的代码,看起来 CREATE TABLE 需要一个 space 这里 "(" + CoL_1 + " INTEGER。它试图创建一个名为 IDINTEGER 的列,然后未指定任何数据类型。在这里它是固定的(并且在我的快速测试中有效)。

@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();
}

终于..它的工作 我在数据库名称中添加了扩展名 .db 并将 onCreate 函数中的代码更改为

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

我删除了分号并为括号添加了 space