Quantcast
Channel: How can I fix 'android.os.NetworkOnMainThreadException'? - Stack Overflow
Viewing all articles
Browse latest Browse all 191

Answer by Alex Shutov for How do I fix 'android.os.NetworkOnMainThreadException'?

$
0
0

There is another very convenient way for tackling this issue - use rxJava's concurrency capabilities. You can execute any task in background and post results to main thread in a very convenient way, so these results will be handed to processing chain.

The first verified answer advice is to use AsynTask. Yes, this is a solution, but it is obsolete nowadays, because there are new tools around.

String getUrl() {
    return "SomeUrl";
}

private Object makeCallParseResponse(String url) {
    return null;
    //
}

private void processResponse(Object o) {

}

The getUrl method provides the URL address, and it will be executed on the main thread.

makeCallParseResponse(..) - does actual work

processResponse(..) - will handle result on main thread.

The code for asynchronous execution will look like:

rx.Observable.defer(new Func0<rx.Observable<String>>() {
    @Override
    public rx.Observable<String> call() {
        return rx.Observable.just(getUrl());
    }
})
    .subscribeOn(Schedulers.io())
    .observeOn(Schedulers.io())
    .map(new Func1<String, Object>() {
        @Override
        public Object call(final String s) {
            return makeCallParseResponse(s);
        }
    })
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(new Action1<Object>() {
        @Override
        public void call(Object o) {
             processResponse(o);
        }
    },
    new Action1<Throwable>() {
        @Override
        public void call(Throwable throwable) {
            // Process error here, it will be posted on
            // the main thread
        }
    });

Compared to AsyncTask, this method allow to switch schedulers an arbitrary number of times (say, fetch data on one scheduler and process those data on another (say, Scheduler.computation()). You can also define you own schedulers.

In order to use this library, include following lines into you build.gradle file:

   compile 'io.reactivex:rxjava:1.1.5'
   compile 'io.reactivex:rxandroid:1.2.0'

The last dependency includes support for the .mainThread() scheduler.

There is an excellent ebook for rx-java.


Viewing all articles
Browse latest Browse all 191

Trending Articles