2013-10-08 55 views
0

我想在我的Android应用中实现setConnectionTimeout。我遵循了几个代码结构,但无法使其工作。我的应用程序已连接到本地主机服务器,我只是希望它显示连接超时,如果它无法连接到数据库。Android应用崩溃setConnectionTimeout

这里是我的http请求代码:

HttpParams httpParameters = new BasicHttpParams(); 
// Set the timeout in milliseconds until a connection is established. 
// The default value is zero, that means the timeout is not used. 
int timeoutConnection = 3000; 
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); 
// Set the default socket timeout (SO_TIMEOUT) 
// in milliseconds which is the timeout for waiting for data. 
int timeoutSocket = 5000; 
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); 

// defaultHttpClient 
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters); 
HttpPost httpPost = new HttpPost(url); 
httpPost.setEntity(new UrlEncodedFormEntity(params)); 

HttpResponse httpResponse = httpClient.execute(httpPost); 
HttpEntity httpEntity = httpResponse.getEntity(); 
is = httpEntity.getContent(); 

问题是,当它达到3秒,应用程序崩溃。在我执行此代码段之前,它只会冻结更长时间。如果我关闭了Wifi,它将返回一个DialogBox,表示互联网没有连接,这就是我想要实现的。

任何想法如何在数据库无法连接时返回AlertDialogBox? (我为此禁用了WAMP)

+0

发布您的logcat崩溃日志。 –

+0

这里是logcat:http://pastebin.com/pS70UDe9 – AimanB

回答

0

您的例外情况是说解析JSON时存在空指针异常。你没有在这里附上这段代码,所以我只假设一旦你的超时发生,你仍然试图将输入流解析为JSON。

这将是很好,检查您的输入流是不是空的第一次。

+0

请原谅我的初学者,但你能告诉我代码在哪里,以及如何检查我的输入流是否为空,并使其为空? – AimanB