我收到了这段代码。但我得到了错误,因为我认为其中一些被弃用了。我想要发生的只是按钮"发送"单击它会将用户的位置发送到mysql。
这是android方面。
public void onCreate(Bundle savedInstanceState) {
Button insert=(Button) findViewById(R.id.button1);
insert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(gps.canGetLocation()){
lat = (float) gps.getLatitude();
lng = (float) gps.getLatitude();
lat2= Float.toString(lat);
lng2= Float.toString(lng);
insert();
Toast.makeText(getApplicationContext(), "Success insert - \nLat: " + lat2 + "\nLong: " + lng2, 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();
}
}});
}
public void insert() {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("lat2", lat2));
nameValuePairs.add(new BasicNameValuePair("lng2", lng2));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://monds.com/example.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
} catch (Exception e) {
Log.e("Fail 1", e.toString());
Toast.makeText(getApplicationContext(), "Invalid IP Address",
Toast.LENGTH_LONG).show();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
} catch (Exception e) {
Log.e("Fail 2", e.toString());
}
try {
JSONObject json_data = new JSONObject(result);
code = (json_data.getInt("code"));
if (code == 1) {
Toast.makeText(getBaseContext(), "Inserted Successfully",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getBaseContext(), "Sorry, Try Again",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Log.e("Fail 3", e.toString());
}
}
}
这是我将lat和lng发送到我的数据库的php文件。
$con = mysql_connect($host,$uname,$pwd) or die("connection failed");
mysql_select_db($db,$con) or die("db selection failed");
$lat2=(isset($_REQUEST['lat']) ? $_REQUEST['lat'] : '');
$lng2=(isset($_REQUEST['lng']) ? $_REQUEST['lng'] : '');
//$lat2=$_REQUEST['lat'];
//$lng2=$_REQUEST['lng'];
var_dump($lat2);
$flag['code']=0;
if($r=mysql_query("insert into markers_awal values('','$lat2','$lng2') ",$con))
{
$flag['code']=1;
echo"hi";
}
print(json_encode($flag));
mysql_close($con);
?>