我正在尝试从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();
}
}
Cordinates.java
public class Cordinates {
// private variables
int _id;
float _latValue;
float _lngValue;
// Empty Constructor
public Cordinates() {
}
// constructor
public Cordinates(int id, float latValue, float lngValue) {
this._id = id;
this._latValue = latValue;
this._lngValue = lngValue;
}
/* GETTERS for id, latitude, longitude
* Will try to add the import for time later...
*/
// getting ID
public int getID() {
return this._id;
}
// getting latitude
public float getLat() {
return this._latValue;
}
// getting longitude
public float getLng() {
return this._lngValue;
}
/* SETTERS for id, latitude, longitude
* Will try to add the import for time later...
*/
public void setID(int id) {
this._id = id;
}
// setting latitude
public void setLat(long latValue) {
this._latValue = latValue;
}
// setting longitude
public void setLng(long lngValue) {
this._lngValue = lngValue;
}
}
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'的列标签?
答案 0 :(得分:1)
首先用以下内容纠正您的Create Table Query
:
String CREATE_CORDINATES_TABLE = "CREATE TABLE " + TABLE_CORDINATES + "( "
+ KEY_ID + " INTEGER PRIMARY KEY, " + KEY_LAT + " TEXT, "
KEY_LNG + " TEXT);";
答案 1 :(得分:0)
您的字段KEY_LAT和KEY_LNG是整数,并且您尝试在那里插入浮点值。
您应该将值转换为整数,或将值和db字段转换为TEXT。