Android的JSON得到PHP数据 [英] Android JSON get data from PHP

查看:125
本文介绍了Android的JSON得到PHP数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人有任何想法,我做错了什么?我试图做几乎所有的例子在那里。我只是想从使用PHP来我的Andr​​oid手机与服务器的纬度和经度COORDS。

感谢您的帮助先进

这是我有问题,我的code的部分:

 公共无效连接()
{
    StrictMode.ThreadPolicy政策=新
    StrictMode.ThreadPolicy.Builder()permitAll()建立()。
    StrictMode.setThreadPolicy(政策);    HttpClient的HttpClient的=新DefaultHttpClient();    // prepare请求对象
    HTTPGET HTTPGET =新HTTPGET(服务器URL);    //执行请求
    HTT presponse响应;
    尝试{
        响应= httpclient.execute(HTTPGET);
        //检查响应状态
        。//Log.i(\"Info\",response.getStatusLine()的toString());与HTTP / 1.1 200 OK回来        //获取响应实体持有
        HttpEntity实体= response.getEntity();        如果(实体!= NULL){
            InputStream的河道= entity.getContent();
            字符串结果= convertStreamToString(插播广告);            JSONArray ARR =新JSONArray(结果);
            的JSONObject jObj = arr.getJSONObject(0);
            字符串经纬度= jObj.getString(纬度);
            Log.d(产出,jObj.getString(经度));
            Toast.makeText(这一点,纬度,Toast.LENGTH_LONG).show();
            instream.close();
        }
    }赶上(例外五){
        Log.e(错误,e.toString());
    }
}

我不能得到的数据出来的JSONObject的。我不断收到此异常。

  03-31 17:23:41.457:E /错误(317):org.json.JSONException:价值与LT; java.lang.String类型的DOCTYPE不能转换为JSONArray

从我的服务器的PHP code为输出:

  [{纬度:47.9255072,经度: -  97.0846979,ID:34}]

下面是所有code在我MainActivity

 包com.misterbusllc.misterbusllc;进口java.io.BufferedReader中;
进口java.io.IOException异常;
进口的java.io.InputStream;
进口java.io.InputStreamReader中;进口org.apache.http.HttpEntity;
进口org.apache.http.Htt presponse;
进口org.apache.http.client.HttpClient;进口org.apache.http.client.methods.HttpGet;
进口org.apache.http.impl.client.DefaultHttpClient;进口org.json.JSONArray;
进口org.json.JSONObject;进口com.google.android.gms.maps.CameraUpdateFactory;
进口com.google.android.gms.maps.GoogleMap;
进口com.google.android.gms.maps.SupportMapFragment;
进口com.google.android.gms.maps.model.BitmapDesc​​riptorFactory;
进口com.google.android.gms.maps.model.LatLng;
进口com.google.android.gms.maps.model.MarkerOptions;进口android.os.Bundle;
进口android.os.StrictMode;
进口android.content.Intent;
进口android.support.v4.app.FragmentActivity;
进口android.util.Log;
进口android.view.Menu;
进口android.widget.SlidingDrawer;
进口android.widget.SlidingDrawer.OnDrawerCloseListener;
进口android.widget.SlidingDrawer.OnDrawerOpenListener;
进口android.widget.Toast;
公共类MainActivity扩展FragmentActivity {@覆盖
保护无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_main);
    连接();    // contactServer();
    最后SlidingDrawer slidingDrawerCost =(SlidingDrawer)findViewById(R.id.slidingDrawerCost);
    最后SlidingDrawer slidingDrawerInfo =(SlidingDrawer)findViewById(R.id.slidingDrawerInfo);    使用GoogleMap地图=((SupportMapFragment)getSupportFragmentManager()findFragmentById(R.id.map)。)的GetMap();    经纬度的latLng =新的经纬度(47.922612,-97.060776);
    map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    map.addMarker(新的MarkerOptions()位置(的latLng).title伪(MisterBus)片段(MisterBus目前这里)图标(BitmapDesc​​riptorFactory.defaultMarker(BitmapDesc​​riptorFactory.HUE_AZURE))。);
    map.getUiSettings()setCompassEnabled(真)。
    map.getUiSettings()setZoomControlsEnabled(真)。
    map.animateCamera(CameraUpdateFactory.newLatLngZoom(的latLng,10));    slidingDrawerCost.setOnDrawerOpenListener(新OnDrawerOpenListener(){
        @覆盖
        公共无效onDrawerOpened(){
            意向意图=新意图(getApplicationContext(),Cost.class);
            startActivity(意向);
        }
        });
        slidingDrawerCost.setOnDrawerCloseListener(新OnDrawerCloseListener(){        @覆盖
        公共无效onDrawerClosed(){
            slidingDrawerCost.close();
        }
        });        slidingDrawerInfo.setOnDrawerOpenListener(新OnDrawerOpenListener(){
            @覆盖
            公共无效onDrawerOpened(){
                意向意图=新意图(getApplicationContext(),info.class);
                startActivity(意向);
            }
            });
            slidingDrawerInfo.setOnDrawerCloseListener(新OnDrawerCloseListener(){            @覆盖
            公共无效onDrawerClosed(){
                slidingDrawerInfo.close();
            }
            });
}@覆盖
公共布尔onCreateOptionsMenu(菜单菜单){
    //充气菜单;如果是present这增加了项目操作栏。
    。getMenuInflater()膨胀(R.menu.main,菜单);
    返回true;
}
公共无效连接()
{
    StrictMode.ThreadPolicy政策=新
    StrictMode.ThreadPolicy.Builder()permitAll()建立()。
    StrictMode.setThreadPolicy(政策);    HttpClient的HttpClient的=新DefaultHttpClient();    // prepare请求对象
    HTTPGET HTTPGET =新HTTPGET(服务器URL);    //执行请求
    HTT presponse响应;
    尝试{
        响应= httpclient.execute(HTTPGET);
        //检查响应状态
        。//Log.i(\"Info\",response.getStatusLine()的toString());与HTTP / 1.1 200 OK回来        //获取响应实体持有
        HttpEntity实体= response.getEntity();        如果(实体!= NULL){
            InputStream的河道= entity.getContent();
            字符串结果= convertStreamToString(插播广告);            JSONArray ARR =新JSONArray(结果);
            的JSONObject jObj = arr.getJSONObject(0);
            字符串经纬度= jObj.getString(纬度);
            Log.d(产出,jObj.getString(经度));
            Toast.makeText(这一点,纬度,Toast.LENGTH_LONG).show();
            instream.close();
        }
    }赶上(例外五){
        Log.e(错误,e.toString());
    }
}    私人静态字符串convertStreamToString(InputStream为){
    / *
     *要InputStream中转换为字符串,我们使用使用BufferedReader.readLine()
     *方法。我们重复,直到BufferedReader中返回NULL,这意味着
     *没有更多的数据读取。每一行追加到一个StringBuilder
     *和返回为String。
     * /
    读者的BufferedReader =新的BufferedReader(新的InputStreamReader(是));
    StringBuilder的SB =新的StringBuilder();    串线= NULL;
    尝试{
        而((行= reader.readLine())!= NULL){
            sb.append(行+\\ n);
        }
    }赶上(IOException异常五){
        e.printStackTrace();
    } {最后
        尝试{
            is.close();
        }赶上(IOException异常五){
            e.printStackTrace();
        }
    }
    返回sb.toString();
}} //类的结束

PHP code:

 <!DOCTYPE HTML PUBLIC -  // W3C // DTD XHTML 1.0过渡// ENhttp://www.w3.org/TR/xhtml1/DTD/ XHTML1-transitional.dtd>
< HTML的xmlns =htt​​p://www.w3.org/1999/xhtml>
< HEAD>
<间的charset = UTF-8HTTP的当量=Content-Type的CONTENT =应用/ JSON; />
<标题>全球定位系统发送和LT; /标题>
< /头>
<身体GT;< PHP
标题(内容类型:应用程序/ JSON');
mysql_connect(localhost的根,密码);
mysql_select_db(misterbus);
$最后的mysql_query =(SELECT * FROM位置,ID =(SELECT MAX(ID)出发地点));而($行= mysql_fetch_assoc($最后))
$输出[] = $行;
 打印(json_en code($输出));mysql_close();
?>< /身体GT;
< / HTML>


解决方案

您的PHP页面包含HTML标签:

 <!DOCTYPE HTML PUBLIC -  // W3C // DTD XHTML 1.0过渡// ENhttp://www.w3.org/TR/xhtml1/DTD/ XHTML1-transitional.dtd>
< HTML的xmlns =htt​​p://www.w3.org/1999/xhtml>
< HEAD>
< META HTTP-EQUIV =Content-Type的CONTENT =text / html的;字符集= UTF-8/>
<标题>全球定位系统发送和LT; /标题>
< /头>
<身体GT;[{纬度:47.9255072,经度: - 97.0846979,ID:34}]
< /身体GT;
< / HTML>

因此​​,你所得到的错误是因为Android不正确理解响应(它假定纯JSON,而不是HTML)。您需要删除的HTML标记,以便响应只包含纯粹的JSON

您可能还需要设置一个头,宣布它一个JSON内容类型。
你可以做到这一点是这样的:

 标题(内容类型:应用程序/ JSON');

将这个code权后的第一个<?PHP 标签,一切之前

Does anyone have any idea what I am doing wrong? I tried doing just about every example out there. I just want to get the lat and lon coords from the server using php to my android phone.

Thank you for your help in advanced

This is the Section of my code which I am having problems with:

public void connect()
{
    StrictMode.ThreadPolicy policy = new   
    StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    HttpClient httpclient = new DefaultHttpClient();

    // Prepare a request object
    HttpGet httpget = new HttpGet("SERVER URL"); 

    // Execute the request
    HttpResponse response;
    try {
        response = httpclient.execute(httpget);
        // Examine the response status
        //Log.i("Info",response.getStatusLine().toString());  Comes back with HTTP/1.1 200 OK

        // Get hold of the response entity
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            InputStream instream = entity.getContent();
            String result= convertStreamToString(instream);

            JSONArray arr = new JSONArray(result);
            JSONObject jObj = arr.getJSONObject(0);
            String lat = jObj.getString("Lat");
            Log.d("OutPut", jObj.getString("Lon"));
            Toast.makeText(this, lat, Toast.LENGTH_LONG).show();
            instream.close();
        }


    } catch (Exception e) {
        Log.e("Error",e.toString());
    }
}

I cannot get the data out of the JSONObject. I keep getting this exception.

03-31 17:23:41.457: E/Error(317): org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONArray

The PHP code from my server is outputting:

[{"Lat":"47.9255072","Lon":"-97.0846979","id":"34"}]

Here is all the code in my MainActivity

package com.misterbusllc.misterbusllc;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;

import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import org.json.JSONArray;
import org.json.JSONObject;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import android.os.Bundle;
import android.os.StrictMode;
import android.content.Intent;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.widget.SlidingDrawer;
import android.widget.SlidingDrawer.OnDrawerCloseListener;
import android.widget.SlidingDrawer.OnDrawerOpenListener;
import android.widget.Toast;


public class MainActivity extends FragmentActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    connect();

    //contactServer();


    final SlidingDrawer slidingDrawerCost = (SlidingDrawer) findViewById(R.id.slidingDrawerCost);
    final SlidingDrawer slidingDrawerInfo = (SlidingDrawer) findViewById(R.id.slidingDrawerInfo);

    GoogleMap map = ((SupportMapFragment)  getSupportFragmentManager().findFragmentById(R.id.map)).getMap();

    LatLng latLng = new LatLng(47.922612,-97.060776);
    map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    map.addMarker(new MarkerOptions().position(latLng).title("MisterBus").snippet("MisterBus is currently here").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
    map.getUiSettings().setCompassEnabled(true);
    map.getUiSettings().setZoomControlsEnabled(true);
    map.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 10));

    slidingDrawerCost.setOnDrawerOpenListener(new OnDrawerOpenListener() {
        @Override
        public void onDrawerOpened() {
            Intent intent = new Intent(getApplicationContext(), Cost.class);
            startActivity(intent);
        }
        });
        slidingDrawerCost.setOnDrawerCloseListener(new OnDrawerCloseListener() {

        @Override
        public void onDrawerClosed() {
            slidingDrawerCost.close();
        }
        }); 

        slidingDrawerInfo.setOnDrawerOpenListener(new OnDrawerOpenListener() {
            @Override
            public void onDrawerOpened() {
                Intent intent = new Intent(getApplicationContext(), info.class);
                startActivity(intent);
            }
            });
            slidingDrawerInfo.setOnDrawerCloseListener(new OnDrawerCloseListener() {

            @Override
            public void onDrawerClosed() {
                slidingDrawerInfo.close();
            }
            }); 


}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}




public void connect()
{
    StrictMode.ThreadPolicy policy = new   
    StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    HttpClient httpclient = new DefaultHttpClient();

    // Prepare a request object
    HttpGet httpget = new HttpGet("SERVER URL"); 

    // Execute the request
    HttpResponse response;
    try {
        response = httpclient.execute(httpget);
        // Examine the response status
        //Log.i("Info",response.getStatusLine().toString());  Comes back with HTTP/1.1 200 OK

        // Get hold of the response entity
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            InputStream instream = entity.getContent();
            String result= convertStreamToString(instream);

            JSONArray arr = new JSONArray(result);
            JSONObject jObj = arr.getJSONObject(0);
            String lat = jObj.getString("Lat");
            Log.d("OutPut", jObj.getString("Lon"));
            Toast.makeText(this, lat, Toast.LENGTH_LONG).show();
            instream.close();
        }


    } catch (Exception e) {
        Log.e("Error",e.toString());
    }
}

    private static String convertStreamToString(InputStream is) {
    /*
     * To convert the InputStream to String we use the BufferedReader.readLine()
     * method. We iterate until the BufferedReader return null which means
     * there's no more data to read. Each line will appended to a StringBuilder
     * and returned as String.
     */
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}

}//end of class

PHP CODE:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset=utf-8" http-equiv="Content-Type" content="application/json"; />
<title>Gps Send</title>
</head>
<body>

<?php
header('Content-type: application/json');
mysql_connect("localhost", "root","password"); 
mysql_select_db("misterbus");
$last =mysql_query("SELECT * FROM location WHERE ID = (SELECT MAX(id)  FROM location)");

while($row=mysql_fetch_assoc($last))
$output[]=$row;
 print(json_encode($output));

mysql_close();
?>

</body>
</html>

解决方案

Your PHP page contains HTML tags:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Gps Send</title>
</head>
<body>



[{"Lat":"47.9255072","Lon":"-97.0846979","id":"34"}]
</body>
</html>

Therefore, the error you are getting is because Android doesn't understand the response correctly (it assumes pure JSON, not HTML). You need to remove the HTML tags so the response only contains the pure JSON.

You might also want to set a header declaring it of a JSON content-type. You can do that this way:

header('Content-type: application/json');

Put this code right after the first <?php tag, before everything else.

这篇关于Android的JSON得到PHP数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆