我必须解决一个任务,我必须从数据库显示所有纬度经度的具体位置,距我当前位置不超过100米。
这是我的主要活动:
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MultiDex.install(this);
setContentView(R.layout.activity_maps);
//etOrigin = (EditText) findViewById(R.id.etOrigin);
btnFindPath = (Button) findViewById(R.id.btnFindPath);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
// Inserting Contacts
Log.d("Insert: ", "Inserting ..");
// db.addLocation(new LocationManager(1,);
db.addLocation(new LocationManager(1, "23.780551", "90.416380", "Gulshan-1"));
db.addLocation(new LocationManager(2, "23.780315", "90.418354", "Gulshan-1"));
db.addLocation(new LocationManager(3, "23.780472", "90.415093", "Gulshan-1"));
db.addLocation(new LocationManager(4, "23.780786", "90.422817", "Gulshan-1"));
db.addLocation(new LocationManager(5, "23.776734", "90.425558", "Badda"));
db.addLocation(new LocationManager(6, "23.776538", "90.425601", "Badda"));
db.addLocation(new LocationManager(7, "23.776572", "90.425563", "Badda"));
db.addLocation(new LocationManager(8, "23.776911", "90.425595", "Badda"));
db.addLocation(new LocationManager(9, "23.781436", "90.425442", "Pran RFl"));
db.addLocation(new LocationManager(10, "23.781293", "90.425583", "Pran RFl"));
db.addLocation(new LocationManager(11, "23.781307", "90.425280", "Pran RFl"));
db.addLocation(new LocationManager(12, "23.781481", "90.425591", "Pran RFl"));
btnFindPath.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mMap.clear();
sendRequest();
}
});
}
@Override
public void onPause() {
super.onPause();
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
} else {
checkLocationPermission();
}
}
else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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;
}
/* mMap.setMyLocationEnabled(true);*/
}
@Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
@Override
public void onConnectionSuspended(int i) {}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {}
@Override
public void onLocationChanged(Location location)
{
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
latitude = location.getLatitude();
longitude = location.getLongitude();
// to get current location without click event code has to be added here
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private void checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
new AlertDialog.Builder(this)
.setTitle("Location Permission Needed")
.setMessage("This app needs the Location permission, please accept to use location functionality")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(MapsActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
})
.create()
.show();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
}
}
private double findDistance(double lat1, double lon1, double lat2, double lon2) {
double theta = lon1 - lon2;
double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
dist = Math.acos(dist);
dist = rad2deg(dist);
dist = dist * 60 * 1.1515;
return (dist);
}
private double deg2rad(double deg) {
return (deg * Math.PI / 180.0);
}
private double rad2deg(double rad) {
return (rad * 180.0 / Math.PI);
}
private void sendRequest() {
LatLng latLng = new LatLng(latitude,longitude);
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);
CircleOptions addCircle = new CircleOptions().center(latLng).radius(radiusInMeters).fillColor(shadeColor).strokeColor(strokeColor).strokeWidth(8);
mCircle = mMap.addCircle(addCircle);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
List<LocationManager> locations = db.getAllLocations();
for (LocationManager cn : locations) {
finlat1 = Double.valueOf(cn.getLatitude());
finlon2 = Double.valueOf(cn.getLongitude());
String name = cn.getPlacename();
double distance = findDistance(latitude, longitude, finlat2, finlon2) * 1000;
if (distance <= 100.00) {
LatLng venus = new LatLng(finlat2, finlon2);
Log.wtf("venus:", String.valueOf(venus));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(venus, 18));
originMarkers.add(mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.mark))
.title(name)
.position(venus)));
}
}
return;
}
}
我的数据库处理程序是:DatabaseHandler.java
package com.pran.vehicletrackingapp.dbhelper;
/**
* Created by Administrator on 11/30/2016.
*/
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 static java.lang.Integer.*;
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "locationStore";
private static final String TABLE_LOCATION = "locations";
private static final String KEY_ID = "id";
private static final String KEY_LATITUDE = "latitude";
private static final String KEY_LONGITUDE = "longitude";
private static final String KEY_PLACENAME = "placename";
// private static final String KEY_PH_NO = "phone_number";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
//3rd argument to be passed is CursorFactory instance
}
// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_LOCATION_TABLE = "CREATE TABLE " + TABLE_LOCATION + "("
+ KEY_ID + " ID INTEGER PRIMARY KEY AUTOINCREMENT ,"
+ KEY_LATITUDE + " TEXT ,"
+ KEY_LONGITUDE + " TEXT ,"
+ KEY_PLACENAME + " TEXT,"
+ ")";
db.execSQL(CREATE_LOCATION_TABLE);
}
// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LOCATION);
// Create tables again
onCreate(db);
}
// code to add the new contact
public void addLocation(LocationManager location) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ID , location.getID());
values.put(KEY_LATITUDE, location.getLatitude());
values.put(KEY_LONGITUDE , location.getLongitude());
values.put(KEY_PLACENAME, location.getPlacename()); // Contact Name
//values.put(KEY_PH_NO, location.getPhoneNumber()); // Contact Phone
// Inserting Row
db.insert(TABLE_LOCATION, null, values);
//2nd argument is String containing nullColumnHack
db.close(); // Closing database connection
}
// code to get the single contact
LocationManager getLocation(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_LOCATION, new String[] {
KEY_ID,KEY_LONGITUDE,KEY_LONGITUDE,KEY_PLACENAME}, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
LocationManager location = new LocationManager(cursor.getInt(0),cursor.getString(1),cursor.getString(2),cursor.getString(3) );
// return contact
return location;
}
// code to get all contacts in a list view
public List<LocationManager> getAllLocations() {
List<LocationManager> contactList = new ArrayList<LocationManager>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_LOCATION;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
LocationManager location = new LocationManager();
location.setID(cursor.getInt(0));
location.setLatitude(cursor.getString(1));
location.setLongitude(cursor.getString(2));
location.setPlacename(cursor.getString(3));
// contact.setPhoneNumber(cursor.getString(2));
// Adding contact to list
contactList.add(location);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
// code to update the single contact
public int updateLocation(LocationManager location) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ID , location.getID());
values.put(KEY_LATITUDE, location.getLatitude());
values.put(KEY_LONGITUDE , location.getLongitude());
values.put(KEY_PLACENAME, location.getPlacename());
// updating row
return db.update(TABLE_LOCATION, values, KEY_ID + " = ?",
new String[] { String.valueOf(location.getID()) });
}
// Deleting single contact
public void deleteLocation(LocationManager location) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_LOCATION, KEY_ID + " = ?",
new String[] { String.valueOf(location.getID()) });
db.close();
}
// Getting contacts Count
public int getLocationCount() {
String countQuery = "SELECT * FROM " + TABLE_LOCATION;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
但它显示了错误:
致命的例外:主要 过程:com.pran.vehicletrackingapp,PID:16019 java.lang.NullPointerException:尝试调用虚方法 &#39; java.lang.String java.lang.String.trim()&#39;在null对象引用上 在java.lang.StringToReal.parseDouble(StringToReal.java:263) 在java.lang.Double.parseDouble(Double.java:301) 在java.lang.Double.valueOf(Double.java:338) 在 com.pran.vehicletrackingapp.MapsActivity.sendRequest(MapsActivity.java:323) 在 com.pran.vehicletrackingapp.MapsActivity.access $ 100(MapsActivity.java:46) 在 com.pran.vehicletrackingapp.MapsActivity $ 1.onClick(MapsActivity.java:118) 在android.view.View.performClick(View.java:5716) 在android.widget.TextView.performClick(TextView.java:10926) 在android.view.View $ PerformClick.run(View.java:22596) 在android.os.Handler.handleCallback(Handler.java:739) 在android.os.Handler.dispatchMessage(Handler.java:95) 在android.os.Looper.loop(Looper.java:148) 在android.app.ActivityThread.main(ActivityThread.java:7325) at java.lang.reflect.Method.invoke(Native Method) 在 com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:1230) 在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
我该如何解决?
答案 0 :(得分:2)
该行
+ KEY_ID + " ID INTEGER PRIMARY KEY AUTOINCREMENT ,"
应该是
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT ,"