简体   繁体   English

setConnectionTimeout后,Android应用程序崩溃

[英]Android app crashes after setConnectionTimeout

I want to implement a setConnectionTimeout in my Android app. 我想在我的Android应用中实现setConnectionTimeout。 I've followed several code structures but couldn't make it work. 我遵循了几种代码结构,但无法使其正常工作。 My app was connected to a localhost server, I just want it to display Connection Timeout if it cannot be connected to the database. 我的应用程序已连接到本地服务器,如果它无法连接到数据库,我只希望它显示“连接超时”。

Here is my Http Request code: 这是我的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();

The problem is when it reaches 3 seconds, the app crashes. 问题是当到达3秒时,应用程序崩溃。 Before I implemented this snippet, it just freezes for a longer time. 在实施此代码段之前,它只会冻结更长的时间。 And if I turn off my Wifi, it will return a DialogBox saying that the internet is not connected, and this is what I want to achieve. 如果我关闭Wifi,它将返回一个对话框,提示未连接互联网,这就是我想要实现的目标。

Any idea how to return an AlertDialogBox if database couldn't be connected? 任何想法如果数据库无法连接如何返回AlertDialogBox? (I've disabled WAMP for this purpose) (我为此禁用了WAMP)

Your exception is saying that there's a null pointer exception while parsing JSON. 您的例外是说,解析JSON时存在空指针例外。 You didn't attach that code here, so I'm only assuming that once your timeout occurs, you're still trying to parse the input stream into JSON. 您没有在此处附加该代码,因此我仅假设一旦发生超时,您仍在尝试将输入流解析为JSON。

It would be good to check if your input stream isn't empty first. 最好先检查您的输入流是否不为空。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM