Android开发-Unknown主机异常问题

时间:2011-04-23 12:58:37

标签: android mysql sql exception timer

我正在开发一个Android应用程序,它从连接到MySQL数据库的php中间件脚本获取JSON_encoded结果。我已经给了应用程序Internet权限。 我遇到的问题是程序在第一次运行时出现UnknownHostException错误。我有一个计时器上的程序,后续调用计时器处理函数不会返回UnknownHostException错误。你知道为什么会这样吗?我测试了域并确保它通过Web浏览器正确连接。 以下是代码中的代码段:

    public final void timerAlert(){ 

    final Handler handler = new Handler();
    final Runnable r = new Runnable()
    {
        public void run() {

            Timer_Method();
            handler.postDelayed(this,1000);
        }

    };
    handler.postDelayed(r, 1000);
}

public void Timer_Method()
{

    //See if this buzzer is being signaled.
    String result = null;
    InputStream is = null;
    StringBuilder sb=null;
    //http post
    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("BuzzerID",BuzzerID.toString()));
   Toast.makeText(getBaseContext(), "BuzzerID="+BuzzerID.toString() ,Toast.LENGTH_LONG).show();
    try{
         HttpClient httpclient = new DefaultHttpClient();
         HttpPost httppost = new HttpPost("http://domain/getBuzzStatus.php?BuzzerID="+BuzzerID.toString());
         httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
         HttpResponse response = httpclient.execute(httppost);
         HttpEntity entity = response.getEntity();
         is = entity.getContent();

    }catch(Exception e){
             Log.e("log_tag", "Error in http connection"+e.toString());
           Toast.makeText(getBaseContext(), "Hm, problem here="+e.toString() ,Toast.LENGTH_LONG).show();
         }

请注意,域在实际代码中还有其他内容,这只是一个片段,但是第一个问题发生的地方。另请注意,我正在混合get和post,我宁愿不这样做,但由于某种原因,将nameValuePair传递给php脚本不会向$ _REQUEST发送任何内容。

非常简单的PHP脚本的片段:

$sql_string="SELECT Signal FROM BuzzCustomer WHERE idBuzzCustomer=" . $_GET['BuzzerID'];

$sql = mysql_query($sql_string);


while($row=mysql_fetch_assoc($sql))  
    $output[]=$row;  
print(json_encode($output));  

mysql_close();

我在这里切换到$ _GET因为我无法获得$ _REQUEST工作。任何帮助,将不胜感激。提前谢谢!

2 个答案:

答案 0 :(得分:1)

可能是他们在模拟器中没有互联网连接......在浏览器中查看网址

而不是

HttpResponse response = httpclient.execute(httppost);
         HttpEntity entity = response.getEntity();
         is = entity.getContent();

使用

ResponseHandler<String>  response = new BasicResponseHandler();
String result = httpclient.execute(httppost,response);

还在“清单”中加入了Internet权限

答案 1 :(得分:0)

只是一个猜测,但也许DNS请求耗时太久而你的HttpClient放弃了,但请求已经完成并缓存,以便下次它不会失败?
这个With Apache HttpClient, why isn't my connection timeout working?似乎是关于如何为HttpClient设置超时的问题。