Crash when is no internet connection

纵饮孤独 提交于 2019-12-25 08:47:02

问题


The following code crashes when is no interenet connection :

    public String gourl(String myurl,String params) {

        URL url;
        String rasp = "";

        try {
            url = new URL(myurl + params);
            BufferedReader rd = new BufferedReader(new InputStreamReader(
                    url.openStream()));
            String line = "";
            while ((line = rd.readLine()) != null) {
                rasp=rasp + line;
            }

            return rasp;
        } catch (Exception e) {
            Log.w("DHA", "EXCEPTIE URL");
        }       
        return null;
}

How can i prevent this from happening ?


回答1:


Check connection before execute your method, something like that:

    public boolean isNetworkConnected() {
         final ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
         final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
         return activeNetwork != null && activeNetwork.getState() == NetworkInfo.State.CONNECTED;
    }



回答2:


Have you checked what the values of myurl and params are in the method?

It may be that url.openStream() is failing and causing a NullPointerException.

It's also helpful to rather do something like:

Log.w("DHA", "EXCEPTIE URL:" + e.toString());

Then you will see what the Exception is rather than having to guess.




回答3:


Check for all Internet connection

For Wifi

    public boolean isWifi(Context context){
    try{
    WifiManager wifi=(WifiManager) 

context.getSystemService(Context.WIFI_SERVICE);
    if(wifi.isWifiEnabled()){
    return true;
    }else{
        return false;
    }
    }
    catch(Exception e){
        e.getMessage();
        return false;
    }
}

For Other Network

    public  boolean isOline(Context context){
    try{
        ConnectivityManager cm=(ConnectivityManager) 

   context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if(cm==null)
            return false;
        NetworkInfo info=cm.getActiveNetworkInfo();
        if(info==null)
            return false;
        return info.isConnectedOrConnecting();
    }
    catch(Exception e){
        e.getMessage();
        return false;
    }
}  

If any of them is present then process WS else show alert.And Never forget to mention

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


来源:https://stackoverflow.com/questions/9908137/crash-when-is-no-internet-connection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!