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.

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

报告相同问题?

悬赏问题

  • ¥15 聚类分析或者python进行数据分析
  • ¥15 如何用visual studio code实现html页面
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?