android - 如何使用 json 将 GPS 坐标从 android 发布到数据库

标签 android mysql json

我是 android 和 json 新手。我想使用 json 将我的 Android GPS 坐标发布到我的 php。

这是我的 php。

  <?php

$response = array();

 include_once('C:\xampp\htdocs\RS\connection.php');

  $latitude = $_POST[GPSlat];
  $longitude = $_POST[GPSlng];

$result = mysql_query("SELECT nama_rs, telepon, lat, lng, ( 3959 * acos( cos( radians('$latitude') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('$longitude') ) + sin( radians('$latitude') ) * sin( radians( lat ) ) ) ) AS distance FROM datars HAVING distance < 2 ORDER BY distance LIMIT 0 , 1") or die(mysql_error());



if (mysql_num_rows($result) > 0) {

    $response["peta_rs"] = array();

    while ($row = mysql_fetch_array($result)) {

        $peta_rs = array();
        $peta_rs["nama"] = stripslashes($row["nama_rs"]);
        $peta_rs["telepon_rs"] = stripslashes($row["telepon"]);
        $peta_rs["lintang_rs"] = stripslashes($row["lat"]);
        $peta_rs["bujur_rs"] = stripslashes($row["lng"]);

        array_push($response["peta_rs"], $peta_rs);
    }

    $response["success"] = 1;

    echo json_encode($response);
} else {

    $response["success"] = 0;
    $response["message"] = "error";

    echo json_encode($response);
}
?>

如果你在我的 php 代码中看到 $纬度 = $_POST[GPSlat];$经度 = $_POST[GPSlng]; 所以我想从android获取我的纬度和经度并发送到GPSlatGPSlng来执行sql查询并使用json显示它。我已经可以使用 locationmanager 显示我的纬度和经度。有什么例子或教程吗?谢谢

这是我的 Android 代码端

public class Callrs extends Activity {
private LocationManager locationManager;
private LocationListener locationListener;


 private ProgressDialog pDialog;


    JSONParser jParser = new JSONParser();


    private static String url_peta_rs = "http://192.168.199.1/RS/callrs.php";

    private static final String TAG_SUCCESS = "success";
    private static final String TAG_PETA_RS = "peta_rs";
    public static final String TAG_NAMA_RS = "nama";
    public static final String TAG_TELEPON_RS = "telepon_rs";
    public static final String TAG_LINTANG_RS = "lintang_rs";
    public static final String TAG_BUJUR_RS = "bujur_rs";

    final Location locationA = new Location("point A");
    final Location locationB = new Location("point B");


    ProgressDialog dialog;

    JSONArray peta_rs = null;
    private LocationManager locManager;
    private LocationListener locListener;
    private ArrayList<Telepon> list_fasilitas = new ArrayList<Telepon>();

    ListenToPhoneState listener;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        CurrentLocation();
        new Activity().execute();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == 100) {

            Intent intent = getIntent();
            finish();
            startActivity(intent);
        }

    }

    class Activity extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            pDialog = new ProgressDialog(Callrs.this);
            pDialog.setMessage("Mohon tunggu...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        protected String doInBackground(String... args) {

            postData();

            List<NameValuePair> params = new ArrayList<NameValuePair>();

             JSONObject json = jParser.makeHttpRequest(url_peta_rs,
                    "GET", params);

            Log.d("peta_rs: ", json.toString());

            try {
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {

                    peta_rs = json.getJSONArray(TAG_PETA_RS);

                    for (int i = 0; i < peta_rs.length(); i++) {
                        JSONObject c = peta_rs.getJSONObject(i);

                        String nama_rs = c.getString(TAG_NAMA_RS);
                        String telepon_rs = c.getString(TAG_TELEPON_RS);
                        double lintang_rs = c.getDouble(TAG_LINTANG_RS);
                        double bujur_rs = c.getDouble(TAG_BUJUR_RS);



                        list_fasilitas.add(new Telepon(nama_rs,telepon_rs,
                                        lintang_rs, bujur_rs));
                    }
                } else {

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

            return null;

        }


         protected void onPostExecute(String file_url) {


            pDialog.dismiss();

        }

    }       


  public void CurrentLocation()
  {
      locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);  

      locationListener = new GPSLocationListener();

      locationManager.requestLocationUpdates(
        LocationManager.NETWORK_PROVIDER, 
        0, 
        0, 
        locationListener);

  }

  private class GPSLocationListener implements LocationListener 
  {

    public void onLocationChanged(Location location) {

        if (location != null) {
        GeoPoint pointA = new GeoPoint(
            (int) (location.getLatitude() * 1E6), 
            (int) (location.getLongitude() * 1E6)); 

        locationA.setLatitude(pointA.getLatitudeE6() / 1E6);
        locationA.setLongitude(pointA.getLongitudeE6() / 1E6);


        Toast.makeText(getBaseContext(), 
            "Latitude: " + location.getLatitude() + 
            " Longitude: " + location.getLongitude(), 
            Toast.LENGTH_LONG).show();

        /////////////////////
            for (int i = 0; i < list_fasilitas.size(); i++) {

            // transform the location to a geopoint
            GeoPoint pointB = new GeoPoint(
                    (int) (list_fasilitas.get(i).lintang_rs * 1E6),
                    (int) (list_fasilitas.get(i).bujur_rs * 1E6));
            locationB.setLatitude(pointB.getLatitudeE6() / 1E6);
            locationB.setLongitude(pointB.getLongitudeE6() / 1E6);

            DecimalFormat formatData = new DecimalFormat("#.#");
            float distance = (float) locationA.distanceTo(locationB) / 1000;
            String jarak;
            jarak = String.valueOf(formatData.format(distance));

            Toast.makeText(Callrs.this, ""+list_fasilitas.get(i).nama_rs, Toast.LENGTH_LONG).show();

                try {
                    Intent callIntent = new Intent(Intent.ACTION_CALL);
                    callIntent.setData(Uri.parse("tel:"+list_fasilitas.get(i).telepon_rs));
                    startActivity(callIntent);

                    ///
                    TelephonyManager tManager = (TelephonyManager) 
                            getSystemService(Context.TELEPHONY_SERVICE);
                          listener = new ListenToPhoneState();
                          tManager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
                    ///
                } catch (ActivityNotFoundException activityException) {
                    Log.e("dialing-example", "Call failed", activityException);
                }

        }
        /////////////////////



      }
    }

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

    }

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

    }

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

    }


  }



  public void postData() {
        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://192.168.199.1/RS/callrs.php");

        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("GPSlat", "-7.772354"));
            nameValuePairs.add(new BasicNameValuePair("GPSlng", "110.351565"));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            String res = EntityUtils.toString(entity);

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }
    } 

}

最佳答案

请看HERE对于 POST 请求。 在你的情况下,它应该看起来像:

public void postData() {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("C:\xampp\htdocs\RS\connection.php");

    try {
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("GPSlat", "48.8566140"));
        nameValuePairs.add(new BasicNameValuePair("GPSlng", "2.3522219"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);


    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }
} 

我看到你的 PHP 返回了一些数据,你可以通过将下面的代码放在代码中来获取它

HttpResponse 响应 = httpclient.execute(httppost);

HttpEntity entity = response.getEntity();
String res = EntityUtils.toString(entity);

关于android - 如何使用 json 将 GPS 坐标从 android 发布到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16914537/

相关文章:

mysql - 为什么我的 WHERE 和 COUNT 子句不起作用?

javascript - Angular 选择器问题

json - 将 JSON 转换为 GeoJSON 前端

android - 如何在午夜更新应用程序小部件?

android - 无法从 Assets /SQLiteOpenHelper 中复制数据库

php - symfony 中的多重连接 : Error: Expected =, <, <=, <>, >, >=, !=

ios - 我应该在哪里保存 iOS 中的本地 JSON 文件?

java - 在 android studio/IntelliJ IDEA 中使用标记接口(interface)

java - 在运行时更新和删除 GridView 项目

php - mysql php评论系统: new database or looping through ids?