Network error андроид

I got a React-Native application working with a NodeJS backend which serves an API. My React-Native front is using Expo and Axios to hit on a route of my NodeJS API (using Hapi, Joi, Knex), which ...

I got a React-Native application working with a NodeJS backend which serves an API.

My React-Native front is using Expo and Axios to hit on a route of my NodeJS API (using Hapi, Joi, Knex), which will (for the example) update my DB (MySQL).

Everything works properly with my iOS simulator. However, on Android Emulator, SOME of my hits on route «»does not work»» with the following error message : Network Error - node_modules/axios/lib/core/createError.js:16:24 in createError (actually, it worked, but the front does not detect it…)

This is strange, because like I said, this is ONLY for some of my route. I changed the http://localhost:8000/api to http://10.0.2.2:8000/api to be sure that Android Emulator access my API, and it is ok for this part.

The buggy route is working properly on iOS, and is working properly on Insomnia / Postman ( localhost:8000/api/sendMail ). It is working on Android Emulator, but the application does not detect it.

This is an example of my code :

FRONT — On press of my button «SendEmail» :

/* Button.js */
const sendAndEmailPromise = await sendEmail(this.state.email);

console.log(sendAndEmailPromise); // Output : NOTHING (not undefined, not null, N O T H I N G).

if (sendAndEmailPromise.status === 200) {
    // handle it
} else (sendAndEmailPromise.status === 403) {
    // etc. for each of my codeStatus that can be returned by my API 
}

/* MyAPI.js */
export function sendEmail(mail) {
    return axiosInstance
    .post(`/sendEmail`, null, {
      params: {
        mail
      },
    })
    .then(response => response) // Will not enter here
    .catch(error => {
       console.log(error); // Will output : NETWORK ERROR
    });
}

BACK — This is the sendEmail promise :

// Will return true of false :
const isMailSend = await sendTheEmail(mail);
console.log(isMailSend); // Output : TRUE and I receive the email on my gmail, so Android Emulator HIT the route.

if (isMailSend) {
  return handler
    .response({
      data: {
        message: "Email sent.",
      },
    })
    .code(200);
} else {
  // Handle it and return another response
}

I expect my front to now that everything works fine (which actually happened…) and get the code status of that, instead of a «Network error».

More, is it possible with Axios to get another level of error ? Something more specific.

A GitHub issue which is not totally the same but seems to relate something equivalent : https://github.com/axios/axios/issues/973

Thank you.

Just two months back, I started seeing “Network error, please try again later” toast message at the bottom of my Android phone’s screen. After a full day of annoying interruptions, I decided to fix it. It did take a few experiments and an hour worth of time, but I finally managed to fix the error.

However, just yesterday night I again faced the same error which made me wonder “if I could face this issue twice in just two months, then other users must be facing it as well”. This is why today I am going to fix “Network error, please try again later” error on my Android phone and show you every step I will take to fix it.

Quick fix

Go to Settings > Applications > Google Drive. Here, tap on “Storage” and then tap on “Clear Data” to reset Google Drive data. This should fix “Network error, please try again later” error.

clear google drive data to fix network error please try again later error

This is usually a Google Drive error and the above quick instructions should fix it. If not, then follow the complete guide below to fix the error.

Find the culprit app

The “Network error, please try again later” toast message is caused by a faulty app, particularly, an app working in the background. Previously, I tracked the error’s pattern and noticed that it always displayed when I used a Google app. Which lead to the conclusion that the Google Drive app syncing must be causing the issue.

Fortunately for you, you won’t have to do that tiring tracking like I had to do. Because this time I have found an Android app that could track the source of toast messages and let you know which app caused it.

The app name is Toast Source and it’s a completely free app without any ads. Let’s see how to use it:

1. Download the Toast Source app and launch it.

2. Tap on the “Yes” button on the “Enable accessibility service?” prompt and then enable the option “Toast Source Detection Service”.

enable accessibility service for app

3. Come back to the app and enable the option “Save to database” so all the toast messages could be saved.

save database of toast source app

4. Now do that exact task that usually causes that toast message to appear. In my case, it appears when I open up a document in Google Docs (see the below screenshot).

error message on google docs app

5. When the toast message appears, come back to the Toast Source app and tap on the “Show saved toasts” option. You’ll see the app name that caused the issue (It’s Google Drive in my case).

toast source identified the app

Fix “Network error, please try again later” error

Now that you know the app which is causing the error, it’s time to fix it. Simply deleting all of the app’s data or uninstalling it (if you don’t need it) is a sure shot way to fix the issue. However, these solutions lead to losing data. Therefore, I am going to start with a basic working solution and then move to that drastic solution.

Solution 1: Force stop the app

Simply stopping the app’s background processes and restarting it usually solves this problem (worked for me when I first had the issue). Here’s how to force stop an app:

  1. Go to “Settings” and tap on “Applications”.
  2. Now tap on the app that is causing the toast message and then tap on “Force Stop”. You’ll have to confirm a prompt to stop the app.

force stop app

This will halt the functioning of the app until it is restarted again from the app drawer. You can restart the app to see if this solved the problem or not. In my case, it didn’t solve the problem this time, so I am moving to the next solution instead.

Solution 2: Delete app cache and Data

If the above didn’t solve your problem, then, unfortunately, you’ll have to reset app data. Make sure that the app doesn’t contain any important local data before following the below steps. As for me, Google Drive doesn’t record much local data, so I can safely delete its data without any worries. Here’s how:

  1. Again move to the app details page like we did in the above solution.
  2. Here tap on the “Storage” option.
  3. Now first tap on “Clear Cache” and see if this fixes the problem. If not, then click on “Clear Data” and this will fix “Network error, please try again later” error.

delete app data to fix error

After clearing Google Drive app data, my issue has been resolved for now. I’ll update this article if I’ll face this error again, or if I could find out the reason why this error occurs in the first place.

If you know any other easier way to solve “Network error, please try again later” error on Android, do share with us in the comments. Additionally, if the above instructions didn’t solve your problem, provide all the details of the error and we may be able to help.

01 August, 2019
2
MIN READ

01 August, 2019
2
MIN READ

While accessing an API within the Android application you might be haunted with the ‘Network Error`:

Network Error in Android Application Development

| What do these errors indicate? 

These errors state that the request you tried to make did not reach your remote server. Be it a hosted API or your local machine. These errors may occur under the following scenarios: 

Scenario 1

If we want to serve the mobile app with your local machine’s REST endpoint which has the local server up and running. We must choose “public IP” of the local machine to be the endpoint.

Scenario 2

You can access APIs over HTTP pointing to a domain name or an IP.  However, these approaches are not suggested as you wouldn’t want your APIs to be unsecured or the server’s IP to be used as an endpoint.

Scenario 3

If you access the API over HTTPS with a domain name and receive a “Network Error”. Try checking the access logs and error logs of the servers to check if the API messed up with the “request” or did the request never reach the server. If the request did not reach the server, this indicates the REST endpoint is rejected to be served by the Android itself.

| Solution

To resolve this issue check if your SSL certificates on the servers are correctly installed. Go to: https://www.ssllabs.com/ssltest/ to find more about your SSL certificate.

Network Error in Android Application Development

If you get the warning “certificate chain is incomplete” and the overall rating is below “A+”. Try resolving the issue by installing the complete certificate chain on the respective server and check for the ratings again.

Copy the certificate :
cp mydomain-2019.crt mydomain-2019.pem

Add the Intermediate Certificate to your SSL Certificate
cat intermediate.crt >> mydomain-2019.pem

Make sure your mydomain-19.pem is a valid file by checking there should be only 10 ‘-’ in the respective lines and no extra new line in the bottom of the file.

Use the mydomain-2019.pem as a certificate in your server configurations

If things are done right the ratings should be increased to A+

Network Error in Android Application Development

Now your mobile application should be able to access the API over HTTPS with a domain main.

Facing any other issues related to Android applications? We would like to hear about them. Drop us a word at [email protected]

Related Articles

In this post I will show how to handle connection errors or the situation when the connection changes (i.e from UMTS to WI-FI). In all these cases we have to gracefully handle these errors and implement some strategies to try to reconnect if possible.

In a perfect world when we connect to a remote server with HTTP protocol everything works perfectly, we don’t have to worry about connection errors, server under heavy request load or unstable network. In some of last posts we talked about how we can connect to a remote server and how we can send and receive data. In the real world, usually while we are connected to a remote server we walk or run or even we are in car, so that the network signal can vary or it can suddenly break. At the same time Android can device to switch from UMTS to WI-FI or vice versa or it can switch from one APN to another and so on. When we code our app, we have to take into account all these situation and handle them correctly. We can simplify and try to categorize all these events in two classes:

  • Network error
  • Network configuration changes

If we used Apache HTTP Client there’s already a mechanism that helps us, we could implement HttpRequestRetryHandler interface with our retry mechanism logic or a default implementation. If we use the standard Android HTTP connection we have to implement is by ourselves.

Handling connection error

In this post I showed how to connect to a remote server and we created an HttpClient class that manages the connection. In this case we extend this class handling possible network error. To do it we use the call back mechanism, in other word we set up a listener that gets notified when there is a connection error. To do it we create an interface:

public interface HttpConnectionRetryHandler {

    public boolean shouldRetry(Throwable t, int attemptNumber) ;
}

This interface has just only one method where we implement our logic to handle or not the network error. We pass the exception and a counter that holds the number of attempt to re-establish the connection. The HttpClient then has to be modified to handle the connection error. It doesn’t have to raise an exception as soon as it can’t connect to the server but has to ask to our class that implements HttpConnectionRetryHandler if it should raise the exception or try to connect again.

public void connect(String method, Properties props) throws HttpClientException {
    boolean status  = true;
    int attemptNumber = 0;
    while (status) {
        try {
            attemptNumber++;
            doConnection(method, props);
            status = false;
        }
        catch(Throwable t) {
            if (handler != null) {
                status = handler.shouldRetry(t, attemptNumber);
                if (!status)
                    throw new HttpClientException(t);
            }
            else {                    
                throw new HttpClientException(t);
            }
        }
    }

}

At line 12 when we have an exception we call handler.shouldRetry to verify if our connection error handler wants to handle the error or not. If not we raise the exception otherwise we keep on trying to reconnect. In our class that handles the error we implement our business logic. The simplest thing is checking the number of attempt. In this case we have:

public class DefaultHttpConnectionRetryHandler implements HttpConnectionRetryHandler {

    @Override
    public boolean shouldRetry(Throwable t, int attemptNumber) {
        System.out.println("Attempt ["+attemptNumber+"]");
        if (attemptNumber > 5)
            return false;

        return true;
    }

}

So when we call the HttpClient we have:

...
client.setHandler(new DefaultHttpConnectionRetryHandler());
...

Handling network configuration changes

As we said early while we move with our smartphone or tablet the network configuration can chance switching from WI-FI to UMTS or vice versa or from UTMS to switching from one APN to another (maybe in roaming). We have to handle all these changes and try to use the network configurations to re-establish the connection. To handle these events we can use a Broadcast receiver that gets notified when a network configuration change occurs. Changes in APN configuration or in changes in connectivity is handle by ConnectivityManager that broadcast some information to its subscribers. So the first thing we code our broadcast receiver:

public class ConnectionMonitorReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context ctx, Intent intent) {
        System.out.println("Receive..");
        NetworkInfo netInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);

        if (netInfo == null)
            return ;

        System.out.println("Here");
        if (netInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
            String proxyHost = System.getProperty( "http.proxyHost" );

            String proxyPort = System.getProperty( "http.proxyPort" );

            if (proxyHost != null)
                HttpClient.getInstance().setProxy(proxyHost, proxyPort);
            else
                HttpClient.getInstance().setProxy(null, null);

        }
    }
}

At line 1 we simply extends the BroadcastReceiver and we implement onReceive method (line 4). At line 6 we get the information shipped inside the intent broad and implements our logic. In our case we simply check if the proxy is changed but we could implements other type of business logic.

The last thing we have to do is register our broadcast receiver so that it can be called. We do it in our onCreate method of the Activity:

registerReceiver(new ConnectionMonitorReceiver(), new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

Running the code we have:

Immagine1 Immagine2
 

I got a React-Native application working with a NodeJS backend which serves an API.

My React-Native front is using Expo and Axios to hit on a route of my NodeJS API (using Hapi, Joi, Knex), which will (for the example) update my DB (MySQL).

Everything works properly with my iOS simulator. However, on Android Emulator, SOME of my hits on route «»does not work»» with the following error message : Network Error - node_modules/axios/lib/core/createError.js:16:24 in createError (actually, it worked, but the front does not detect it…)

This is strange, because like I said, this is ONLY for some of my route. I changed the http://localhost:8000/api to http://10.0.2.2:8000/api to be sure that Android Emulator access my API, and it is ok for this part.

The buggy route is working properly on iOS, and is working properly on Insomnia / Postman ( localhost:8000/api/sendMail ). It is working on Android Emulator, but the application does not detect it.

This is an example of my code :

FRONT — On press of my button «SendEmail» :

/* Button.js */
const sendAndEmailPromise = await sendEmail(this.state.email);

console.log(sendAndEmailPromise); // Output : NOTHING (not undefined, not null, N O T H I N G).

if (sendAndEmailPromise.status === 200) {
    // handle it
} else (sendAndEmailPromise.status === 403) {
    // etc. for each of my codeStatus that can be returned by my API 
}

/* MyAPI.js */
export function sendEmail(mail) {
    return axiosInstance
    .post(`/sendEmail`, null, {
      params: {
        mail
      },
    })
    .then(response => response) // Will not enter here
    .catch(error => {
       console.log(error); // Will output : NETWORK ERROR
    });
}

BACK — This is the sendEmail promise :

// Will return true of false :
const isMailSend = await sendTheEmail(mail);
console.log(isMailSend); // Output : TRUE and I receive the email on my gmail, so Android Emulator HIT the route.

if (isMailSend) {
  return handler
    .response({
      data: {
        message: "Email sent.",
      },
    })
    .code(200);
} else {
  // Handle it and return another response
}

I expect my front to now that everything works fine (which actually happened…) and get the code status of that, instead of a «Network error».

More, is it possible with Axios to get another level of error ? Something more specific.

A GitHub issue which is not totally the same but seems to relate something equivalent : https://github.com/axios/axios/issues/973

Thank you.

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Network error wildberries акт сверки
  • Network error while fetching file unknown connection error stocksubmitter
  • Network error when attempting to fetch resource что значит
  • Network error unable to lookup host names
  • Network error typeerror failed to fetch вк при входе

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии