【问题标题】:Android HttpPost gets NULL from PHP script instead of JSONArrayAndroid HttpPost 从 PHP 脚本而不是 JSONArray 获取 NULL
【发布时间】:2014-09-22 07:11:14
【问题描述】:

我有一个包含两列(id、name)的数据库,位于 localhost:88。我试图从我的 android 应用程序中进入它,但是在解析 Json 时,应用程序给出了 JSONException。我尝试在没有 Json 解析的情况下从 php 获取数据,只是一个字符串。但它只得到 NULL。 这是我的 php 脚本:

<?php

$con = mysqli_connect('127.0.0.1:3306', 'root', '', 'test');

if(mysqli_connect_errno())
    echo 'Failed to connect to MySQL: ' . mysqli_connect_error();

$query = mysqli_query($con, "SELECT * FROM example");
$rows = array();

while($r = mysqli_fetch_assoc($query))
    $rows[] = $r;

print(json_encode($rows));
    mysqli_close($con);     
?>

这是我的方法:

public class MainActivity extends Activity
{
    TextView txt;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_layout);

        txt = (TextView) findViewById(R.id.textView);

        txt.setText(getDataFromDB());
    }

    public String getDataFromDB()
    {
        try
        {
            HttpPost httpPost = new HttpPost("http://127.0.0.1:88/basicphp/GetData.php");

            HttpClient httpClient = new DefaultHttpClient();
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            final String response = httpClient.execute(httpPost, responseHandler);

            return response.trim();
        }
        catch(Exception e){
            return "error\n" + e.getMessage();
        }
    }
}

当我在浏览器中输入“http://localhost:88/basicphp/GetData.php”时,我得到:“[{“id”:“1”,“name”:“John”}]”。所以我想至少在我的TextView上得到这个字符串,但是TextView只得到null:(那么,我做错了什么?

【问题讨论】:

标签: php android mysql json http-post


【解决方案1】:

改变

 HttpPost httpPost = new HttpPost("http://127.0.0.1:88/basicphp/GetData.php");

 HttpPost httpPost = new HttpPost("http://10.0.2.2/basicphp/GetData.php");

访问【问题】:java.net.ConnectException: /127.0.0.1:8080 an android emulator

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-24
    • 1970-01-01
    • 2015-04-18
    相关资源
    最近更新 更多