Android freezes, but android cannot find connection

I am creating an Android application, but so far (if?) The server is not found, it will hang up a toolbox (SDK / emulator?). I have attached my login code. Please help me find a solution. I just want that if the server is unavailable, my application will remain on the login page without hanging itself.

when I debugged my code, I did not get the httpResponse value and after this line

HttpResponse httpResponse = httpclient.execute(httpPost); 

there was a problem

 public String login(String userName, String password){ try { String url = URL+ "?flag="+"on"+"&user="+userName+"&pass="+password; httpPost = new HttpPost(url); HttpResponse httpResponse = httpclient.execute(httpPost); int statuscode = httpResponse.getStatusLine().getStatusCode(); if (statuscode == 200) { String responseMsg = getResponse(httpResponse); return responseMsg; }else{ Log.e(TAG, statuscode+""); } } catch (ClientProtocolException e) { Log.e(TAG, e.getMessage(),e); } catch (IOException e) { Log.e(TAG, e.getMessage(),e); } return null; } 
+4
source share
4 answers

You should also consider determining a timeout (for example, 5 seconds) so that the system does not try to connect to an unreachable server for a long time.

 final HttpParams httpParams = httpClient.getParams(); HttpConnectionParams.setConnectionTimeout(httpParams, 5000); HttpConnectionParams.setSoTimeout(httpParams, 5000); 
+2
source

Check How to set the HttpResponse timeout for Android in Java . And you really have to do all your network communications in a separate thread / AsyncTask, and not in the main thread.

+2
source

If your user interface hangs on your emulator, you are probably doing network stuff in the user interface thread, which blocks all user interface operations until a network operation is completed. Read how to run this code in the stream here: http://developer.android.com/resources/articles/painless-threading.html

+2
source

Did you get any exception? If the URL is not formatted correctly, you will get a MalformedURLException , and if the server is unavailable / the link is broken by an IOException .

Do you want to pass the response through ResponseHandler

 ResponseHandler<String> responseHandler = new BasicResponseHandler(); try { responseString = mHttpClient.execute(post, responseHandler); Log.d(TAG, "doHTTPpost responseString = " + responseString); } catch (ClientProtocolException e) { //handle it } catch (IOException e) { //handle it } catch (IllegalStateException e) { //handle it } finally { //handle it } 
+1
source

Source: https://habr.com/ru/post/1340592/


All Articles