在没有网络连接的情况下改造+ RxJava FATAL MAIN

时间:2016-10-09 15:19:13

标签: android retrofit rx-java retrofit2

我有这个奇怪的错误 - 当我登录(有网络连接)然后我禁用网络然后当我尝试syncOne()我得到:

    10-09 16:47:22.986 23444-23444/package.app.whatever E/asd-local-error: java.net.UnknownHostException: Unable to resolve host "cbm.aype.pl": No address associated with hostname/libcore.io.GaiException: getaddrinfo failed: EAI_NODATA (No address associated with hostname)/java.net.UnknownHostException: Unable to resolve host "myhost.com": No address associated with hostname
10-09 16:47:22.986 23444-23444/package.app.whatever E/AndroidRuntime: FATAL EXCEPTION: main
                                                             Process: package.app.whatever, PID: 23444
10-09 16:47:23.071 2445-2898/? E/Watchdog: !@Sync 4443
10-09 16:47:23.306 2445-24874/? E/android.os.Debug: !@Dumpstate > sdumpstate -k -t -z -d -o /data/log/dumpstate_app_error

我读到Retrofit会抛出IOException而没有可用的网络连接,但我不知道如何抓住它。这是正确的代码:

 private void syncOne(){
    RealmResults<CallLog> res = Realm.getDefaultInstance()
            .where(CallLog.class)
            .equalTo(Constants.EXTRA_CALL_LOG_PRIVATE, false)
            .equalTo(Constants.EXTRA_CALL_LOG_DEFAULT_SYNC, true)
            .greaterThan(Constants.EXTRA_CALL_LOG_DATE_EDIT, Utils.getUTCToDate(lastSuccessfulSync))
            .findAll();

    listCallLogs.addAll(res);

    String json = jsonCallLogAdapter.toJson(listCallLogs);

    Log.d("asd-1json1", json);

    Subscription sendLogs = networkClient
            .sendCallLogs(token, RequestBody.create(MediaType.parse("application/json"), json))
            .flatMap(response -> {
                return networkClient.getCallLogsAfterDate(token, lastSuccessfulSync);
            })
            .flatMap(response ->{
                String json2 = "";
                try {
                    json2 = response.body().string();
                    listCallLogs.clear();
                    listCallLogs = jsonCallLogAdapter.fromJson(json2);
                    Log.d("asd-1json2", json2);
                } catch (IOException e){
                    Log.e("IOException", e.toString());
                }

                RealmResults<Contact> res3 = Realm.getDefaultInstance()
                        .where(Contact.class)
                        .equalTo(Constants.EXTRA_CONTACT_PRIVATE, false)
                        .greaterThan(Constants.EXTRA_CONTACT_DATE_EDIT, Utils.getUTCToDate(lastSuccessfulSync))
                        .findAll();
                listContacts.clear();
                listContacts.addAll(res3);

                String json3 = jsonContactAdapter.toJson(listContacts);

                Log.i("asd-1json3", json3);

                return networkClient.sendContacts(token, (RequestBody.create(MediaType.parse("application/json"), json3)));
            })
            .flatMap(response -> {
                return networkClient.getContactsAfterDate(token, lastSuccessfulSync);
            })
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                    response -> {
                        stopRefreshing(swipeRefreshLayout);
                        if(response.isSuccessful()){
                            try {
                                Log.d("asd-1json4", response.body().string());
                                SharedPreferences.Editor editor = userdata.edit();
                                editor.putString(Constants.EXTRA_LAST_SYNC, Utils.getDateInUTC(Calendar.getInstance().getTime()));
                                editor.commit();

                                Toast.makeText(c,
                                        c.getResources().getString(R.string.synchronization_database_synced),
                                        Toast.LENGTH_SHORT).show();

                            } catch (IOException e){
                                Log.d("asd-sync-one-error", e.toString());
                            }
                        } else {
                            try{
                                String s = response.errorBody().string();
                                Log.e("asd-server-error", s);
                                Toast.makeText(c,
                                        c.getResources().getString(R.string.synchronization_error_sending_logs_server),
                                        Toast.LENGTH_SHORT).show();

                            } catch (IOException e){
                                e.printStackTrace();
                            }
                        }
                    },
                    error -> {

                        if(error instanceof IOException){

                        }
                        stopRefreshing(swipeRefreshLayout);

                        Toast.makeText(c,
                                c.getResources().getString(R.string.synchronization_error_sending_logs_local),
                                Toast.LENGTH_SHORT).show();

                        Log.e("asd-local-error", error.toString()
                                + "/" + error.getCause()
                                + "/" + error);

                        Crashlytics.logException(error);
                    });
}

1 个答案:

答案 0 :(得分:1)

不知道这个错误是怎么发生的,但我有一个预防性解决方案。

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

现在当你像这样调用syn检查时

if(isNetworkAvailable()){
 doSync()
}

在你的清单中添加一项权限

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

希望最好!