Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/193.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 从我的数据库中检索数据?_Php_Android_Json - Fatal编程技术网

Php 从我的数据库中检索数据?

Php 从我的数据库中检索数据?,php,android,json,Php,Android,Json,我的应用程序是一个简单的定位系统,每个用户的位置都会更新到服务器上,当需要帮助时,它会发回给定范围内所有人的手机号码。 该应用程序可以完美地定期向服务器更新位置,并使用一种近似方法查找特定范围内的人我现在面临的问题是将查询到的号码列表发送回设备。我尝试了一些教程,但运气不佳,应用程序一直崩溃。 这是我的代码,我在其中发送数据和php代码。如果有人能帮我弄清楚如何从服务器接收回号码 private void serverConnection() { // TODO Auto-generat

我的应用程序是一个简单的定位系统,每个用户的位置都会更新到服务器上,当需要帮助时,它会发回给定范围内所有人的手机号码。 该应用程序可以完美地定期向服务器更新位置,并使用一种近似方法查找特定范围内的人我现在面临的问题是将查询到的号码列表发送回设备。我尝试了一些教程,但运气不佳,应用程序一直崩溃。 这是我的代码,我在其中发送数据和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();
    }
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”,应用程序崩溃。我不太确定我的方法是否正确

要以JSON格式向应用程序发送数据,您必须发送标题,并在最后使用JSON_encode发送JSON。另一个陷阱是PHP文件的编码必须是UTF-8,没有BOM,否则会损坏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);
但要完成这项工作,有一个light库,它使您能够随意伪造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,应该创建如下方法

您应该使用将JSON转换为数据Java对象,如中所示


希望它能有所帮助

你说应用程序一直崩溃,但不是在哪里或如何崩溃。你能详细说明一下吗?我已经编辑了关于应用程序崩溃的问题@怀哈雷
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);
// 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)
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;
}
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);
    }
}