JianYA JianYA - 5 months ago 38
Android Question

Android HTTP Post returns null

I have a async task that continuously sends a message to a server and receives a message in return. When I test it, I let it run for a few seconds and then switch off the wifi. The app then crashes and sends a null pointer exception. Am I able to do anything in the HTTPPost or even just send a message if there is no internet instead of crashing the app?

This is my code

private class UpdateLoc extends AsyncTask<Void,Void,String> {
InputStream inputStream = null;
@Override
protected void onPreExecute() {
super.onPreExecute();
}

@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try{
if(s.trim()!=null){
Log.d("HTTPRESULT",s.toString());
}
}catch (Exception e){
e.printStackTrace();
}

}

@Override
protected String doInBackground(Void... params) {
String result = null;
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(Constants.UPDATE);
List<NameValuePair> nameValuePairs = new ArrayList<>();
nameValuePairs.add(new BasicNameValuePair(Constants.params_email,email));
nameValuePairs.add(new BasicNameValuePair(Constants.params_location,curr_location));

try{
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
inputStream = httpEntity.getContent();

BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"),8);
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while((line=bufferedReader.readLine())!=null){
stringBuilder.append(line+"\n");
}
result = stringBuilder.toString();

}catch (ClientProtocolException e){
e.printStackTrace();
}catch (UnsupportedEncodingException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}

return result;
}
}

Answer

Try checking for the network connection before calling the AsyncTask, something like:

private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

=======

You can find the docs here.