【发布时间】: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:(那么,我做错了什么?
【问题讨论】:
-
NetworkOnMainThreadException 的可能。考虑使用
AsyncTask或Handler。
标签: php android mysql json http-post