Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/226.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 记录空值的SQLite表_Android_Sqlite - Fatal编程技术网

Android 记录空值的SQLite表

Android 记录空值的SQLite表,android,sqlite,Android,Sqlite,我试图从android GPS传感器中提取纬度和经度,并在本地将它们写入sqlite db文件中的列。然而,我似乎不明白为什么这些值不是正确的纬度和经度 DatabaseHandler.java import java.util.ArrayList; import java.util.List; import android.content.ContentValues; import android.content.Context; import android.database.Curso

我试图从android GPS传感器中提取纬度和经度,并在本地将它们写入sqlite db文件中的列。然而,我似乎不明白为什么这些值不是正确的纬度和经度

DatabaseHandler.java

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;


`public class DatabaseHandler extends SQLiteOpenHelper  {

// All static variables
    // Database version
    private static final int DATABASE_VERSION = 1;

    // Database name
    private static final String DATABASE_NAME = "Cordinates Manager";

    // Coordinates Table name
    private static final String TABLE_CORDINATES = "cordinates";

    // Coordinates Table Column titles
    private static final String KEY_ID = "ID";
    private static final String KEY_LAT = "LAT"; 
    private static final String KEY_LNG = "LNG";

    public String latitudeField;
    public String longitudeField;

    public DatabaseHandler(Context context)  {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // Creating Table
    @Override
    public void onCreate(SQLiteDatabase db)  {
        String CREATE_CORDINATES_TABLE = "CREATE TABLE " + TABLE_CORDINATES + "("
                + KEY_ID + "INTEGER PRIMARY KEY, " + KEY_LAT + //" TEXT,"  
                 KEY_LNG + ")";

        // create table
        db.execSQL(CREATE_CORDINATES_TABLE);
    }

    // Upgrading database
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)  {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTED" + TABLE_CORDINATES);

        // Create table again
        this.onCreate(db);
    }

    //Adding new Coordinate
    public void addCordinate(Cordinates cordinate)  {
        // Print to the log cat
        Log.println(Log.ASSERT, "addCordinate", cordinate.toString());
        // 1. Get reference to writable DB
        SQLiteDatabase db = this.getWritableDatabase();

        // 2. Create contentValues to add key "column" / value
        ContentValues values = new ContentValues();
        values.put(KEY_LAT, cordinate.getLat()); // Coordinates Lat
        values.put(KEY_LNG, cordinate.getLng()); // Coordinates Lng

        // 3. Inserting a Row
        db.insert(TABLE_CORDINATES, null, values);
        // 4. Close the database
        db.close(); // close database connection
    }

    // Getting Single Cordinate Row
    Cordinates getCordinates(int id)  {
        // 1. get reference to readable DB
        SQLiteDatabase db = this.getReadableDatabase();

        // 2. Build query
        Cursor cursor = db.query(TABLE_CORDINATES,           // a. table
                new String[] { KEY_ID, KEY_LAT, KEY_LNG },   // b. column names 
                KEY_ID + "=?",                               // c. selections 
                new String[] {String.valueOf(id) },          // d. selection args  
                null,                                        // e. group by
                null,                                        // f. having
                null,                                        // g. order by
                null);                                       // h. limit

        // 3.  if we get results, get the first one 
        if(cursor != null)
            cursor.moveToFirst();

        // 4.  build cordinate object
        Cordinates cordinate = new Cordinates();

        // Print to the log cat
        Log.println(Log.ASSERT,"getCordinates("+id+")", cordinate.toString());
        // 5.  return cordinates
        return cordinate;
    }

    // Getting All Cordinates
    public List<Cordinates> getAllCordinates()  {
        List<Cordinates> cordinateList = new ArrayList<Cordinates>();
        // 1.  Build the query for Select All
        String selectQuery = "SELECT *  FROM * " + TABLE_CORDINATES;

        // 2.  get reference to writable DB
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);


        // 3.  Looping through all rows and adding to list
        if (cursor.moveToFirst())  {
            do {
                Cordinates cordinates = new Cordinates();
                cordinates.setID(Integer.parseInt(cursor.getString(0)));
                cordinates.setLat(cursor.getLong(1));
                cordinates.setLng(cursor.getLong(2));

                // Adding Cordinate to list
                cordinateList.add(cordinates);
            } while (cursor.moveToNext());
        }

        Log.println(Log.ASSERT,"getAllCordinates()", cordinateList.toString());
        // return the cordinate list
        return cordinateList;
    }

    /* for every new row, update single cordinate row
     *      'Listen for cordinate values*
     * if !newRow == false NEW ROOWWWW!!
     * Create a new value object
     */
    public int updateCordinate(Cordinates cordinate)  {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues value = new ContentValues();
        value.put(KEY_LAT, cordinate.getLat()); // get latitude
        value.put(KEY_LNG, cordinate.getLng()); // get longitude

        // Updating row
        return db.update(TABLE_CORDINATES, value, KEY_ID + " = ?",
                new String[] { String.valueOf(cordinate.getID())});
    }

    // Deleting a single Coordinate
    public void deleteCordinate(Cordinates cordinate)  {
        // 1.  get reference to writable DB
        SQLiteDatabase db = this.getWritableDatabase();

        // 2.  delete
        db.delete(TABLE_CORDINATES, KEY_ID + "=?",
                new String[] {String.valueOf(cordinate.getID()) });

        // 3. Close
        db.close();
        Log.println(Log.ASSERT, "deleteCordinate", cordinate.toString());
    }

    // Getting Cordinate total count
    public int getCordinatesCount()  {
        String countQuery = "SELECT * FROM " + TABLE_CORDINATES;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        cursor.close();

        Log.println(Log.ASSERT, "getcCordinatesCount()", countQuery.toString());

        // return count
        return cursor.getCount();
    }
}
MyLocation.java

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.widget.TextView;
import android.widget.Toast;
import android.util.Log;
import com.xxx.DatabaseHandler;

public class MyLocation extends Activity implements LocationListener  {

      private Handler handler = null;  
      private TextView latituteField = null;
      private TextView longitudeField = null;
      private double lat = 0;
      private double lng = 0;
      DatabaseHandler db = null;

      @Override
      protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.println(Log.ASSERT, "MyLocation.java", "App Started ~^*~^*~^*~^*~^*~^*~^*~^*~^*~^*~^*~^*");
        setContentView(R.layout.activity_main);

        // get db
        db = new DatabaseHandler(getApplicationContext());

        // Handler will post to UI thread
        handler = new Handler();

        // normal stuff
        latituteField = (TextView) findViewById(R.id.latTextView);
        longitudeField = (TextView) findViewById(R.id.lngTextView);

        LocationManager lm = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
        if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER))  {
            Toast.makeText(this, "Enable your GPS.",Toast.LENGTH_LONG).show();
            Intent intent = new Intent(  
                Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(intent); 
        }

        Location loc = lm.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
            Log.println(Log.ASSERT, "getLastKnownLocation()", loc.getLatitude() + " " + loc.getLongitude());
            lat = loc.getLatitude();
            lng = loc.getLongitude();
            latituteField.setText(lat + "");
            longitudeField.setText(lng + "");

            // THIS IS the standard 
            // Register the listener with the Location Manager to receive location updates
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500, 0, this); // Or NETWORK_PROVIDER
      }

            public void onLocationChanged(Location loc) {
                lat = loc.getLatitude();
                lng = loc.getLongitude();
                DatabaseHandler db = new DatabaseHandler(this);
                db.addCordinate(new Cordinates());
                handler.post(new Runnable() {
                        public void run() {
                            latituteField.setText(lat + "");
                            longitudeField.setText(lng + "");                               
                        }
                }); 
            }

            @Override
            public void onProviderDisabled(String provider) { 
                Toast.makeText(getApplicationContext(), "GPS Disabled  " + provider,Toast.LENGTH_SHORT).show();
                Log.println(Log.ASSERT, "onProviderDisabled()", "Provider has been Disabled");              
            }

            @Override
            public void onProviderEnabled(String provider) {
                // you could do things here, such as sense when a user has turned off the gps in setttings
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
                // provides a lot of info that might be useful, such as the quality of the signal, etc.
                Log.println(Log.ASSERT, "onStatusChanged()", "PROVIDER : " + provider 
                        + " ~ " +"STATUS: " + status 
                        + ". /// " + "EXTRAS? : " + extras 
                        + ".");

                Toast.makeText(getApplicationContext(), "Latitude: "+lat+ "\n"+" Longitude: "+lng, Toast.LENGTH_SHORT).show();              
            }
        }

任何人都可以跟踪我的代码,看看为什么我每行都得到空值吗?还有为什么我有“TEXT”的列标签?

首先用以下内容更正您的
创建表查询:

String CREATE_CORDINATES_TABLE = "CREATE TABLE " + TABLE_CORDINATES + "( "
            + KEY_ID + " INTEGER PRIMARY KEY, " + KEY_LAT + " TEXT, "  
             KEY_LNG + " TEXT);";

您的字段KEY_LAT和KEY_LNG是整数,您尝试在其中插入浮点值


您应该将值转换为整数,或者将值和db字段转换为文本。

首先更正
创建表查询
。在
列名
列类型
之间添加空格您是否检查从GPS接收的值是否正确?将行添加到SQLite时,值的正确性是否重要?这会在创建表时修复列吗?或者这是针对所有行的空值吗?不,这只是创建一个包含空行的表。添加纬度和经度值时,应将
Double
转换为
String
,获取此值时,应将此值从
String
转换为
Double
,并使用它。就是这样。所以在添加行之前,我必须使用toString()之类的工具将浮点值转换为文本。是否显示SQLite数据库?是。数据类型应该匹配
String CREATE_CORDINATES_TABLE = "CREATE TABLE " + TABLE_CORDINATES + "( "
            + KEY_ID + " INTEGER PRIMARY KEY, " + KEY_LAT + " TEXT, "  
             KEY_LNG + " TEXT);";