简体   繁体   中英

App crashes when no internet connection

I am working on a android project in which users try to upload their files into AWS S3. Developer authentication is done using AWS Cognito. So here the process is before user tries to upload files into S3, user has to get Credentials using AWS Cogntio. And after that users upload files. This process happens at the background when user select files and click OK. Everything goes fine if internet is available. Otherwise app crashes. Here is part of code.

Here Auth class extends AWSAbstractCognitoDeveloperIdentityProvider.

     Auth developerProvider = new Auth(
                    null,
                    "ap-northeast-1:a871fa5f-2-480d-baa6-b4ed31437244",
                    Regions.AP_NORTHEAST_1);

     CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider(
                    this.ctx.getApplicationContext(),
                    developerProvider,
                    Regions.AP_NORTHEAST_1);

            HashMap<String, String> loginsMap = new HashMap<String, String>();
            loginsMap.put("login.cool.app", "7386872");
            credentialsProvider.setLogins(loginsMap);
            credentialsProvider.refresh();

App crashing at this line

           credentialsProvider.refresh();

Error it showing:

        I/AmazonHttpClient: Unable to execute HTTP request: Unable to resolve host "cognito-identity.ap-northeast-1.amazonaws.com": No address associated with hostname
                                               java.net.UnknownHostException: Unable to resolve host "cognito-identity.ap-northeast-1.amazonaws.com": No address associated with hostname
                                                   at java.net.InetAddress.lookupHostByName(InetAddress.java:427)
                                                   at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
                                                   at java.net.InetAddress.getAllByName(InetAddress.java:215)
                                                   at com.android.okhttp.HostResolver$1.getAllByName(HostResolver.java:29)
                                                   at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:232)
                                                   at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:124)
                                                   at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:272)
                                                   at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
                                                   at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:382)
                                                   at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:106)
                                                   at com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:217)
                                                   at com.android.okhttp.internal.http.DelegatingHttpsURLConnection.getOutputStream(DelegatingHttpsURLConnection.java:218)
                                                   at com.android.okhttp.internal.http.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:25)
                                                   at com.amazonaws.http.UrlHttpClient.writeContentToConnection(UrlHttpClient.java:128)
                                                   at com.amazonaws.http.UrlHttpClient.execute(UrlHttpClient.java:65)
                                                   at com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:353)
                                                   at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:196)
                                                   at com.amazonaws.services.cognitoidentity.AmazonCognitoIdentityClient.invoke(AmazonCognitoIdentityClient.java:533)
                                                   at com.amazonaws.services.cognitoidentity.AmazonCognitoIdentityClient.getCredentialsForIdentity(AmazonCognitoIdentityClient.java:406)
                                                   at com.amazonaws.auth.CognitoCredentialsProvider.populateCredentialsWithCognito(CognitoCredentialsProvider.java:627)
                                                   at com.amazonaws.auth.CognitoCredentialsProvider.startSession(CognitoCredentialsProvider.java:553)
                                                   at com.amazonaws.auth.CognitoCredentialsProvider.refresh(CognitoCredentialsProvider.java:503)
                                                   at com.amazonaws.auth.CognitoCachingCredentialsProvider.refresh(CognitoCachingCredentialsProvider.java:462)
                                                   at com.amazonaws.auth.CognitoCachingCredentialsProvider.getIdentityId(CognitoCachingCredentialsProvider.java:413)
                                                   at com.amazonaws.auth.CognitoCredentialsProvider.populateCredentialsWithCognito(CognitoCredentialsProvider.java:620)
                                                   at com.amazonaws.auth.CognitoCredentialsProvider.startSession(CognitoCredentialsProvider.java:553)
                                                   at com.amazonaws.auth.CognitoCredentialsProvider.refresh(CognitoCredentialsProvider.java:503)
                                                   at com.amazonaws.auth.CognitoCachingCredentialsProvider.refresh(CognitoCachingCredentialsProvider.java:462)
                                                   at com.example.sandesh.filer.UpDown.upload.doInBackground(upload.java:89)
                                                   at com.example.sandesh.filer.UpDown.upload.doInBackground(upload.java:27)
                                                   at android.os.AsyncTask$2.call(AsyncTask.java:292)
                                                   at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                   at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
                                                   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
                                                   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
                                                   at java.lang.Thread.run(Thread.java:818)

Is there anyway to try catch it? or Any solution to avoid crashing?

Thank you.

Once I had implemented a check in my app, to see if there is any internet connection or not. You can have a look at this and decide if you are going to implement this.

public class ConnectionDetector {

    private Context context;

    public ConnectionDetector(Context cont) {
        this.context = cont;
    }

    public boolean isConnectingToInternet() {
        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }

        }
        return false;
    }
}

You can initialize an object of this class in your OnCreate method.

And finally call this class' method just before you upload files.

ConnectionDetector connectionDetector = new ConnectionDetector(mContext);
Boolean isInternetConnected = connectionDetector.isConnectingToInternet();

if (isInternetConnected) {
    //Do your stuff
} else {

    Toast.makeText(mContext, "Please Check Your Internet Connection", Toast.LENGTH_LONG).show();
}

Hope this helps.

After lot of struggle I figured it. The problem is causing because of low and weak Internet connection. Although app connected to internet but that is not an active internet connection. Could not access. So I solved by checking if app connected to internet and finding if the internet is accessible by pinging google.com. Thank you.

       public class internetchek extends AsyncTask<Void,Void,Void> {

public boolean connection;
Context ctx;
public internetchek(Context context){
    this.ctx = context;
}
public internetchek(){

}
@Override
protected void onPreExecute() {
    super.onPreExecute();
}

@Override
protected Void doInBackground(Void... params) {

    if(isNetworkAvailable(this.ctx))
    {

     Log.d("NetworkAvailable","TRUE");
        if(connectGoogle())
        {

            Log.d("GooglePing","TRUE");
            connection=true;
        }
        else
        {

            Log.d("GooglePing","FALSE");
            connection=false;
        }
    }
    else {

        connection=false;
    }


    return null;
}

@Override
protected void onPostExecute(Void aVoid) {
    super.onPostExecute(aVoid);
}

public static boolean isNetworkAvailable(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnected()) {
        return true;
    }
    return false;
}

public static boolean connectGoogle() {
    try {
        HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
        urlc.setRequestProperty("User-Agent", "Test");
        urlc.setRequestProperty("Connection", "close");
        urlc.setConnectTimeout(10000);
        urlc.connect();
        return (urlc.getResponseCode() == 200);

    } catch (IOException e) {

        Log.d("GooglePing","IOEXCEPTION");
        e.printStackTrace();
        return false;
    }
}

}

You can surround your code with try/catch.

try {
    //your code
} catch(Exception e) { 
Toast.makeText(getApplicationContext(), "Error connecting to network.", Toast.LENGTH_SHORT).show();
}

However the unnecessary running of your code can be prevented by doing a network check right before you execute it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM