我的应用程序是一个简单的定位系统,每个用户位置都更新到服务器上,当需要帮助时,它会发回给定范围内所有人的移动号码(大约)。 该应用程序可以定期向服务器定期更新位置,并使用近似方法查找某个范围内的人,我现在面临的问题是将查询的数字列表发送回设备。我已经尝试了一些教程,但没有运气,应用程序一直在崩溃。 这是我的代码,我发送数据和PHP代码。如果有人帮我弄清楚如何从服务器接收数字。
private void serverConnection() {
// TODO Auto-generated method stub
GPSTracker gps1 = new GPSTracker(MainActivity.this);
double latitude = gps1.getLatitude();
double longitude = gps1.getLongtitude();
Toast.makeText(getApplicationContext(),"Your Location is -\nLat:"+latitude+"\nLon:"+longitude,Toast.LENGTH_LONG).show();
String lat = String.valueOf(latitude);
String log = String.valueOf(longitude);
String svdNum;
RegistrationActivity gsm = new RegistrationActivity();
SharedPreferences sharedData = getSharedPreferences(gsm.filename,0);
svdNum = sharedData.getString("Mobile Number", "No Number Registered");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("Lat",lat));
nameValuePairs.add(new BasicNameValuePair("Long",log));
nameValuePairs.add(new BasicNameValuePair("Number",svdNum));
try{
if(distress == 0){
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://10.0.2.2/tech/serverConnection.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}else{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://10.0.2.2/tech/serverConnection2.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
}
catch(ClientProtocolException e){
Log.e("ClientProtocol", "Log_tag");
e.printStackTrace();
}
catch(IOException e){
Log.e("Log_tag", "IOException");
e.printStackTrace();
}
php代码
<?php
$conn = mysql_connect(localhost, 'root', '');
mysql_select_db('finalyearproject');
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$Number=$_POST['Number'];
$LatitudeS=$_POST['Lat'];
$LongitudeS=$_POST['Long'];
$Latitude = floatval($LatitudeS);
$Longitude = floatval($LongitudeS);
$sql = "INSERT INTO app_backup(Number,Latitude, Longitude) VALUES('$Number', '$Latitude', '$Longitude') ON DUPLICATE KEY UPDATE Latitude=VALUES(Latitude), Longitude=VALUES(Longitude)";
$sql = "UPDATE app_backup SET Lat_diff=Latitude-$Latitude ,Long_diff=Longitude-$Longitude";
$query= mysql_query("SELECT Number FROM app_backup WHERE Lat_diff <= 30 AND Long_diff <=30 AND Long_diff <> 0 AND Lat_diff <> 0 AND Long_diff >= -30 AND Lat_diff >= -30");
$column = array();
while ( $row = mysql_fetch_array($query, MYSQL_ASSOC) ) {
$column[] = $row['Number'];
}
echo json_encode(column);
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($conn);
?>
先谢谢你。
编辑: 应用程序一直崩溃的代码块
HttpEntity entity2 = response.getEntity();
InputStream nums = entity2.getContent();
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(nums,"iso-8859-1") );
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null){
sb.append(line + "\n");
}
nums.close();
res = sb.toString();
}
catch(IOException e){
Log.e("Log_tag", "IOException");
e.printStackTrace();
}
Json循环
try{
JSONArray jarray = new JSONArray(res);
JSONObject json_data = null;
for(int i=0; i < jarray.length(); i++)
{
json_data = jarray.getJSONObject(i);
}}
catch(JSONException e){
Log.e("error parsing data", "Log_tag");
e.printStackTrace();}
添加这两个块之后,logcat说'关闭VM'并且应用程序崩溃了。我不太确定我的方法在检索方面是否正确。
答案 0 :(得分:0)
要使用JSON将数据发送到您的应用,您必须发送标头,最后使用json_encode发送JSON。另一个缺陷是PHP文件的编码(必须是没有BOM的UTF-8),否则会破坏json。
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');//*/
echo json_encode(column);
但是为了完成这项工作,有一个轻型图书馆Simple JSON for PHP它使你能够'#34;锻造&#34;您可以随心所欲地使用JSON并将其发送(包括标题)。
在你的情况下,它会像:
// At the beginning
$Json = new json();
// Add the data
while ( $row = mysql_fetch_array($query, MYSQL_ASSOC) ) {
$Json->addContent(new arrayJson("data",$row));
}
$Json->addContent(new propertyJson('message', 'Success'));
// At the end, send the json
json_send($Json)
在JAVA部分:
要获取JSON,您应该制作类似here
的方法public String getJSON(String url, int timeout) {
HttpURLConnection c = null;
try {
URL u = new URL(url);
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setRequestProperty("Content-length", "0");
c.setUseCaches(false);
c.setAllowUserInteraction(false);
c.setConnectTimeout(timeout);
c.setReadTimeout(timeout);
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
return sb.toString();
}
} catch (MalformedURLException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} finally {
if (c != null) {
try {
c.disconnect();
} catch (Exception ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
}
}
}
return null;
}
您应该使用Google GSON将JSON转换为数据Java对象,如StackOverflow所示。
import java.util.List;
import com.google.gson.Gson;
public class Test {
public static void main(String... args) throws Exception {
String json =
"{"
+ "'title': 'Computing and Information systems',"
+ "'id' : 1,"
+ "'children' : 'true',"
+ "'groups' : [{"
+ "'title' : 'Level one CIS',"
+ "'id' : 2,"
+ "'children' : 'true',"
+ "'groups' : [{"
+ "'title' : 'Intro To Computing and Internet',"
+ "'id' : 3,"
+ "'children': 'false',"
+ "'groups':[]"
+ "}]"
+ "}]"
+ "}";
// Now do the magic.
Data data = new Gson().fromJson(json, Data.class);
// Show it.
System.out.println(data);
}
}
class Data {
private String title;
private Long id;
private Boolean children;
private List<Data> groups;
public String getTitle() { return title; }
public Long getId() { return id; }
public Boolean getChildren() { return children; }
public List<Data> getGroups() { return groups; }
public void setTitle(String title) { this.title = title; }
public void setId(Long id) { this.id = id; }
public void setChildren(Boolean children) { this.children = children; }
public void setGroups(List<Data> groups) { this.groups = groups; }
public String toString() {
return String.format("title:%s,id:%d,children:%s,groups:%s", title, id, children, groups);
}
}
希望有所帮助