2015-12-21 185 views
1

enter image description here我正在制作一个简单的android应用程序来获取android用户的位置,我需要将纬度和经度发送到MySQL数据库。我怎么用这种代码段来做到这一点?如何将纬度和经度从android发送到Mysql

数据库处理器类

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

      } 
     }); 
    } 

} 
+0

什么问题,你所面对? –

+0

从这段代码我正在获取纬度和经度正确的对话框。但我想知道如何我可以将它们传递给Mysql数据库。我也写了一个PHP脚本。 – joseph

+0

你好。你有在你的本地数据库中创建的表,或者你有任何服务将它发送到mysql db.here有两种方法我们可以做。让我知道清楚,以便我可以给你示例的例子。 – ManiTeja

回答

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

} 

第2步:创建以下db cl屁股: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(); 
       } 

      } 
     }); 
+0

在我的主类我得到一个错误,说“构造函数DatabaseHandler(新View.OnClickListener(){})是不确定的”作为建议我创建超级onclistner然后也给了我同样的错误。 – joseph

+0

不需要创建。你创建了我所给的db类。 – ManiTeja

+0

将DatabaseHandler导入到您的主要class.dont中创建任何其他东西。它是boss的基本问题。您需要考虑一次 – ManiTeja

1

您需要通过http协议将纬度和经度发送到您的服务器,也就是说您应该使用像Volley或OKHttp这样的网络连接框架连接您的服务器并将此信息发送到您的服务器,然后您的服务器可以获得纬度和经度并将其更新到Mysql数据库,则无法直接将其写入Mysql数据库。

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

+0

任何示例plzzzzzzz – joseph

+0

@ joseph,对不起,我不知道你的数据库是如何设计的,不要给你具体的代码,但我可以给你一步做出来。请看我更新的答案。 – starkshang

1

请使用下面的代码来插入纬度,登录本地数据库。

//展示位置按钮单击事件

 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例如按你的逻辑

+0

当我尝试这段代码我有一些日志猫错误和应用程序已停止,实际上我是新的android如何创建dbm实例 – joseph

+0

如何创建db结构。让我知道。或让我知道错误你是什么getting.so,我可以帮你 – ManiTeja

+0

数据库名称是GPS。表名是位置,有三个字段id,它们是自动递增的,另外两个字段是纬度和经度(双精度)。 – joseph