Android HttpPost从PHP脚本而不是JSONArray获取NULL
我有一个数据库,它有两列(id,name),位于localhost:88。我试图从我的android应用程序进入它,但在解析Json时,应用程序会给出JSONException。我试着不用Json解析就从php获取数据,只是一个字符串。但它只得到空值。 以下是我的php脚本:Android HttpPost从PHP脚本而不是JSONArray获取NULL,php,android,mysql,json,http-post,Php,Android,Mysql,Json,Http Post,我有一个数据库,它有两列(id,name),位于localhost:88。我试图从我的android应用程序进入它,但在解析Json时,应用程序会给出JSONException。我试着不用Json解析就从php获取数据,只是一个字符串。但它只得到空值。 以下是我的php脚本: <?php $con = mysqli_connect('127.0.0.1:3306', 'root', '', 'test'); if(mysqli_connect_errno()) echo 'Fa
<?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();
}
}
}
公共类MainActivity扩展活动
{
文本视图;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(右布局、主布局);
txt=(TextView)findViewById(R.id.TextView);
setText(getDataFromDB());
}
公共字符串getDataFromDB()
{
尝试
{
HttpPost HttpPost=新的HttpPost(“http://127.0.0.1:88/basicphp/GetData.php");
HttpClient HttpClient=新的DefaultHttpClient();
ResponseHandler ResponseHandler=新BasicResponseHandler();
最终字符串响应=httpClient.execute(httpPost,responseHandler);
returnresponse.trim();
}
捕获(例外e){
返回“error\n”+e.getMessage();
}
}
}
当我在浏览器中键入“http://localhost:88/basicphp/GetData.php
”,我得到这个:“[{“id”:“1”,“name”:“John”}]”。所以我想至少在我的TextView上获取这个字符串,但是TextView只获取null:(那么,我做错了什么?更改
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");