php - 从android发送数据( double 类型)到mysql

标签 php android mysql

我有一个 Android 应用程序可以恢复 GPS 坐标(经度、纬度),然后我想将这些坐标发送到我的数据库!然后之间的连接已设置,但我的经度始终为“零”,纬度为“零”???

这是我的 MainActivity.java 代码:

    package gps.com.gps;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


public class MainActivity extends AppCompatActivity {

private String URL_NEW_LOCATION = "http://10.0.3.2/T.T.P/gps/gps_a001.php";
private Button btnAddLocation;

private LocationManager objgps;
private LocationListener objlistener;
private TextView mTxtViewlong;
private TextView mTxtViewlat;

/*private double gpsLongN  ;
private double gpsLatiN  ;*/

private String gpsLong  ;
private String gpsLati ;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //---utilisation  de la class LocationManager pour le gps---
    objgps = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    //*************ecouteur ou listener*********************
    objlistener = new Myobjlistener();

    objgps.requestLocationUpdates(
            LocationManager.GPS_PROVIDER,
            0,
            0,
            objlistener);
    //**variable qui pointe sur  mes champs d'affichage*************

    mTxtViewlong = (TextView) findViewById(R.id.textlong);
    gpsLong = mTxtViewlong.getText().toString();

    mTxtViewlat = (TextView) findViewById(R.id.textlat);
    gpsLati = mTxtViewlat.getText().toString();

    btnAddLocation = (Button) findViewById(R.id.submit);


   /* gpsLongN = Double.parseDouble(gpsLong);
    gpsLatiN = Double.parseDouble(gpsLati);*/


    btnAddLocation.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub

            new AddNewLocation().execute(gpsLong, gpsLati);
        }
    });


}

private class Myobjlistener implements LocationListener
{



    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 onLocationChanged(Location location) {

        //affichage des valeurs dans la les zone de saisie
        mTxtViewlat.setText(" "+location.getLatitude());
        mTxtViewlong.setText(" "+location.getLongitude());
    }

}






private class AddNewLocation extends AsyncTask<String, Void, Void> {

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

    }

    @Override
    protected Void doInBackground(String... arg) {
        // TODO Auto-generated method stub
        String longitude = arg[0];
        String latitude = arg[1];


        // Preparing post params
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("longitude" , longitude));
        params.add(new BasicNameValuePair("latitude", latitude));


        ServiceHandler serviceClient = new ServiceHandler();

        String json = serviceClient.makeServiceCall(URL_NEW_LOCATION,
                ServiceHandler.POST, params);

        Log.d("Create Location: ", "> " + json);

        if (json != null) {
            try {
                JSONObject jsonObj = new JSONObject(json);
                boolean error = jsonObj.getBoolean("error");
                // checking for error node in json
                if (!error) {
                    // new category created successfully
                    Log.e("Location added  ",
                            "> " + jsonObj.getString("message"));
                } else {
                    Log.e("Add Location Error: ",
                            "> " + jsonObj.getString("message"));
                }

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

        } else {
            Log.e("JSON Data", "JSON data error!");
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
    }
}

     }

这是 ServiceHandler.java 类:

     package gps.com.gps;

/**
 * Created by RaddadiM on 21/06/2017.
 */


import android.util.Log;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;



public class ServiceHandler {

static InputStream is = null;
static String response = null;
public final static int GET = 1;
public final static int POST = 2;

public ServiceHandler() {

}

public String makeServiceCall(String url, int method) {
    return this.makeServiceCall(url, method, null);
}


public String makeServiceCall(String url, int method,
                              List<NameValuePair> params) {
    try {

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpEntity httpEntity = null;
        HttpResponse httpResponse = null;


        if (method == POST) {
            HttpPost httpPost = new HttpPost(url);

            if (params != null) {
                httpPost.setEntity(new UrlEncodedFormEntity(params));
            }

            httpResponse = httpClient.execute(httpPost);

        } else if (method == GET) {

            if (params != null) {
                String paramString = URLEncodedUtils
                        .format(params, "utf-8");
                url += "?" + paramString;
            }
            HttpGet httpGet = new HttpGet(url);

            httpResponse = httpClient.execute(httpGet);

        }
        httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "UTF-8"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        response = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error: " + e.toString());
    }

    return response;
}
}

这是我的 xml 代码:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="gps.com.gps.MainActivity"
tools:showIn="@layout/activity_main">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/textlong"
    android:layout_below="@+id/editText"
    android:layout_alignStart="@+id/textlat"
    android:layout_alignLeft="@+id/textlat"
    android:layout_marginTop="49dp" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/textlat"
    android:layout_marginTop="157dp"
    android:layout_below="@+id/textlong"
    android:layout_centerHorizontal="true" />

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/editText"
    android:text="coordLong"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true" />

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/editText2"
    android:layout_alignBottom="@+id/textlat"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="53dp"
    android:text="coordLat" />
<Button
    android:id="@+id/submit"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:text="Submit"
    android:layout_marginBottom="168dp"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true" />

这是我的 php 脚本:gps_a001.php:

     <?php
    include_once './DbConnect.php';
    function createNewLocation() {
     $response = array();
    $longitude = $_POST["longitude"];
    $latitude = $_POST["latitude"];


    //$float_long = floatval($longitude);
    //$float_lati = floatval($latitude);


            $db = new DbConnect();
   // mysql query
    $query = "INSERT INTO gps4(longitude,latitude) VALUES('$longitude','$latitude')";
    $result = mysql_query($query) or die(mysql_error());
    if ($result) {
        $response["error"] = false;
        $response["message"] = "Location added successfully!";
    } else {
        $response["error"] = true;
        $response["message"] = "Failed to add location!";
    }
   // echo json response
echo json_encode($response);
      }
     createNewlocation();
     ?>

这是我的表(gps4)结构:

table gps4 structure

最后这是我得到的结果:

result

为了通知您,我使用: -Android工作室 -Genymotion -wamp服务器

有人可以帮我解决这个问题吗???

最佳答案

那么!我找到了我的问题的解决方案,以防有人需要! 就这么简单!在 MainActivity 中替换这些行

 gpsLong = mTxtViewlong.getText().toString();

 gpsLati = mTxtViewlat.getText().toString();      

像这样放置 onClick :

       public void onClick(View v) {
        // TODO Auto-generated method stub

   gpsLong = mTxtViewlong.getText().toString();

   gpsLati = mTxtViewlat.getText().toString();   

        new AddNewLocation().execute(gpsLong, gpsLati);
    }    

然后像这样更改 doInBackground 中的变量:

        protected Void doInBackground(String... arg) {
    // TODO Auto-generated method stub

    String longitude = gpsLong;
    String latitude = gpsLati;

就是这样;) 享受...

关于php - 从android发送数据( double 类型)到mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44688189/

相关文章:

javascript - 将php数组值循环到html数据属性

php - 从 mysql 更新到 PDO 的最佳实践

android - 使用 Jar 转换类,合并调试重复条目

php - 无法在 XAMPP 中打开 phpmyadmin

mysql - 我创建了一个表,但出现了以下错误。我不知道原因

php - 如何根据我在 codeigniter session 中拥有的电子邮件返回数据?

PHP 将值传递给包含文件中的变量

Android - Realm - 对象删除 - 对象不再有效以进行操作

android - 添加到 Layout 的 View 继承父级的样式

MySQL MyISAM 表文件现在太大