如何发送纬度和经度从机器人到MySQL [英] How to send latitude and longtitude from android to Mysql

查看:190
本文介绍了如何发送纬度和经度从机器人到MySQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里输入的形象描述我想提出一个简单的Andr​​oid应用获取的位置一个Android用户,我需要的纬度和经度发送到MySQL数据库。我如何能做到用这种code段的?

数据库处理器类

 包com.example.gpstracking;进口android.content.ContentValues​​;
进口android.content.Context;
进口android.database.sqlite.SQLiteDatabase;
进口android.database.sqlite.SQLiteOpenHelper;公共类数据库处理器扩展SQLiteOpenHelper {    //所有静态变量
    //数据库版本
    私有静态最终诠释DATABASE_VERSION = 1;    //数据库名称
    私有静态最后弦乐DATABASE_NAME =GPS;    //联系人表名
    私有静态最后弦乐TABLE_CONTACTS =地利;    //联系方式表列名
    私有静态最后弦乐KEY_ID =ID;
    私有静态最后弦乐KEY_LAT =纬度;
    私有静态最后弦乐KEY_LONG =长;     公共数据库处理器(上下文的背景下){
        超(背景下,DATABASE_NAME,空,DATABASE_VERSION);
    }    //创建表
    @覆盖
    公共无效的onCreate(SQLiteDatabase DB){
        字符串CREATE_CONTACTS_TABLE =CREATE TABLE+ TABLE_CONTACTS +(
                + KEY_ID +INTEGER PRIMARY KEY,+ KEY_LAT +TEXT
                + KEY_LONG +TEXT+);
        db.execSQL(CREATE_CONTACTS_TABLE);
    }    //数据库升级
    @覆盖
    公共无效onUpgrade(SQLiteDatabase分贝,INT oldVersion,诠释静态网页){
        如果存在//删除旧的表
        db.execSQL(DROP TABLE IF EXISTS+ TABLE_CONTACTS);        //再次创建表
        的onCreate(DB);
    }    / **
     *所有CRUD(创建,读取,更新,删除)操作
     * /    //添加新值
    无效addvalues​​(价值的LatLong){
        SQLiteDatabase分贝= this.getWritableDatabase();        ContentValues​​值=新ContentValues​​();
        values​​.put(KEY_LAT,value.get_lat()); // 联系人姓名
        values​​.put(KEY_LONG,value.get_long()); // 联系电话        //插入行
        db.insert(TABLE_CONTACTS,空,价值);
        db.close(); //关闭数据库连接
    }
}

我的日志猫

  13 12-30:59:49.040:D / gralloc_goldfish(1411):无仿真模拟GPU检测。
12-30 13:59:50.960:D / GPS功能的(1411):启用GPS
12-30 13:59:50.980:D / AndroidRuntime(1411):关闭VM
12-30 13:59:50.980:W / dalvikvm(1411):主题ID = 1:螺纹未捕获的异常(组= 0xb3a6aba8)退出
12-30 13:59:50.990:E / AndroidRuntime(1411):致命异常:主要
12-30 13:59:50.990:E / AndroidRuntime(1411):工艺:com.example.gpstracking,PID:1411
12-30 13:59:50.990:E / AndroidRuntime(1411):显示java.lang.NullPointerException
12-30 13:59:50.990:E / AndroidRuntime(1411):在com.example.gpstracking.AndroidGPSTrackingActivity $ 1.onClick(AndroidGPSTrackingActivity.java:46)
12-30 13:59:50.990:E / AndroidRuntime(1411):在android.view.View.performClick(View.java:4438)
12-30 13:59:50.990:E / AndroidRuntime(1411):在android.view.View $ PerformClick.run(View.java:18422)
12-30 13:59:50.990:E / AndroidRuntime(1411):在android.os.Handler.handleCallback(Handler.java:733)
12-30 13:59:50.990:E / AndroidRuntime(1411):在android.os.Handler.dispatchMessage(Handler.java:95)
12-30 13:59:50.990:E / AndroidRuntime(1411):在android.os.Looper.loop(Looper.java:136)
12-30 13:59:50.990:E / AndroidRuntime(1411):在android.app.ActivityThread.main(ActivityThread.java:5001)
12-30 13:59:50.990:E / AndroidRuntime(1411):在java.lang.reflect.Method.invokeNative(本机方法)
12-30 13:59:50.990:E / AndroidRuntime(1411):在java.lang.reflect.Method.invoke(Method.java:515)
12-30 13:59:50.990:E / AndroidRuntime(1411):在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:785)
12-30 13:59:50.990:E / AndroidRuntime(1411):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
12-30 13:59:50.990:E / AndroidRuntime(1411):在dalvik.system.NativeStart.main(本机方法)
12-30 13:59:55.950:I /流程(1411):发送信号。 PID:1411 SIG:9

这是我的GPSTracker类

 包com.example.gpstracking;进口android.app.AlertDialog;
进口android.app.Service;
进口android.content.Context;
进口android.content.DialogInterface;
进口android.content.Intent;
进口android.location.Location;
进口android.location.LocationListener;
进口android.location.LocationManager;
进口android.os.Bundle;
进口android.os.IBinder;
进口android.provider.Settings;
进口android.util.Log;公共类GPSTracker扩展服务实现LocationListener的{    私人最终上下文mContext;    //标志GPS状态
    布尔isGPSEnabled = FALSE;    //标志网络状态
    布尔isNetworkEnabled = FALSE;    //标志GPS状态
    布尔canGetLocation = FALSE;    地点位置; // 位置
    双纬度; //纬度
    双经度; //经度    //最小距离改变米的更新
    私有静态最后长MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; //10米    //毫秒更新之间的最短时间
    私有静态最后长MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1分钟    //声明一个位置管理
    受保护的LocationManager的LocationManager;    公共GPSTracker(上下文的背景下){
        this.mContext =背景;
        的getLocation();
    }    公共场所的getLocation(){
        尝试{
            的LocationManager =(的LocationManager)mContext
                    .getSystemService(LOCATION_SERVICE);            //获取GPS状态
            isGPSEnabled =的LocationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);            //获取网络状态
            isNetworkEnabled =的LocationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);            如果(isGPSEnabled&安培;!&安培;!isNetworkEnabled){
                //没有启用网络供应商
            }其他{
                this.canGetLocation = TRUE;
                //首先从网络提供商处获取位置
                如果(isNetworkEnabled){
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES,这一点);
                    Log.d(网络,网络);
                    如果(的LocationManager!= NULL){
                        位置=的LocationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        如果(位置!= NULL){
                            纬度= location.getLatitude();
                            经度= location.getLongitude();
                        }
                    }
                }
                //如果GPS功能的获得纬度/长期使用GPS服务
                如果(isGPSEnabled){
                    如果(位置== NULL){
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES,这一点);
                        Log.d(GPS已启用,GPS功能的);
                        如果(的LocationManager!= NULL){
                            位置=的LocationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            如果(位置!= NULL){
                                纬度= location.getLatitude();
                                经度= location.getLongitude();
                            }
                        }
                    }
                }
            }        }赶上(例外五){
            e.printStackTrace();
        }        返回的位置;
    }    / **
     *停止使用GPS监听器
     *调用此函数将停止在你的应用程序中使用GPS
     * * /
    公共无效stopUsingGPS(){
        如果(的LocationManager!= NULL){
            locationManager.removeUpdates(GPSTracker.this);
        }
    }    / **
     *函数来获取纬度
     * * /
    公共双getLatitude(){
        如果(位置!= NULL){
            纬度= location.getLatitude();
        }        //返回纬度
        返回纬度;
    }    / **
     *函数来获取经度
     * * /
    公共双getLongitude(){
        如果(位置!= NULL){
            经度= location.getLongitude();
        }        //返回经度
        返回经度;
    }    / **
     *功能检查启用GPS / WIFI
     * @返回布尔
     * * /
    公共布尔canGetLocation(){
        返回this.canGetLocation;
    }    / **
     *功能,以显示设置警告对话框
     *在pressing设置按钮将劳克设置选项
     * * /
    公共无效showSettingsAlert(){
        AlertDialog.Builder alertDialog =新AlertDialog.Builder(mContext);        //设置对话框标题
        alertDialog.setTitle(GPS是设置);        //设置对话框留言
        alertDialog.setMessage(GPS未启用你想要去设置菜单?);        //在pressing设置按钮
        alertDialog.setPositiveButton(设置,新DialogInterface.OnClickListener(){
            公共无效的onClick(DialogInterface对话,诠释它){
                意向意图=新意图(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(意向);
            }
        });        //在pressing取消按钮
        alertDialog.setNegativeButton(取消,新DialogInterface.OnClickListener(){
            公共无效的onClick(DialogInterface对话,诠释它){
            dialog.cancel();
            }
        });        //显示警报信息
        alertDialog.show();
    }
    @覆盖
    公共无效onLocationChanged(地点){
    }    @覆盖
    公共无效onProviderDisabled(字符串提供商){
    }    @覆盖
    公共无效onProviderEnabled(字符串提供商){
    }    @覆盖
    公共无效onStatusChanged(字符串提供商,INT地位,捆绑演员){
    }    @覆盖
    公众的IBinder onBind(意向为arg0){
        返回null;
    }}

下面是我的Andr​​oid活动

 包com.example.gpstracking;进口android.app.Activity;
进口android.os.Bundle;
进口android.view.View;
进口android.widget.Button;
进口android.widget.Toast;公共类AndroidGPSTrackingActivity延伸活动{    按钮btnShowLocation;    // GPSTracker类
    GPSTracker GPS;    @覆盖
    公共无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_main);        btnShowLocation =(按钮)findViewById(R.id.btnShowLocation);        //展示位置按钮单击事件
        btnShowLocation.setOnClickListener(新View.OnClickListener(){            @覆盖
            公共无效的onClick(查看为arg0){
                //创建类对象
                GPS =新GPSTracker(AndroidGPSTrackingActivity.this);                //检查是否启用GPS
                如果(gps.canGetLocation()){                    双纬度= gps.getLatitude();
                    双经度= gps.getLongitude();                    // \\ n是新行
                    Toast.makeText(getApplicationContext(),您现在的位置是 - \\ nLat:+纬度+\\ nLong:+经度,Toast.LENGTH_LONG).show();
                }其他{
                    //无法获取位置
                    未启用// GPS或网络
                    //要求用户在设置中启用GPS /网络
                    gps.showSettingsAlert();
                }            }
        });
    }}


解决方案

喜使用以下code:

步骤1创建以下类LatLong.java:

 公共类的LatLong {    //私有变量
    INT _id;
    串_lat;
    串_long;
    //空的构造
    公众的LatLong(){    }
    //构造
    公众的LatLong(INT ID,字符串纬度,经度字符串){
        this._id = ID;
        this._lat =纬度;
        this._long =经度;
    }    //构造
    公众的LatLong(字符串纬度,经度字符串){
        this._lat =纬度;
        this._long =经度;
    }
    //获取ID
    公众诠释的getID(){
        返回this._id;
    }    //设置ID
    公共无效SETID(INT ID){
        this._id = ID;
    }    公共字符串get_lat(){
        返回_lat;
    }
    公共无效set_lat(字符串_lat){
        this._lat = _lat;
    }
    公共字符串get_long(){
        返回_long;
    }
    公共无效set_long(字符串_long){
        this._long = _long;
    }}

第2步:创建以下DB类:DatabaseHandler.java

 进口android.content.ContentValues​​;
进口android.content.Context;
进口android.database.sqlite.SQLiteDatabase;
进口android.database.sqlite.SQLiteOpenHelper;公共类数据库处理器扩展SQLiteOpenHelper {    //所有静态变量
    //数据库版本
    私有静态最终诠释DATABASE_VERSION = 1;    //数据库名称
    私有静态最后弦乐DATABASE_NAME =GPS;    //联系人表名
    私有静态最后弦乐TABLE_CONTACTS =gracking;    //联系方式表列名
    私有静态最后弦乐KEY_ID =ID;
    私有静态最后弦乐KEY_LAT =纬度;
    私有静态最后弦乐KEY_LONG =长;    公共数据库处理器(上下文的背景下){
        超(背景下,DATABASE_NAME,空,DATABASE_VERSION);
    }    //创建表
    @覆盖
    公共无效的onCreate(SQLiteDatabase DB){
        字符串CREATE_CONTACTS_TABLE =CREATE TABLE+ TABLE_CONTACTS +(
                + KEY_ID +INTEGER PRIMARY KEY,+ KEY_LAT +TEXT
                + KEY_LONG +TEXT+);
        db.execSQL(CREATE_CONTACTS_TABLE);
    }    //数据库升级
    @覆盖
    公共无效onUpgrade(SQLiteDatabase分贝,INT oldVersion,诠释静态网页){
        如果存在//删除旧的表
        db.execSQL(DROP TABLE IF EXISTS+ TABLE_CONTACTS);        //再次创建表
        的onCreate(DB);
    }    / **
     *所有CRUD(创建,读取,更新,删除)操作
     * /    //添加新值
    无效addvalues​​(价值的LatLong){
        SQLiteDatabase分贝= this.getWritableDatabase();        ContentValues​​值=新ContentValues​​();
        values​​.put(KEY_LAT,value.get_lat()); // 联系人姓名
        values​​.put(KEY_LONG,value.get_long()); // 联系电话        //插入行
        db.insert(TABLE_CONTACTS,空,价值);
        db.close(); //关闭数据库连接
    }
}

第三步:添加以下code在你的类:

  btnShowLocation.setOnClickListener(新View.OnClickListener(){            @覆盖
            公共无效的onClick(查看为arg0){
                //创建类对象
                GPS =新GPSTracker(AndroidGPSTrackingActivity.this);                //检查是否启用GPS
                如果(gps.canGetLocation()){                    双纬度= gps.getLatitude();
                    双经度= gps.getLongitude();
  数据库处理器DB =新的数据库处理器(本);        / **
         * CRUD操作
         * * /
        //插入latlongs
        Log.d(插入,插入..);
        db.addvalues​​(新的LatLong(latvalue,的longValue));                    Toast.makeText(getApplicationContext(),您现在的位置是 - \\ nLat:+纬度+\\ nLong:+经度,Toast.LENGTH_LONG).show();
                }其他{
                    //无法获取位置
                    未启用// GPS或网络
                    //要求用户在设置中启用GPS /网络
                    gps.showSettingsAlert();
                }            }
        });

enter image description hereI am making a simple android app to get the location of an android user and I need to send the latitude and longitude to the MySQL database. How can I do that with this kind of code segment?

DatabaseHandler class

package com.example.gpstracking;

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



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 = "gps";

    // Contacts table name
    private static final String TABLE_CONTACTS = "location";

    // Contacts Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_LAT = "lat";
    private static final String KEY_LONG = "long";

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

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
                + KEY_ID + " INTEGER PRIMARY KEY," + KEY_LAT + " TEXT,"
                + KEY_LONG + " TEXT" + ")";
        db.execSQL(CREATE_CONTACTS_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_CONTACTS);

        // Create tables again
        onCreate(db);
    }

    /**
     * All CRUD(Create, Read, Update, Delete) Operations
     */

    // Adding new values
    void addvalues(LatLong value) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_LAT, value.get_lat()); // Contact Name
        values.put(KEY_LONG,  value.get_long()); // Contact Phone

        // Inserting Row
        db.insert(TABLE_CONTACTS, null, values);
        db.close(); // Closing database connection
    }


}

My log cat

12-30 13:59:49.040: D/gralloc_goldfish(1411): Emulator without GPU emulation detected.
12-30 13:59:50.960: D/GPS Enabled(1411): GPS Enabled
12-30 13:59:50.980: D/AndroidRuntime(1411): Shutting down VM
12-30 13:59:50.980: W/dalvikvm(1411): threadid=1: thread exiting with uncaught exception (group=0xb3a6aba8)
12-30 13:59:50.990: E/AndroidRuntime(1411): FATAL EXCEPTION: main
12-30 13:59:50.990: E/AndroidRuntime(1411): Process: com.example.gpstracking, PID: 1411
12-30 13:59:50.990: E/AndroidRuntime(1411): java.lang.NullPointerException
12-30 13:59:50.990: E/AndroidRuntime(1411):     at com.example.gpstracking.AndroidGPSTrackingActivity$1.onClick(AndroidGPSTrackingActivity.java:46)
12-30 13:59:50.990: E/AndroidRuntime(1411):     at android.view.View.performClick(View.java:4438)
12-30 13:59:50.990: E/AndroidRuntime(1411):     at android.view.View$PerformClick.run(View.java:18422)
12-30 13:59:50.990: E/AndroidRuntime(1411):     at android.os.Handler.handleCallback(Handler.java:733)
12-30 13:59:50.990: E/AndroidRuntime(1411):     at android.os.Handler.dispatchMessage(Handler.java:95)
12-30 13:59:50.990: E/AndroidRuntime(1411):     at android.os.Looper.loop(Looper.java:136)
12-30 13:59:50.990: E/AndroidRuntime(1411):     at android.app.ActivityThread.main(ActivityThread.java:5001)
12-30 13:59:50.990: E/AndroidRuntime(1411):     at java.lang.reflect.Method.invokeNative(Native Method)
12-30 13:59:50.990: E/AndroidRuntime(1411):     at java.lang.reflect.Method.invoke(Method.java:515)
12-30 13:59:50.990: E/AndroidRuntime(1411):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
12-30 13:59:50.990: E/AndroidRuntime(1411):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
12-30 13:59:50.990: E/AndroidRuntime(1411):     at dalvik.system.NativeStart.main(Native Method)
12-30 13:59:55.950: I/Process(1411): Sending signal. PID: 1411 SIG: 9

here is my GPSTracker class

package com.example.gpstracking;

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;

public class GPSTracker extends Service implements LocationListener {

    private final Context mContext;

    // flag for GPS status
    boolean isGPSEnabled = false;

    // flag for network status
    boolean isNetworkEnabled = false;

    // flag for GPS status
    boolean canGetLocation = false;

    Location location; // location
    double latitude; // latitude
    double longitude; // longitude

    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

    // Declaring a Location Manager
    protected LocationManager locationManager;

    public GPSTracker(Context context) {
        this.mContext = context;
        getLocation();
    }

    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);

            // getting GPS status
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);

            // getting network status
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                this.canGetLocation = true;
                // First get location from Network Provider
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return location;
    }

    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app
     * */
    public void stopUsingGPS(){
        if(locationManager != null){
            locationManager.removeUpdates(GPSTracker.this);
        }       
    }

    /**
     * Function to get latitude
     * */
    public double getLatitude(){
        if(location != null){
            latitude = location.getLatitude();
        }

        // return latitude
        return latitude;
    }

    /**
     * Function to get longitude
     * */
    public double getLongitude(){
        if(location != null){
            longitude = location.getLongitude();
        }

        // return longitude
        return longitude;
    }

    /**
     * Function to check GPS/wifi enabled
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }

    /**
     * Function to show settings alert dialog
     * On pressing Settings button will lauch Settings Options
     * */
    public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        // Setting Dialog Title
        alertDialog.setTitle("GPS is settings");

        // Setting Dialog Message
        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

        // On pressing Settings button
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });

        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }


    @Override
    public void onLocationChanged(Location location) {
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

}

Here is my Android Activity

package com.example.gpstracking;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class AndroidGPSTrackingActivity extends Activity {

    Button btnShowLocation;

    // GPSTracker class
    GPSTracker gps;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnShowLocation = (Button) findViewById(R.id.btnShowLocation);

        // show location button click event
        btnShowLocation.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {        
                // create class object
                gps = new GPSTracker(AndroidGPSTrackingActivity.this);

                // check if GPS enabled     
                if(gps.canGetLocation()){

                    double latitude = gps.getLatitude();
                    double longitude = gps.getLongitude();

                    // \n is for new line
                    Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();    
                }else{
                    // can't get location
                    // GPS or Network is not enabled
                    // Ask user to enable GPS/network in settings
                    gps.showSettingsAlert();
                }

            }
        });
    }

}

解决方案

hi use the following code:

Step 1 Create the following class LatLong.java:

public class LatLong {

    //private variables
    int _id;
    String _lat;
    String _long;


    // Empty constructor
    public LatLong(){

    }
    // constructor
    public LatLong(int id, String latitude, String longitude){
        this._id = id;
        this._lat = latitude;
        this._long = longitude;
    }

    // constructor
    public LatLong(String latitude, String longitude){
        this._lat = latitude;
        this._long = longitude;
    }
    // getting ID
    public int getID(){
        return this._id;
    }

    // setting id
    public void setID(int id){
        this._id = id;
    }

    public String get_lat() {
        return _lat;
    }
    public void set_lat(String _lat) {
        this._lat = _lat;
    }
    public String get_long() {
        return _long;
    }
    public void set_long(String _long) {
        this._long = _long;
    }

}

Step 2:Create the following db class:DatabaseHandler.java

import android.content.ContentValues;
import android.content.Context;


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

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 = "gps";

    // Contacts table name
    private static final String TABLE_CONTACTS = "gracking";

    // Contacts Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_LAT = "lat";
    private static final String KEY_LONG = "long";

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

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
                + KEY_ID + " INTEGER PRIMARY KEY," + KEY_LAT + " TEXT,"
                + KEY_LONG + " TEXT" + ")";
        db.execSQL(CREATE_CONTACTS_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_CONTACTS);

        // Create tables again
        onCreate(db);
    }

    /**
     * All CRUD(Create, Read, Update, Delete) Operations
     */

    // Adding new values
    void addvalues(LatLong value) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_LAT, value.get_lat()); // Contact Name
        values.put(KEY_LONG,  value.get_long()); // Contact Phone

        // Inserting Row
        db.insert(TABLE_CONTACTS, null, values);
        db.close(); // Closing database connection
    }


}

Step 3:Add the following code in your class:

 btnShowLocation.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {        
                // create class object
                gps = new GPSTracker(AndroidGPSTrackingActivity.this);

                // check if GPS enabled     
                if(gps.canGetLocation()){

                    double latitude = gps.getLatitude();
                    double longitude = gps.getLongitude();


  DatabaseHandler db = new DatabaseHandler(this);

        /**
         * CRUD Operations
         * */
        // Inserting latlongs
        Log.d("Insert: ", "Inserting ..");
        db.addvalues(new LatLong("latvalue", "longvalue"));

                    Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();    
                }else{
                    // can't get location
                    // GPS or Network is not enabled
                    // Ask user to enable GPS/network in settings
                    gps.showSettingsAlert();
                }

            }
        });

这篇关于如何发送纬度和经度从机器人到MySQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆