0

我是 android 和 json 的新手。我想使用 json 将一些数据从 android 发布并返回到我的 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 代码中看到, $latitude = $_POST['GPSlat'];$longitude = $_POST['GPSlng']; 那么我想从 android 获取我的纬度和经度并发送到GPSlatGPSlng执行sql查询并使用json显示它。有没有例子或教程?谢谢

这是我的安卓代码

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

}

4

1 回答 1

0

Check out this.. Android: Server-client programming

Here you can see the usage of NameValuePair for info passing. And also, the network operations must be in different thread, preferably in AsyncTask.

于 2013-06-04T17:40:55.307 回答