Issue
I use an AsyncTask for get-requests with my server. Everythink works fine, if i have connection to the internet, but if I activate airplane mode I get a FATAL EXCEPTION:
01-11 16:01:56.602 3456-3456/com.me.myapp E/ApiHelper: Error at
getting WuerdestDu Stats. Id: 19
01-11 16:01:56.603 3456-3522/com.me.myapp E/AndroidRuntime: FATAL
EXCEPTION: AsyncTask #1
Process: com.me.myapp, PID: 3456
And the strange thing is, that this is the complete Error log at Logcat in verbose mode and no Filters.
This is where i use the AsyncTask:
try {
response = new ApiGetHelper().execute(path).get();
} catch (Exception e) {
Log.e(TAG, "Error at getting WuerdestDu Stats. Id: " + question.getId(), e);
}
this is my AsyncTask:
public class ApiGetHelper extends AsyncTask<String, String, String> {
private final static String TAG = ApiGetHelper.class.getSimpleName();
@Override
protected String doInBackground(String... strings) {
String urlString = strings[0];
try {
URL url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
int responseCode = urlConnection.getResponseCode();
if (responseCode >= 200 && responseCode < 300) {
Log.i(TAG, "Response: " + urlConnection.getResponseCode() + ": " + urlConnection.getResponseMessage());
} else {
Log.e(TAG, "Response: " + urlConnection.getResponseCode() + ": " + urlConnection.getResponseMessage());
}
return ApiUtils.readResponseAsString(urlConnection.getInputStream());
} catch (MalformedURLException e) {
throw new IllegalStateException("URL-ERROR", e);
} catch (IOException e) {
throw new IllegalStateException("IO-ERROR", e);
}
}
}
Solution
If you turn on aeroplane mode you are going to lose internet, you need to check that there is an active internet connection available before trying to post to your server.
Something like the following should do the trick
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null;
}
ref: Android check internet connection
Answered By - Boardy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.