1

I am creating android app that call rest services made by me on server and server is ruuning live but due to internet connectivity issues some time my application runs successfully but sometime it crashes. The code for my connection class is as

public class CommunicationClass {

@SuppressWarnings("unused")
private static final String TAG = null;
public String Domain;
public HttpClient client;
public HttpPost datapost;
public HttpResponse response;
public BufferedReader reader;
public StringBuilder builder;
public JSONTokener tokener;
public JSONObject finalResult;
List<NameValuePair> namevaluepairs = new ArrayList<NameValuePair>(10);


public void setClient() {
    // TODO Auto-generated method stub
    client = new DefaultHttpClient();
    System.out.println("Created http client");
}
public void setDomain(String st) {
    // TODO Auto-generated method stub
    Domain = st;
    System.out.println("Domain has been set");
}
public void setResponse(){
    response=null;
    System.out.println("Response has been initalized by null");
}
public void setStringBuilder(){
    builder = new StringBuilder();
}
public void setreader(){
    try {
        reader = new BufferedReader(new InputStreamReader(this.response.getEntity().getContent(), "UTF-8"));
        System.out.println("Setting the contents of the Reader");
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        System.out.println("In the UnsupportedEncodingException catch of the Reader");
        e.printStackTrace();
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        System.out.println("In the IllegalStateException catch of the Reader");
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        System.out.println("In the IOException catch of the Reader");
        e.printStackTrace();
    }

}
public void startpost(String str){
    datapost=new HttpPost(str);
    System.out.println("Created the httppost domain");
}
public void insertdata(String tag,String value){
    namevaluepairs.add(new BasicNameValuePair(tag,value));
    System.out.println("Added the parameter  "+tag);
}
public void trydata(){
    try {
        this.datapost.setEntity(new UrlEncodedFormEntity(this.namevaluepairs));
        System.out.println("Setting the entity");
        try {
            this.response = this.client.execute(this.datapost);
            System.out.println("executing the client");
             if(this.response != null){
                 System.out.println("i am in if of this.response!=null");
             }
             else{
                 System.out.println("i am in else of this.response!=null");
             }
             System.out.println("in response try box");
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            System.out.println("in ClientProtocolException Catch box");
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            System.out.println("in IOException Catch box");
            e.printStackTrace();
        }
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        System.out.println("in UnSupported Catch box");
        e.printStackTrace();
    }
}
public void readresponse(){     



    try {
        for (String line = null; (line = reader.readLine()) != null;) {
            builder.append(line).append("\n");

        }
        System.out.println(this.builder);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
     tokener = new JSONTokener(builder.toString());
    try {
         finalResult = new JSONObject(tokener);
        System.out.println("I am in try block of json final result reading");
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        System.out.println("I catch block of jsonException");
        e.printStackTrace();
    } 
}


}

it gives me error on line trydata(); that actually execute the HTTP Client so i want to make sure that it should not crash due to internet connectivity but may throw the exception that can be caught or make toast. Guys need help on this

Thanks!

Naveed Yousaf
  • 133
  • 2
  • 13
  • i have checked the internet connectivity before the application is launched if internet is not available it will be launched but will not work i am asking about why it crashes at trydata(); which is actually executing client it display setting the entity in logcat and then a long lines of red error why is it crashing???? – Naveed Yousaf Dec 12 '13 at 10:44

4 Answers4

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

and dont forgett:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

it's work great for me.

nano_nano
  • 12,351
  • 8
  • 55
  • 83
1

Check Internet connectivity before calling Webservice:

 public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager
                .getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }
Sharmilee
  • 1,286
  • 1
  • 12
  • 20
1

Although other answers are correct, they are partially correct. If you want ot know you have internet connection, not just connected to a wi-fi hotspot, you have to ping a site. This is something I found yesterday, and works if you are connected but have no internet connection via this hotspot. Basically it pings google. Use a boolean with it, and put it in the checks in the other people's answers' check.

Community
  • 1
  • 1
0

Use this:

public static Boolean checkForInternetConnection(Context context) {
    final ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
    if (activeNetwork != null && activeNetwork.isConnected()) {
        return true;
    } else {
        return false;
    }

}
Abhishek Shukla
  • 1,242
  • 8
  • 11
  • This line checks for internet connectivity i have checked it as soon as app launches it checks for internet connectivity and if internet is connected then application will work otherwise it will not i am saying is that i have a user just signed in he was having internet connection and while he is moving from one room to another this app will sign him in but will not call edit method on server but will crash why it crashes due to client execution. – Naveed Yousaf Dec 12 '13 at 10:37