【问题标题】:How to send latitude and longitude from Android to Mysql如何将经纬度从Android发送到Mysql
【发布时间】:2015-12-21 07:57:13
【问题描述】:


我正在制作一个简单的 Android 应用程序来获取 Android 用户的位置,我需要将纬度和经度发送到 MySQL 数据库。我怎样才能用这种代码段做到这一点?

DatabaseHandler 类

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
    }


}

我的原木猫

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

这是我的 GPSTracker 类

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;
    }

}

这是我的 Android 活动

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();
                }

            }
        });
    }

}

【问题讨论】:

  • 你面临什么问题?
  • 从这个代码段中,我在对话框中正确获取了纬度和经度。但我想知道如何将它们传递给 Mysql 数据库。我也编写了一个 php 脚本。
  • 嗨。您是否在本地数据库中创建了表,或者您是否有任何服务可以将其发送到 mysql db。这里有两种方法我们可以做。让我清楚地知道,以便我可以给你示例。
  • @ManiTeja 是的,我已经在本地数据库中创建了我的表
  • @ManiTeja 我已经更新了我的日志猫,请查看

标签: android mysql android-layout android-intent


【解决方案1】:

使用以下代码:

步骤 1 创建以下类 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;
    }

}

第二步:创建如下db类: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
    }


}

第 3 步:在您的类中添加以下代码:

 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();
                }

            }
        });

【讨论】:

  • 在我的主课上,我收到一条错误消息,提示“构造函数 DatabaseHandler(new View.OnClickListener(){}) 未定义”,因为这表明我已经创建了超级 onclistner,然后也给了我同样的错误。
  • 不需要创建。你创建了我给的db类吗。
  • 将DatabaseHandler导入到你的主类中。不要创建任何其他东西。这是基本问题boss。你需要考虑一次
  • 你能把你的课程发给我一次吗?你是按照我给的DatabaseHandler.java创建的吗?在activity.DatabaseHandler db中试试这个;点击。 db = new DatabaseHandler(this);
  • 更新你的活动类。你在哪里得到错误。那个类
【解决方案2】:

请使用以下代码插入lat,登录本地数据库。

//显示位置按钮点击事件

       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();
SQLiteDatabase dbm = this.getWritableDatabase();
                 ContentValues cv = new ContentValues();


                cv.put("LAT_G",
                        gps.getLatitude());

                cv.put("LANG",  gps.getLongitude());

                boolean result = dbm.insert("table name", cv);


                    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();
                }

            }
        });

注意:需要根据你的逻辑创建你的 dbm 实例

【讨论】:

  • 当我尝试这段代码时,我遇到了一些 log cat 错误并且应用程序已停止,实际上我是 android 新手,如何创建 dbm 实例
  • 您是如何创建数据库结构的。让我知道。或者让我知道您遇到的错误。以便我可以帮助您
  • 数据库名称是 gps。并且表名是位置。有三个字段 id 是自动递增的,另外两个字段是纬度和经度(双精度)。
  • 我已经更新了日志猫请看一下。点击按钮时出现错误
  • 您好,请使用我发布 2 次的代码。我测试了这段代码,它可以正常插入。
【解决方案3】:

您需要通过http协议将经纬度发送到您的服务器,即您应该使用Volley或OKHttp等网络连接框架连接您的服务器并将此信息发送到您的服务器,然后您的服务器可以获取纬度和经度更新到Mysql数据库,不能直接写入Mysql数据库。

既然你得到了正确的数据,那么之后你只做以下两件事:
1.编写一个接收纬度和经度作为参数的函数,将此数据写入您的mysql数据库。
2.使用Volley或者OKHttp或者其他你熟悉的网络通讯工具将经纬度发送到你的php脚本中(已经在step1中做了)。例如,如果你使用Volley,可以参考这个doc

【讨论】:

  • 任何例子 plzzzzzzz
  • @joseph,对不起,我不知道你的数据库是如何设计的,所以我不能给出你的具体代码,但我可以给你制作它的步骤。请看我更新的答案.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-19
  • 2016-03-15
  • 2019-12-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多