Сеть Android недоступна - ENETUNREACH

У меня возникла странная ошибка в моем приложении для Android. Я тестирую локальный сервер с помощью Xampp. Приложение должно извлекать записи из базы данных и хранить их в телефоне.

Дело в том, что я тестировал приложение в Motorola XT550 с Android 2.3.6 и в своем Sony Xperia S с Android 4.0.4, и приложение работает отлично. Но когда я тестирую его с помощью Samsung Fame с Android 4.1.2 (мой клиентский телефон), он не работает.

Вот LogCat:

02-22 04:48:33.001    3961-3976/com.sistel.manantiales W/System.err﹕ at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:183)
02-22 04:48:33.001    3961-3976/com.sistel.manantiales W/System.err﹕ at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
02-22 04:48:33.001    3961-3976/com.sistel.manantiales W/System.err﹕ at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
02-22 04:48:33.011    3961-3976/com.sistel.manantiales W/System.err﹕ at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
02-22 04:48:33.011    3961-3976/com.sistel.manantiales W/System.err﹕ at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:670)
02-22 04:48:33.011    3961-3976/com.sistel.manantiales W/System.err﹕ at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:509)
02-22 04:48:33.011    3961-3976/com.sistel.manantiales W/System.err﹕ at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
02-22 04:48:33.011    3961-3976/com.sistel.manantiales W/System.err﹕ at com.sistel.manantiales.SyncActivity$DatabaseSync.updateDatabase(SyncActivity.java:198)
02-22 04:48:33.011    3961-3976/com.sistel.manantiales W/System.err﹕ at com.sistel.manantiales.SyncActivity$DatabaseSync.doInBackground(SyncActivity.java:165)
02-22 04:48:33.011    3961-3976/com.sistel.manantiales W/System.err﹕ at com.sistel.manantiales.SyncActivity$DatabaseSync.doInBackground(SyncActivity.java:147)
02-22 04:48:33.011    3961-3976/com.sistel.manantiales W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:287)
02-22 04:48:33.011    3961-3976/com.sistel.manantiales W/System.err﹕ at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
02-22 04:48:33.011    3961-3976/com.sistel.manantiales W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:137)
02-22 04:48:33.021    3961-3976/com.sistel.manantiales W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
02-22 04:48:33.021    3961-3976/com.sistel.manantiales W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
02-22 04:48:33.021    3961-3976/com.sistel.manantiales W/System.err﹕ at java.lang.Thread.run(Thread.java:856)
02-22 04:48:33.021    3961-3976/com.sistel.manantiales W/System.err﹕ Caused by: java.net.ConnectException: failed to connect to /10.0.0.7 (port 80) after 15000ms: connect failed: ENETUNREACH (Network is unreachable)
02-22 04:48:33.021    3961-3976/com.sistel.manantiales W/System.err﹕ at libcore.io.IoBridge.connect(IoBridge.java:114)
02-22 04:48:33.031    3961-3976/com.sistel.manantiales W/System.err﹕ at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
02-22 04:48:33.031    3961-3976/com.sistel.manantiales W/System.err﹕ at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
02-22 04:48:33.031    3961-3976/com.sistel.manantiales W/System.err﹕ at java.net.Socket.connect(Socket.java:842)
02-22 04:48:33.031    3961-3976/com.sistel.manantiales W/System.err﹕ at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
02-22 04:48:33.031    3961-3976/com.sistel.manantiales W/System.err﹕ at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
02-22 04:48:33.031    3961-3976/com.sistel.manantiales W/System.err﹕ ... 15 more
02-22 04:48:33.041    3961-3976/com.sistel.manantiales W/System.err﹕ Caused by: libcore.io.ErrnoException: connect failed: ENETUNREACH (Network is unreachable)
02-22 04:48:33.081    1216-1467/? V/AudioFlinger﹕ presentationComplete() session 35 complete: framesWritten 940032
02-22 04:48:33.081    1216-1467/? V/AudioFlinger﹕ TrackBase::reset
02-22 04:48:33.091    3961-3976/com.sistel.manantiales W/System.err﹕ at libcore.io.Posix.connect(Native Method)
02-22 04:48:33.091    3961-3964/com.sistel.manantiales D/dalvikvm﹕ GC_CONCURRENT freed 197K, 13% free 7645K/8775K, paused 16ms+16ms, total 54ms
02-22 04:48:33.091    3961-3976/com.sistel.manantiales W/System.err﹕ at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:85)
02-22 04:48:33.091    3961-3976/com.sistel.manantiales W/System.err﹕ at libcore.io.IoBridge.connectErrno(IoBridge.java:144)
02-22 04:48:33.101    3961-3976/com.sistel.manantiales W/System.err﹕ at libcore.io.IoBridge.connect(IoBridge.java:112)
02-22 04:48:33.101    3961-3976/com.sistel.manantiales W/System.err﹕ ... 20 more
02-22 04:48:33.101    1577-1800/? D/PowerManagerService﹕ acquireDVFSLockLocked : type : DVFS_MIN_LIMIT  frequency : 999999  uid : 1000  pid : 1577  tag : ActivityManager
02-22 04:48:33.101    1577-1800/? W/ActivityManager﹕ mDVFSLock.acquire()
02-22 04:48:33.141    1577-1800/? D/BatteryStatsImpl﹕ ++++++xy WakeLock start : pid=1577, name=, type=0, tid=1800, pid=1577, pName=null
02-22 04:48:33.161    1577-1588/? D/WindowManager﹕ PhoneWindowManager: focusChangedLw
02-22 04:48:33.161    1577-1588/? D/WindowManager﹕ updateReadingMode
02-22 04:48:33.161    1577-1588/? D/KeyguardViewMediator﹕ setHidden false
02-22 04:48:33.161    1577-1588/? D/WindowManager﹕ mInputFocus is not null.
02-22 04:48:33.161    1577-1588/? D/WindowManager﹕ mInputFocus is not null.
02-22 04:48:33.161    1577-1588/? D/WindowManager﹕ mInputFocus is not null.
02-22 04:48:33.191    3961-3961/com.sistel.manantiales D/AbsListView﹕ Get MotionRecognitionManager
02-22 04:48:33.211    3961-3976/com.sistel.manantiales W/dalvikvm﹕ threadid=11: thread exiting with uncaught exception (group=0x411ba2a0)
02-22 04:48:33.211    1577-1810/? D/WindowManager﹕ mInputFocus is not null.
02-22 04:48:33.211    3961-3976/com.sistel.manantiales E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
        java.lang.RuntimeException: An error occured while executing doInBackground()
        at android.os.AsyncTask$3.done(AsyncTask.java:299)
        at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
        at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
        at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
        at java.util.concurrent.FutureTask.run(FutureTask.java:137)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
        at java.lang.Thread.run(Thread.java:856)
        Caused by: java.lang.IllegalArgumentException: HTTP entity may not be null
        at org.apache.http.util.EntityUtils.toString(EntityUtils.java:110)
        at org.apache.http.util.EntityUtils.toString(EntityUtils.java:146)
        at com.sistel.manantiales.SyncActivity$DatabaseSync.updateDatabase(SyncActivity.java:217)
        at com.sistel.manantiales.SyncActivity$DatabaseSync.doInBackground(SyncActivity.java:165)
        at com.sistel.manantiales.SyncActivity$DatabaseSync.doInBackground(SyncActivity.java:147)
        at android.os.AsyncTask$2.call(AsyncTask.java:287)
        at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)

И вот мой код:

public class DatabaseSync extends AsyncTask<String, Void, Boolean> {

        @Override
        protected Boolean doInBackground(String... url) {

            try {
                clientDataSource.open();
            } catch (SQLException e) {
                e.printStackTrace();
            }

            try {
                movementDataSource.open();
            } catch (SQLException e) {
                e.printStackTrace();
            }

            clientDataSource.deleteAllClients();
            updateDatabase(url[0]);

            return null;
        }

        @Override
        protected void onPostExecute(Boolean bool) {
            super.onPostExecute(bool);
        }

        public void updateDatabase(String url) {

                ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("Operation", "Download"));
                nameValuePairs.add(new BasicNameValuePair("Value", "Download"));

                HttpParams httpParams = new BasicHttpParams();

                HttpConnectionParams.setConnectionTimeout(httpParams, 15000);
                HttpConnectionParams.setSoTimeout(httpParams, 15000);

            HttpClient httpClient = new DefaultHttpClient(httpParams);
            HttpPost httpPost = new HttpPost(url);

            try {
                httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            HttpResponse httpResponse = null;

            try {
                httpResponse = httpClient.execute(httpPost);
            } catch (IOException e) {
                e.printStackTrace();
            }

            HttpEntity httpEntity = null;

            try {
                httpEntity = httpResponse.getEntity();
            }catch (NullPointerException e) {

                Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                startActivity(intent);

            }


            String result = "empty";
            try {
                result = EntityUtils.toString(httpEntity);
            } catch (IOException e) {
                e.printStackTrace();
            }

            JSONObject jsonObject = null;
            try {
                jsonObject = new JSONObject(result);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            JSONArray jsonClients = null;

            try {
                jsonClients =  jsonObject.getJSONArray("clients");
            } catch (JSONException e) {
                e.printStackTrace();
            }

            long id = 0;
            String name;
            String address;
            String locality;
            long bonus = 0;
            double price = 0.0;
            double prev_balance = 0.0;
            double balance = 0.0;
            long prev_bottles = 0;
            long bottles = 0;
            String update_date;
            String sync_date;

            for(int i = 0; i < jsonClients.length(); i++) {
                JSONObject json = null;
                try {
                    json = jsonClients.getJSONObject(i);

                    String s_id = new String(Base64.decode(json.get("id").toString(),Base64.DEFAULT));
                    name = new String(Base64.decode(json.get("name").toString(),Base64.DEFAULT));
                    address = new String(Base64.decode(json.get("address").toString(), Base64.DEFAULT));
                    locality = new String(Base64.decode(json.get("locality").toString(), Base64.DEFAULT));
                    String s_bonus = new String(Base64.decode(json.get("bonus").toString(), Base64.DEFAULT));
                    String s_price = new String(Base64.decode(json.get("price").toString(), Base64.DEFAULT));
                    String s_prev_balance = new String(Base64.decode(json.get("prev_balance").toString(), Base64.DEFAULT));
                    String s_balance = new String(Base64.decode(json.get("balance").toString(), Base64.DEFAULT));
                    String s_prev_bottles = new String(Base64.decode(json.get("prev_bottles").toString(), Base64.DEFAULT));
                    String s_bottles = new String(Base64.decode(json.get("bottles").toString(), Base64.DEFAULT));
                    update_date = new String(Base64.decode(json.get("update_date").toString(), Base64.DEFAULT));
                    sync_date = new String(Base64.decode(json.get("sync_date").toString(), Base64.DEFAULT));

                    id = Long.parseLong(s_id);
                    bonus = Long.parseLong(s_bonus);
                    price = Double.parseDouble(s_price);
                    prev_balance = Double.parseDouble(s_prev_balance);
                    balance = Double.parseDouble(s_balance);
                    prev_bottles = Long.parseLong(s_prev_bottles);
                    bottles = Long.parseLong(s_bottles);

                    Client client = new Client(id, name, address, locality, bonus, price,
                            prev_balance, balance, prev_bottles, bottles, update_date, sync_date);

                    clientDataSource.insertClient(client);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            Intent intent = new Intent(getApplicationContext(), MainActivity.class);
            startActivity(intent);

        }

    }

Ответ 1

Я выяснил, в чем проблема! Samsung Fame не была подключена к Wi-Fi. У него не было интернета.

Ответ 2

Вы также можете добавить проверку на подключение к Интернету, прежде чем делать какие-либо запросы, чтобы пользователь не узнал, что интернет не существует.

Используйте код ниже, и если он возвращает ложное шоу Toast/Alert.

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

Ответ 3

У вас есть случай, когда мое приложение подключается, а затем отключите wifi > сбой приложения и он не может войти в команду catch Exception.