donglu6805 2012-03-11 16:03
浏览 64
已采纳

MySQL,Android和PHP的问题

I can find tons of examples where you can query a MySQL database from Android with name value pairs like in this example, and I can get that to work just fine.

Now, however, I want to make it even simpler and that's when I run into problems. I want to simply return an entire table with the query below.

<?php
mysql_connect("localhost","username","pw");
mysql_select_db("db");

$q=mysql_query("SELECT field FROM table");

while($e=mysql_fetch_assoc($q))
        $output[]=$e;

print(json_encode($output));

mysql_close();

?>

So no $_REQUEST lines are being used which is the main difference. The PHP code works fine by itself when I run it in the web browser.

The problem arises in the Android code below. It fails when running the final httpclient.execute line.

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://site.com/db.php");
//httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);

The error returned is android.os.NetworkOnMainThreadException.

I don't know if the setEntity part here is needed since I have no actual nameValuePairs that needs to be received by the PHP script? I have tried both commenting it out as above and setting some dummy value pairs, it won't connect either way. I suspect the setEntity part is where the problem is. How would I set the entity in this case? Or is it a different problem? Thanks.

UPDATE: I tried changing HttpPost to HttpGet as below, but still get the same problem.

HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://site.com/db.php");
//httpget.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httpget);
  • 写回答

1条回答 默认 最新

  • dongyanfeng0563 2012-03-11 16:58
    关注

    According to this question: How to fix android.os.NetworkOnMainThreadException?

    That exception is thrown when you perform networking operations on the main thread, which is bad practice because it hurts responsiveness of your app. You should use a background thread to do the work.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 spring后端vue前端
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题