Google地图的数据未在数据库中正确保存

时间:2015-03-30 11:19:34

标签: android google-maps

我正在研究与Google地图相关的Android应用程序。当我尝试给予时 通过模拟器控制它的值不会在地图中给出我想要的输出。 谁能帮我吗? 这是我的MapsActivity.java:

package com.example.user.suraksha;

import android.content.ContentValues;
import android.content.IntentSender;
import android.database.sqlite.SQLiteConstraintException;
import android.database.sqlite.SQLiteDatabase;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

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

public class MapsActivity extends FragmentActivity implements
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener {
    public static final String TAG = MapsActivity.class.getSimpleName();
    /*
    * Define a request code to send to Google Play services
    * This code is returned in Activity.onActivityResult
    */
    private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
    private GoogleMap mMap; // Might be null if Google Play services APK is not available.
    private GoogleApiClient mGoogleApiClient;
    private LocationRequest mLocationRequest;
    MySqlHelper mDbHelper = new MySqlHelper(this);
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        setUpMapIfNeeded();
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
// Create the LocationRequest object
        mLocationRequest = LocationRequest.create()
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                .setInterval(10 * 1000) // 10 seconds, in milliseconds
                .setFastestInterval(1 * 1000); // 1 second, in milliseconds
    }
    @Override
    protected void onResume() {
        super.onResume();
        setUpMapIfNeeded();
        mGoogleApiClient.connect();
    }
    @Override
    protected void onPause() {
        super.onPause();
        if (mGoogleApiClient.isConnected()) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
            mGoogleApiClient.disconnect();
        }
    }
    /**
     * Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
     * installed) and the map has not already been instantiated.. This will ensure that we only ever
     * call {@link #setUpMap()} once when {@link #mMap} is not null.
     * <p/>
     * If it isn't installed {@link SupportMapFragment} (and
     * {@link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
     * install/update the Google Play services APK on their device.
     * <p/>
     * A user can return to this FragmentActivity after following the prompt and correctly
     * installing/updating/enabling the Google Play services. Since the FragmentActivity may not
     * have been completely destroyed during this process (it is likely that it would only be
     * stopped or paused), {@link #onCreate(Bundle)} may not be called again so we should call this
     * method in {@link #onResume()} to guarantee that it will be called.
     */
    private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
        if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
            mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                    .getMap();
// Check if we were successful in obtaining the map.
            if (mMap != null) {
                setUpMap();
            }
        }
    }
    /**
     * This is where we can add markers or lines, add listeners or move the camera. In this case, we
     * just add a marker near Africa.
     * <p/>
     * This should only be called once and when we are sure that {@link #mMap} is not null.
     */
    private void setUpMap() {
        mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
    }
    private void handleNewLocation(Location location) {
        Log.d(TAG, location.toString());
        double currentLatitude = location.getLatitude();
        double currentLongitude = location.getLongitude();
        LatLng latLng = new LatLng(currentLatitude, currentLongitude);
//mMap.addMarker(new MarkerOptions().position(new LatLng(currentLatitude, currentLongitude)).title("Current Location"));
        Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
        String   add = "";
        try{
            List<Address> addresses = geocoder.getFromLocation(currentLatitude, currentLongitude, 1);
            if (addresses != null && addresses.size() > 0) {
                StringBuilder result = new StringBuilder();
                for(int i = 0; i < addresses.size(); i++){
                    Address address =  addresses.get(i);
                    int maxIndex = address.getMaxAddressLineIndex();
                    for (int x = 0; x <= maxIndex; x++ ){
                        result.append(address.getAddressLine(x));
                        result.append(",");
                    }
                    result.append(address.getLocality());
                    result.append(",");
                    result.append(address.getPostalCode());
                    result.append("\n\n");
                }

               add = result.toString();
            }

        }catch (Exception e){
            e.printStackTrace();
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
        }
        SQLiteDatabase db = mDbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        try {
            values.put("loc_longitude", currentLongitude);
            values.put("loc_latitude", currentLatitude);
            values.put("loc_title", add);
            long newrowid = db.insert("Location", null, values);
        }catch(SQLiteConstraintException e){
            e.printStackTrace();
        }
        MarkerOptions options = new MarkerOptions()
                .position(latLng)
                .title(add);
        mMap.addMarker(options);
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    }
    @Override
    public void onConnected(Bundle bundle) {
        Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (location == null) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        }
        else {
            handleNewLocation(location);
        }
    }
    @Override
    public void onConnectionSuspended(int i) {
    }
    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
/*
* Google Play services can resolve some errors it detects.
* If the error has a resolution, try sending an Intent to
* start a Google Play services activity that can resolve
* error.
*/
        if (connectionResult.hasResolution()) {
            try {
// Start an Activity that tries to resolve the error
                connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
            } catch (IntentSender.SendIntentException e) {
// Log the error
                e.printStackTrace();
            }
        } else {
/*
* If no resolution is available, display a dialog to the
* user with the error.
*/
            Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
        }
    }
    @Override
    public void onLocationChanged(Location location) {
        handleNewLocation(location);
    }
}

这是我的MySqlHelper.java:     包com.example.user.suraksha;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * Created by user on 3/29/2015.
 */

public class MySqlHelper extends SQLiteOpenHelper{
    public static final String TABLE_NAME = "Location";

    public static final String ID_SQL = "loc_id";
    public static final String TITLE = "loc_title";
    public static final String LONGITUDE = "loc_longitude";
    public static final String LATITUDE = "loc_latitude";
    public static final String POSITION = "loc_position";

    public static final int D_VERSION = 1;
    public static final String DB_NAME = "markerlocations.db";

    public static final String DB_CREATE =
            "create table Location ( loc_id integer autoincrement,loc_longitude float , loc_latitude float, loc_title text , loc_position text,primary key(loc_id));";

    public MySqlHelper(Context context) {
        super(context, DB_NAME, null, D_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(DB_CREATE);
    }

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

这是我的logcat错误:

    03-30 19:23:55.980: E/ConnectivityService(387): Exception trying to add  a route: java.lang.IllegalStateException: command '16 interface fwmark exempt add 10.0.2.2/32' failed with '400 16 Failed to add exemption rule (File exists)'
03-30 19:23:56.120: E/logwrapper(772): executing /system/bin/ip failed: No such file or directory
03-30 19:25:10.630: E/JavaBinder(670): java.lang.RuntimeException: android.os.DeadObjectException
03-30 19:25:10.630: E/JavaBinder(670):     at android.os.Parcel.writeException(Parcel.java:1366)
03-30 19:25:10.630: E/JavaBinder(670):     at android.os.Binder.execTransact(Binder.java:410)
03-30 19:25:10.630: E/JavaBinder(670):     at dalvik.system.NativeStart.run(Native Method)
03-30 19:25:10.630: E/JavaBinder(670): Caused by: android.os.DeadObjectException
03-30 19:25:10.630: E/JavaBinder(670):     at android.os.BinderProxy.transact(Native Method)
03-30 19:25:10.630: E/JavaBinder(670):     at android.content.IIntentReceiver$Stub$Proxy.performReceive(IIntentReceiver.java:124)
03-30 19:25:10.630: E/JavaBinder(670):     at android.app.ActivityThread$ApplicationThread.scheduleRegisteredReceiver(ActivityThread.java:816)
03-30 19:25:10.630: E/JavaBinder(670):     at android.app.ApplicationThreadNative.onTransact(ApplicationThreadNative.java:394)
03-30 19:25:10.630: E/JavaBinder(670):     at android.os.Binder.execTransact(Binder.java:404)
03-30 19:26:35.210: E/SQLiteDatabase(1015): Error inserting loc_latitude=37.422005 loc_longitude=-100.084095 loc_title=
03-30 19:26:35.210: E/SQLiteDatabase(1015): android.database.sqlite.SQLiteConstraintException: columns loc_longitude, loc_latitude are not unique (code 19)
03-30 19:26:35.210: E/SQLiteDatabase(1015):     at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
03-30 19:26:35.210: E/SQLiteDatabase(1015):     at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:782)
03-30 19:26:35.210: E/SQLiteDatabase(1015):     at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
03-30 19:26:35.210: E/SQLiteDatabase(1015):     at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
03-30 19:26:35.210: E/SQLiteDatabase(1015):     at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1469)
03-30 19:26:35.210: E/SQLiteDatabase(1015):     at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1339)
03-30 19:26:35.210: E/SQLiteDatabase(1015):     at com.example.user.suraksha.MapsActivity.handleNewLocation(MapsActivity.java:144)
03-30 19:26:35.210: E/SQLiteDatabase(1015):     at com.example.user.suraksha.MapsActivity.onLocationChanged(MapsActivity.java:194)
03-30 19:26:35.210: E/SQLiteDatabase(1015):     at com.google.android.gms.internal.zzpe$zza.handleMessage(Unknown Source)
03-30 19:26:35.210: E/SQLiteDatabase(1015):     at android.os.Handler.dispatchMessage(Handler.java:102)
03-30 19:26:35.210: E/SQLiteDatabase(1015):     at android.os.Looper.loop(Looper.java:136)
03-30 19:26:35.210: E/SQLiteDatabase(1015):     at android.app.ActivityThread.main(ActivityThread.java:5017)
03-30 19:26:35.210: E/SQLiteDatabase(1015):     at java.lang.reflect.Method.invokeNative(Native Method)
03-30 19:26:35.210: E/SQLiteDatabase(1015):     at java.lang.reflect.Method.invoke(Method.java:515)
03-30 19:26:35.210: E/SQLiteDatabase(1015):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-30 19:26:35.210: E/SQLiteDatabase(1015):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
03-30 19:26:35.210: E/SQLiteDatabase(1015):     at dalvik.system.NativeStart.main(Native Method)
03-30 19:26:38.930: E/StrictMode(620): A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.
03-30 19:26:38.930: E/StrictMode(620): java.lang.Throwable: Explicit termination method 'close' not called
03-30 19:26:38.930: E/StrictMode(620):     at dalvik.system.CloseGuard.open(CloseGuard.java:184)
03-30 19:26:38.930: E/StrictMode(620):     at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:278)
03-30 19:26:38.930: E/StrictMode(620):     at android.net.SSLCertificateSocketFactory.verifyHostname(SSLCertificateSocketFactory.java:190)
03-30 19:26:38.930: E/StrictMode(620):     at android.net.SSLCertificateSocketFactory.createSocket(SSLCertificateSocketFactory.java:435)
03-30 19:26:38.930: E/StrictMode(620):     at com.android.okhttp.Connection.upgradeToTls(Connection.java:131)
03-30 19:26:38.930: E/StrictMode(620):     at com.android.okhttp.Connection.connect(Connection.java:107)
03-30 19:26:38.930: E/StrictMode(620):     at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:294)
03-30 19:26:38.930: E/StrictMode(620):     at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:255)
03-30 19:26:38.930: E/StrictMode(620):     at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:206)
03-30 19:26:38.930: E/StrictMode(620):     at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)
03-30 19:26:38.930: E/StrictMode(620):     at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:89)
03-30 19:26:38.930: E/StrictMode(620):     at com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:197)
03-30 19:26:38.930: E/StrictMode(620):     at com.android.okhttp.internal.http.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:254)
03-30 19:26:38.930: E/StrictMode(620):     at com.google.android.gms.http.GoogleHttpClient.a(SourceFile:913)
03-30 19:26:38.930: E/StrictMode(620):     at com.google.android.gms.http.GoogleHttpClient.b(SourceFile:759)
03-30 19:26:38.930: E/StrictMode(620):     at com.google.android.gms.http.GoogleHttpClient.execute(SourceFile:663)
03-30 19:26:38.930: E/StrictMode(620):     at com.google.android.gms.http.GoogleHttpClient.execute(SourceFile:654)
03-30 19:26:38.930: E/StrictMode(620):     at com.google.android.gms.playlog.uploader.e.a(SourceFile:346)
03-30 19:26:38.930: E/StrictMode(620):     at com.google.android.gms.playlog.uploader.e.a(SourceFile:232)
03-30 19:26:38.930: E/StrictMode(620):     at com.google.android.gms.playlog.uploader.e.a(SourceFile:204)
03-30 19:26:38.930: E/StrictMode(620):     at com.google.android.gms.playlog.uploader.UploaderService.a(SourceFile:52)
03-30 19:26:38.930: E/StrictMode(620):     at com.google.android.gms.gcm.ap.run(SourceFile:131)

1 个答案:

答案 0 :(得分:0)

MapActivityForAddress.java

public class MapActivityForAddress extends Activity implements LocationListener, OnMyLocationButtonClickListener {

    private GoogleMap googleMap;
    LocationManager locationManager;
    Location location;
    Geocoder geocoder;
    List<Address> addresses;
    CameraUpdate cameraUpdate;
    double latitude, longitude;
    String zip, city, state, country, mediaPath, mediaDate, mediaTime, mediaLongitude, mediaLatitude;
    int position = 0;
    String title = "";
    DatabaseHelper dbHelper;
    Button next;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.map_activity_for_address);

        if (!isGooglePlayServicesAvailable()) {
            finish();
        }
        MapFragment supportMapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.mapforAddress);
        next = (Button) findViewById(R.id.btnMapNext);
        dbHelper = new DatabaseHelper(getApplicationContext());

        googleMap = supportMapFragment.getMap();
        googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
        googleMap.setMyLocationEnabled(true);
        // googleMap.setOnMyLocationButtonClickListener(this);
        googleMap.getUiSettings().setZoomControlsEnabled(true);

        googleMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {

            @Override
            public void onMapLongClick(LatLng arg0) {
                googleMap.clear();
                latitude = arg0.latitude;
                longitude = arg0.longitude;
                zip = null;
                city = null;
                state = null;
                country = null;

                geocoder = new Geocoder(MapActivityForAddress.this, Locale.getDefault());
                try {

                    addresses = geocoder.getFromLocation(latitude, longitude, 1);
                    if (addresses != null && addresses.size() > 0) {

                        title = "";
                        zip = addresses.get(0).getPostalCode();
                        city = addresses.get(0).getLocality();
                        state = addresses.get(0).getAdminArea();
                        country = addresses.get(0).getCountryName();
                        if (zip != null) {
                            title += zip + ", ";
                        }
                        if (city != null) {
                            title += city + ", ";
                        }
                        if (state != null) {
                            title += state + ", ";
                        }
                        if (country != null) {
                            title += country;
                        }
                    } else {
                        title = "Unknown Location";
                    }

                } catch (IOException e) {

                    e.printStackTrace();
                }
                googleMap.addMarker(new MarkerOptions().position(arg0).title(title));

            }
        });
        next.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                if (!title.trim().isEmpty() && title != null) {

                    finish();
                } else {
                    Toast.makeText(getApplicationContext(), "Select Location First", Toast.LENGTH_LONG).show();

                }

            }
        });



 // place this function on your button click
dbHelper.insertMedia(mediaAddress, mediaLongitude, mediaLatitude);
        }

    @Override
    protected void onResume() {
        super.onResume();
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        if (location != null) {
            LatLng latLang = new LatLng(location.getLatitude(), location.getLongitude());
            cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLang, 17);
            googleMap.animateCamera(cameraUpdate);

        }

    }

    @Override
    public void onBackPressed() {

    }

    @Override
    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub

    }

    private boolean isGooglePlayServicesAvailable() {
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (ConnectionResult.SUCCESS == status) {
            return true;
        } else {
            GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
            return false;
        }
    }

    @Override
    public boolean onMyLocationButtonClick() {
        // TODO Auto-generated method stub
        return false;
    }

}

DatabaseHelper.java

public class DatabaseHelper extends SQLiteOpenHelper {

     private static final String DATABASE_NAME = "MapDatabase.db";


    private static final int DATABASE_VERSION = 1;

    Cursor cur;
    SQLiteDatabase db;
    ContentValues values;

    // Table Names

    private static final String INCIDENT = "incident";


    // Table Create Statements

    // INCIDENT table create statement
    private static final String CREATE_TABLE_INCIDENT = "CREATE TABLE "+ INCIDENT + " (sr_no INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, mediaAddress text,mediaLongitude text,mediaLatitude text)";

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

    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL(CREATE_TABLE_INCIDENT);

    }

    public void insertMedia(String mAddress, String mLongitude, String mLatitude) {
        db = this.getWritableDatabase();

        values = new ContentValues();
        cur = db.query(INCIDENT, null, null, null, null, null, null);
        cur.moveToFirst();

        values.put("mediaAddress", mAddress);
        values.put("mediaLongitude", mLongitude);
        values.put("mediaLatitude", mLatitude);

        db.insert(INCIDENT, null, values);
        db.close();


    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

}