By bejoy george


2011-06-14 12:02:00 8 Comments

I got an error while running my Android project for RssReader.

Code:

URL url = new URL(urlToRssFeed);
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader xmlreader = parser.getXMLReader();
RssHandler theRSSHandler = new RssHandler();
xmlreader.setContentHandler(theRSSHandler);
InputSource is = new InputSource(url.openStream());
xmlreader.parse(is);
return theRSSHandler.getFeed();

And it shows the below error:

android.os.NetworkOnMainThreadException

How can I fix this issue?

30 comments

@yoAlex5 2018-03-17 15:58:49

You are able to move a part of your code into another thread to offload the main thread and avoid getting ANR, NetworkOnMainThreadException, IllegalStateException(e.g. Cannot access database on the main thread since it may potentially lock the UI for a long period of time).

There are some approaches that you should choose depends on the situation

Java Thread or Android HandlerThread

Java threads are one-time use only and die after executing its run method.

HandlerThread is a handy class for starting a new thread that has a looper.

AsyncTask

AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent package such as Executor, ThreadPoolExecutor and FutureTask.

Thread pool implementation ThreadPoolExecutor, ScheduledThreadPoolExecutor...

ThreadPoolExecutor class that implements ExecutorService which gives fine control on the thread pool (Eg, core pool size, max pool size, keep alive time, etc.)

ScheduledThreadPoolExecutor - a class that extends ThreadPoolExecutor. It can schedule tasks after a given delay or periodically.

FutureTask

FutureTask performs asynchronous processing, however, if the result is not ready yet or processing has not complete, calling get() will be block the thread

AsyncTaskLoaders

AsyncTaskLoaders as they solve a lot of problems that are inherent to AsyncTask

IntentService

This is the defacto choice for long running processing on Android, a good example would be to upload or download large files. The upload and download may continue even if the user exits the app and you certainly do not want to block the user from being able to use the app while these tasks are going on.

JobScheduler

Effectively, you have to create a Service and create a job using JobInfo.Builder that specifies your criteria for when to run the service.

RxJava

Library for composing asynchronous and event-based programs by using observable sequences.

Coroutines (Kotlin)

The main gist of it is, it makes asynchronous code looks so much like synchronous

Read more here:
8 ways to do asynchronous processing in Android and counting
The Evolution of Android Network Access
Using a Thread Pool in Android
Managing Threads and Custom Services

@Suraj Shingade 2018-03-25 05:46:40

Worked for me ... I have used AsyncTask extensively, but when one task is running another will wait. I want to resolve this. Now working with executeonexecutor. Let's see how it will behave on low memory devices.

@yoAlex5 2018-03-25 07:52:16

Please take a look at the method: asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params); to run your task simultaneously

@Santanu Sur 2019-03-01 17:37:35

You can use Kotlin-coroutines

 class YoutActivity : AppCompatActivity, CoroutineScope {

      override fun onCreate(...) {
         launch {  yourHeavyMethod() }
      }

      suspend fun yourHeavyMethod() {
         async{ yourNetworkCall() }.await()
         ...
         ...
      }

 } 

You can follow this guide.

@Devix 2018-12-10 22:09:37

If you are working in kotlin and anko you can add

 doAsync {
   method()
}

@dhiraj kakran 2014-03-01 13:43:59

Use this in Your Activity

    btnsub.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new Thread(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub

                    //Initialize soap request + add parameters
                    SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME1);

                    //Use this to add parameters
                    request.addProperty("pincode", txtpincode.getText().toString());
                    request.addProperty("bg", bloodgroup.getSelectedItem().toString());

                    //Declare the version of the SOAP request
                    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

                    envelope.setOutputSoapObject(request);
                    envelope.dotNet = true;

                    try {
                        HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

                        //this is the actual part that will call the webservice
                        androidHttpTransport.call(SOAP_ACTION1, envelope);

                        // Get the SoapResult from the envelope body.
                        SoapObject result = (SoapObject) envelope.getResponse();
                        Log.e("result data", "data" + result);
                        SoapObject root = (SoapObject) result.getProperty(0);
                        // SoapObject s_deals = (SoapObject) root.getProperty(0);
                        // SoapObject s_deals_1 = (SoapObject) s_deals.getProperty(0);
                        //

                        System.out.println("********Count : " + root.getPropertyCount());

                        value = new ArrayList<Detailinfo>();

                        for (int i = 0; i < root.getPropertyCount(); i++) {
                            SoapObject s_deals = (SoapObject) root.getProperty(i);
                            Detailinfo info = new Detailinfo();

                            info.setFirstName(s_deals.getProperty("Firstname").toString());
                            info.setLastName(s_deals.getProperty("Lastname").toString());
                            info.setDOB(s_deals.getProperty("DOB").toString());
                            info.setGender(s_deals.getProperty("Gender").toString());
                            info.setAddress(s_deals.getProperty("Address").toString());
                            info.setCity(s_deals.getProperty("City").toString());
                            info.setState(s_deals.getProperty("State").toString());
                            info.setPinecode(s_deals.getProperty("Pinecode").toString());
                            info.setMobile(s_deals.getProperty("Mobile").toString());
                            info.setEmail(s_deals.getProperty("Email").toString());
                            info.setBloodgroup(s_deals.getProperty("Bloodgroup").toString());
                            info.setAdddate(s_deals.getProperty("Adddate").toString());
                            info.setWaight(s_deals.getProperty("waight").toString());
                            value.add(info);
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    Intent intent = new Intent(getApplicationContext(), ComposeMail.class);
                    //intent.putParcelableArrayListExtra("valuesList", value);

                    startActivity(intent);
                }
            }).start();
        }
    });

@Ashok Kumar 2018-05-10 09:24:39

Different options:

  1. use normal java runnable thread to process network task and can use runOnUIThread() to update the UI

  2. intentservice/ async task can be used in case you want to update the UI after getting network response

@KG6ZVP 2017-10-20 23:50:07

There are many great answers already on this question, but a lot of great libraries have come out since those answers were posted. This is intended as a kind of newbie-guide.

I will cover several use cases for performing network operations and a solution or two for each.

ReST over HTTP

Typically Json, can be XML or something else

Full API Access

Let's say you are writing an app that lets users track stock prices, interest rates and currecy exchange rates. You find an Json API that looks something like this:

http://api.example.com/stocks                       //ResponseWrapper<String> object containing a list of Srings with ticker symbols
http://api.example.com/stocks/$symbol               //Stock object
http://api.example.com/stocks/$symbol/prices        //PriceHistory<Stock> object
http://api.example.com/currencies                   //ResponseWrapper<String> object containing a list of currency abbreviation
http://api.example.com/currencies/$currency         //Currency object
http://api.example.com/currencies/$id1/values/$id2  //PriceHistory<Currency> object comparing the prices of the first currency (id1) to the second (id2)

Retrofit from Square

This is an excellent choice for an API with multiple endpoints and allows you to declare the ReST endpoints instead of having to code them individually as with other libraries like ion or Volley. (website: http://square.github.io/retrofit/)

How do you use it with the finances API?

build.gradle

Add these lines to your Module level buid.gradle:

implementation 'com.squareup.retrofit2:retrofit:2.3.0' //retrofit library, current as of September 21, 2017
implementation 'com.squareup.retrofit2:converter-gson:2.3.0' //gson serialization and deserialization support for retrofit, version must match retrofit version

FinancesApi.java

public interface FinancesApi {
    @GET("stocks")
    Call<ResponseWrapper<String>> listStocks();
    @GET("stocks/{symbol}")
    Call<Stock> getStock(@Path("symbol")String tickerSymbol);
    @GET("stocks/{symbol}/prices")
    Call<PriceHistory<Stock>> getPriceHistory(@Path("symbol")String tickerSymbol);

    @GET("currencies")
    Call<ResponseWrapper<String>> listCurrencies();
    @GET("currencies/{symbol}")
    Call<Currency> getCurrency(@Path("symbol")String currencySymbol);
    @GET("currencies/{symbol}/values/{compare_symbol}")
    Call<PriceHistory<Currency>> getComparativeHistory(@Path("symbol")String currency, @Path("compare_symbol")String currencyToPriceAgainst);
}

FinancesApiBuilder

public class FinancesApiBuilder {
    public static FinancesApi build(String baseUrl){
        return new Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build()
                    .create(FinancesApi.class);
    }
}

FinancesFragment snippet

FinancesApi api = FinancesApiBuilder.build("http://api.example.com/"); //trailing '/' required for predictable behavior
api.getStock("INTC").enqueue(new Callback<Stock>(){
    @Override
    public void onResponse(Call<Stock> stockCall, Response<Stock> stockResponse){
        Stock stock = stockCall.body();
        //do something with the stock
    }
    @Override
    public void onResponse(Call<Stock> stockCall, Throwable t){
        //something bad happened
    }
}

If your API requires an API Key or other header like a user token, etc. to be sent, Retrofit makes this easy (see this awesome answer for details: https://stackoverflow.com/a/42899766/1024412).

One off ReST API access

Let's say you're building a "mood weather" app that looks up the users GPS location and checks the current temperature in that area and tells them the mood. This type of app doesn't need to declare API endpoints; it just needs to be able to access one API endpoint.

Ion

This is a great library for this type of access.

Please read msysmilu's great answer (https://stackoverflow.com/a/28559884/1024412)

Load images via HTTP

Volley

Volley can also be used for ReST APIs, but due to the more complicated setup required I prefer to use Retrofit from Square as above (http://square.github.io/retrofit/)

Let's say you are building a social networking app and want to load profile pictures of friends.

build.gradle

Add this line to your Module level buid.gradle:

implementation 'com.android.volley:volley:1.0.0'

ImageFetch.java

Volley requires more setup than Retrofit. You will need to create a class like this to setup a RequestQueue, an ImageLoader and an ImageCache, but it's not too bad:

public class ImageFetch {
    private static ImageLoader imageLoader = null;
    private static RequestQueue imageQueue = null;

    public static ImageLoader getImageLoader(Context ctx){
        if(imageLoader == null){
            if(imageQueue == null){
                imageQueue = Volley.newRequestQueue(ctx.getApplicationContext());
            }
            imageLoader = new ImageLoader(imageQueue, new ImageLoader.ImageCache() {
                Map<String, Bitmap> cache = new HashMap<String, Bitmap>();
                @Override
                public Bitmap getBitmap(String url) {
                    return cache.get(url);
                }
                @Override
                public void putBitmap(String url, Bitmap bitmap) {
                    cache.put(url, bitmap);
                }
            });
        }
        return imageLoader;
    }
}

user_view_dialog.xml

Add the following to your layout xml file to add an image:

<com.android.volley.toolbox.NetworkImageView
    android:id="@+id/profile_picture"
    android:layout_width="32dp"
    android:layout_height="32dp"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    app:srcCompat="@android:drawable/spinner_background"/>

UserViewDialog.java

Add the following code to the onCreate method (Fragment, Activity) or the constructor (Dialog):

NetworkImageView profilePicture = view.findViewById(R.id.profile_picture);
profilePicture.setImageUrl("http://example.com/users/images/profile.jpg", ImageFetch.getImageLoader(getContext());

Picasso

Another excellent library from Square. Please see the site for some great examples: http://square.github.io/picasso/

@Rakibul Haq 2017-11-28 11:46:46

this should be the better answer than the original one as it simplifies the implementation of networking on android in the present world 2017, and most of the real world application uses very good libraries like these.

@user1169115 2012-02-15 06:59:50

You should almost always run network operations on a thread or as an asynchronous task.

But it is possible to remove this restriction and you override the default behavior, if you are willing to accept the consequences.

Add:

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

StrictMode.setThreadPolicy(policy); 

In your class,

and

ADD this permission in android manifest.xml file:    

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

Consequences:

Your app will (in areas of spotty internet connection) become unresponsive and lock up, the user perceives slowness and has to do a force kill, and you risk the activity manager killing your app and telling the user that the app has stopped.

Android has some good tips on good programming practices to design for responsiveness: http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html

@MByD 2012-05-14 14:10:56

This is a very bad idea. the solution is to avoid network IO on main thread (as the accepted answer shows).

@davs 2012-05-15 13:25:41

@BinyaminSharet, agreed, Network IO can take a lot of time and on main thread can 'freeze' the activity

@Alex 2012-06-18 06:44:01

With this you only hide your real problem.

@Bhagwad Jal Park 2012-08-27 14:48:48

It's a good solution for those who quickly want to test some functionality and don't care if their app takes very long to respond.

@Abandoned Cart 2012-08-28 01:48:03

This may not be the solution to downloading an image gallery, but when you have an app that simply gets some text from a site and displays it to the user, this is MUCH better than a page of added code.

@Zoltán 2012-09-04 09:39:36

@TwistedUmbrella The AsyncTask does not add a page of code, it adds 6 lines (class declaration, override annotation, doInBackground declaration, 2 closing brackets and a call to execute()). On the other hand, even a single fetch from a site as you mention brings a significant lag in the UI responsiveness. Don't be lazy.

@Abandoned Cart 2012-09-08 01:49:09

@Zoltán The AsyncTask (done right) adds the entire declaration of the task itself, the pre and post execute, the calls, the imports, access calls, etc. I have yet to see a single bit of "significant lag in the UI responsiveness" to read and parse a text file. I am not being lazy, just efficient. That is how better apps are made.

@VicVu 2012-09-26 13:14:13

@TwistedUmbrella I definitely have to agree with you. My action is simply to log out. Why should I make an async task for a network interaction whose function is simply to stop all network interactions? Its not being lazy; its not cluttering the app.

@Zoltán 2012-11-01 23:26:58

@TwistedUmbrella If you're reading the txt file, or even just logging out while on a slow connection such as 2G, you WILL see a significant lag.

@Alex Lockwood 2012-12-12 05:00:26

@TwistedUmbrella You are incorrect... you should never perform network requests on the main thread. This is one of the #1 rules when it comes to developing responsive GUIs and it does not only apply to Android... it applies to desktop applications like Swing as well. Network requests depend on a number of other factors, such as geographic proximity, failed/unresponsive servers, lost packets, etc. There is no way to guarantee how long it will take and studies have shown that 0.1 seconds of lag is enough to piss off most users.

@Alex Lockwood 2012-12-12 05:04:24

@TwistedUmbrella That said, I think what you are saying is correct with respect to disk I/O... in general, disk reads/writes should be performed on a separate thread as well because those take a while too. In the case of simply reading 15 lines from a text file stored on disk, however, it would probably take longer to spawn a new thread than it would to simply grab the text directly on the UI thread. But again, this does not apply for network requests because they can take an indeterminate amount of time no matter how large the size of the request.

@Alex Lockwood 2012-12-12 05:06:53

@TwistedUmbrella ...and last but not least, I can't believe there is even a discussion here about an AsyncTask cluttering up your code. It totally does not... just include it as a private inner class at the very bottom of your Activity class. It really isn't that big of a deal, at least in my opinion...

@Abandoned Cart 2012-12-30 00:09:45

@AlexLockwood Your dissertation is interesting, but here is a scenario: Local server hosting a few text files with 3 links each that are generated by PHP, app that needs those links when it starts, and then uses them to connect to other servers. There are very few variables you listed that an async task would handle any differently then a thread, as they both are online tasks. I also made it clear that there are only some scenarios it's beneficial. If you have any further single-minded rants, please direct them to me personally and spare future readers the unnecessary, excessive comments.

@Alex Lockwood 2012-12-30 02:12:26

@TwistedUmbrella TL;DR... don't perform network operations on the main thread. Check the Android Developer site and they will tell you the same thing. The reason why it is called NetworkOnMainThreadException is because they don't want you to perform network operations on the main thread. Further comment withheld.

@Abandoned Cart 2012-12-31 17:36:44

@AlexLockwood After spanning three comments to make a single point, I apologize my single paragraph was too long. Back to the literate crowd, it is important to note that with the code listed there should also be an API check, such as if (Integer.parseInt(Build.VERSION.SDK) >= Build.VERSION_CODES.GINGERBREAD) {

@hooked82 2013-02-09 06:49:20

I think this is the perfect solution if you're looking to just run a sample chunk of code to see if something works before implementing the proper AsyncTask. That's why I upvoted this answer, though as all others have said, this should not be done in a production app, only as a quick workaround for a dev test.

@Seraphim's 2013-02-18 14:11:12

My experience: "touching" StrictMode will cause an application Exception on some devices.

@JaydeepW 2013-04-01 07:48:15

-1 for this answer. Bad Bad idea to do network/ file IO on Main thread of the application. You should not manipulate the policies just to get things working. Use separate thread for networking rather.

@Adam 2013-05-01 06:48:01

Upvoted. This answer is correct, and for the many programmers who are neither naive nor stupid, but who simply require a SYNCHRONOUS (i.e.: this must block the app) call, this is exactly what's needed. I'm more than happy that Android throws the exception by default (IMHO it's a very "helpful" thing to do!) - but I'm equally happy to say "thanks, but - this is actually what I intended" and to override it.

@Peopleware 2013-05-12 10:31:47

There is one reason why this answer is helpful: I disabled throwing the exception to evaluate a socket connection to another device. Now that everyone in our office is convinced of the prototype the networking will be moved to a separate thread. The release version of the application may of course not block its UI.

@カオナシ 2013-05-16 04:23:40

This is a great solution for Android learners to avoid complicating their code unnecessarily by following some stupid "best practices". The idea is to temporarily get away with it to see if the core application works or not. "Best practice" is good for commercial products, but should not be forced to use. E.g. you could give warnings but returning an error and confusing people is really a bad idea. Thumb up for this answer, or just don't thumb it down.

@RvdK 2013-05-22 07:14:01

@TranSonHai: I strongly disagree. If people try to learn Android, they should learn about asynchronous way of working. Adding code to ignore error checkings is a bad idea. Same with adding all Android permissions to your manifest, because you may need to have one...

@カオナシ 2013-05-22 23:00:52

@RvdK The purpose of suppressing warnings is to help learner quickly see if their code works or not, without being bothered by a lot more of extra fancy code following the "best practice". When the learner is certain about their code they could start learning other things such as asynchtask, that's much better than learning too many things right at the beginning.

@Chris Stratton 2013-06-07 23:24:45

@Adam - no, this is not an proper way to accomplish SYNCHRONOUS operation. The proper way to do that is to have your program maintain and depend on a sequence of states. The reason this is not a safe way to do synchronization is that even while part of the user experience may be synchronous, Android may need to urgently deliver other events to the UI thread. If the UI thread is blocked waiting for a slow network, it is impossible for it to do that. With the state method, you hold off on the things which depend on the network result, yet still handle other UI/lifecycle/etc events promptly.

@Adam 2013-06-08 22:56:37

@ChrisStratton why do you assume we're all novices? I'll say it again: I REQUIRED a blocking call. Not "I wanted a sort-of-blocking call that would let the app continue", but an ACTUAL, BLOCKING, CALL. It was critical that the entire app STOP WORKING while this happened. I've been coding in Java for almost 20 years, 10 of them specialising in low-level multithreading systems - I know exactly what I'm doing, and it's infuriating that people who have no idea about my codebase are happy to lecture on "the proper way".

@Chris Stratton 2013-06-09 00:14:08

@Adam - if that's what you believe, then you severely misunderstand how to do event-driven development. Please spend some time to learn about the difference between returning from event calls in a timely fashion as this platform requires vs. having your code not act on events until the whatever necessary prerequisites mandated by your needs have been met. To violate the platform requirements by blocking the UI thread as an unreliable shortcut is simply bad and unprofessional practice.

@Adam 2013-06-09 01:01:10

Or, possibly: I know what I'm doing and why. The question was reasonable, the answer is correct, and those of us who know what we're doing are happy. It seems it gets downvoted by those who have no idea what we're doing, but are all too happy to lecture on it.

@Chris Stratton 2013-06-09 03:16:12

No. Your approach is absolutely wrong as you cannot stop the user from generating UI events. Your contract with the Android platform requires that you permit delivery of these in a timely fashion. The key to solving your problem in a compliant way is realizing that letting android report events to you does not mean that your program has to use those events. Your refusal to adapt to the needs of the platform (such as by using the UI thread for translation only, not sequential program logic) is plainly and simply a refusal to do the job correctly.

@njzk2 2013-08-06 15:00:29

Lazy. If your server fails to respond, your user is stuck.

@Shadow 2014-01-12 08:44:46

Sortof handy just to know for debuggin only - but anyone who implements this sort of a solution in production code should be shot. Even if it is just a small text file.

@autonomy 2014-01-14 18:23:35

This answer is helpful for those of us who need to implement a quick feasibility test and don't need our hands held through implementation.

@OJFord 2014-02-28 06:02:57

+1 for quick and dirty solution. All the naysayers - it is just that. This allowed me to move past an issue I'd been on for hours, and do something more interesting. Surrounded with the comments //!HACKY - CLEAN IT UP LATER. I'll come back to it and do it properly. Good enough for now.

@JRaymond 2014-04-02 22:49:28

To all saying that there is no possible use for this feature: Android throws this Exception regardless of context. We have a Service running in a separate process so that multiple applications can share a common Service through our Library. There is no UI, there is only this networking service - It does not need strict policy checking because we're already interacting with it in a way that does not impede our UI

@RobinJ 2014-08-15 18:40:18

This is a bad idea, but during development I'm just grateful that there's a temporary workaround :)

@CommonsWare 2014-08-26 12:08:52

@JRaymond: You still need a background thread, even in your scenario, as Android will still terminate your work if you take too long on the main application thread. In your case, "too long" is somewhere in the 5-10 second range, last I checked, rather than the couple of millisecond range that would be needed to prevent a janky UI. However, the exact timeout could be modified by device manufacturers, so even if you have your own logic to try to end your work before some fixed duration, that might not be short enough. Forking a thread is simple by comparison and avoids the risk.

@Joseph Lennox 2014-08-28 20:56:30

My main thread isn't a UI thread and it does nothing async. Why not block? +1

@nunofmendes 2014-11-02 13:32:48

This is actually bad practice to be included. I wouldn't be admired if Google actually rejected an app in GooglePlay with this code.

@mim 2015-05-15 00:08:36

In contrary this answer was useful for me, I'm not even blocking the main thread! Instead I started a service on another thread and I need that service to be blocked while waiting for answer! because that thread was made ONLY for this reason and I need it to be a SERVICE not a THREAD or ANOTHER THREAD ON A SERVICE ON A SEPARATE THREAD!! (that would be TWO thread to do ONE job people)

@CommonsWare 2015-05-30 14:25:06

@MimArmand: "I started a service on another thread" -- in Java programming, objects (like a Service) do not run on threads. Methods run on threads. It is not possible to start "a service on another thread". At best, a Service can create a thread and use it, as IntentService does. And, if you do network I/O on that separate thread, you will not get this exception. Conversely, if you are getting this exception, you are doing the work on the main application thread.

@Jordan Rieger 2015-09-18 20:21:37

Just to add to the flame war, can anyone explain why using this non-strict policy to allow network I/O on the main thread would be bad in the following scenario: Suppose your app needs to call an HTTP service that is always expected to return within less than 500ms; you set a timeout on the HTTP call to enforce this. You want the call to block the UI thread because there is no need for the user to interact with the UI during the call. Obviously you could use an AsyncTask and a modal "curtain" over the UI, but why bother if you can do it synchronously with a 500ms timeout?

@CpnCrunch 2015-11-03 00:37:49

Chris, you are incorrect. As Adam points out there are a few cases where this is required. In my case, I have a virtual machine running in my app which has synchronous functions that return an image, for example. I can't just change these synchronous functions to be async, because my virtual machine is defined to work that way. To change that behaviour would require re-architecting my entire application on all platforms, which just isn't reasonable. This workaround may not be ideal, but it works.

@ridsatrio 2015-12-22 12:14:33

This answer simply offered an alternative. It clearly said not to follow this example in production apps. I find this for testing/debugging purposes to be very helpful.

@grantespo 2017-04-07 23:50:33

I would only include this method on my Launchscreen.

@Nathan Osman 2017-04-28 05:01:19

Sure, you should issue all external network requests on a separate thread, but a request to a local server (running on the device) is unlikely to block for any significant amount of time (more than a few ms) and the convenience of performing the request synchronously outweighs the need to do things The Right Way.™

@matec 2018-01-01 13:31:46

To me this is the correct answer to a different question, which could go along the lines of "I have this exception, I know what it means, but in my particular situation I do want to block the application, how can I do that?"

@sharath kumar 2017-09-04 10:43:19

The main thread is the UI thread, and you cannot do an operation in the main thread which may block the user interaction. You can solve this in two ways:

Force to do the task in the main thread like this

StrictMode.ThreadPolicy threadPolicy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(threadPolicy);

Or create a simple handler and update the main thread if you want.

Runnable runnable;
Handler newHandler;

newHandler = new Handler();
runnable = new Runnable() {
    @Override
    public void run() {
         try {
            //update UI
        } catch (Exception e) {
            e.printStackTrace();
        } 
    }
};
newHandler.post(runnable);

And to stop the thread use:

newHandler.removeCallbacks(runnable);

For more information check this out: Painless threading

@Ingo 2018-01-26 14:29:34

Thx. Version 1 helps when adding as first Action in onCreate .

@Elye 2018-01-17 21:54:56

As of 2018, I would recommend to use RxJava in Kotlin for network fetching. A simple example is below.

Single.fromCallable {
        // Your Network Fetching Code
        Network.fetchHttp(url) 
    }
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe {
        // What you need to do with your result on the view 
        result -> view.updateScreen(result) 
    }

@Elye 2018-01-17 21:56:03

You could find the complete code from github.com/elye/demo_android_network_evolution

@Elye 2018-01-17 21:56:50

If you like to look at the overall trend of network access in Android historically to present, check out medium.com/@elye.project/…

@Michael Spector 2011-06-14 12:15:05

This exception is thrown when an application attempts to perform a networking operation on its main thread. Run your code in AsyncTask:

class RetrieveFeedTask extends AsyncTask<String, Void, RSSFeed> {

    private Exception exception;

    protected RSSFeed doInBackground(String... urls) {
        try {
            URL url = new URL(urls[0]);
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser parser = factory.newSAXParser();
            XMLReader xmlreader = parser.getXMLReader();
            RssHandler theRSSHandler = new RssHandler();
            xmlreader.setContentHandler(theRSSHandler);
            InputSource is = new InputSource(url.openStream());
            xmlreader.parse(is);

            return theRSSHandler.getFeed();
        } catch (Exception e) {
            this.exception = e;

            return null;
        } finally {
            is.close();
        }
    }

    protected void onPostExecute(RSSFeed feed) {
        // TODO: check this.exception
        // TODO: do something with the feed
    }
}

How to execute the task:

In MainActivity.java file you can add this line within your oncreate() method

new RetrieveFeedTask().execute(urlToRssFeed);

Don't forget to add this to AndroidManifest.xml file:

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

@dyslexicanaboko 2012-07-22 05:57:08

I think it is worth noting here that the code snippet above is supposed to be a subclass (inner class), preferably private. That way when the AsyncTask finishes, you can still manipulate the innards of your class.

@Dhruv Tyagi 2016-08-30 11:08:21

Actually i did the Same thing as u mentioned above but m facing this error java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

@Brill Pappin 2016-09-09 19:08:12

This is exactly the wrong answer. I come across this all the time in peoples code, and its annoying to have to fix it all the time. AsyncTask should not be used for network activity, because it's tied to the activity, but not the activity lifecycle. Rotating the device with this task is running will cause an exception and crash your app. Use an IntentService that drops data in the sqlite database instead.

@Brill Pappin 2016-10-05 21:24:09

Caution, AsyncTask is often used for per activity network operations when it should not be. its lifecycle is not in sync with the activity. For fetching data, you should use an IntentService and the database behind the view.

@Roman Gherta 2017-09-20 16:51:12

I strongly suggest AsyncTask Loaders for such cases.

@ofekp 2018-04-25 14:23:39

@BrillPappin Please read the section "In Comparison to AsyncTask" in the following link, sometimes AsyncTask is what you need - Starting-Background-Services

@Brill Pappin 2018-04-26 01:22:11

@ofekp not saying its not useful sometimes, but it should never be used for loading remote data through a network connection. Android has extremely good methods of doing that that do not include AsyncTask, and if your architecture depends on that, then you are doing it wrong.

@Chud37 2018-08-08 11:39:43

@BrillPappin can you post an answer of the correct way then?

@Brill Pappin 2018-08-08 15:06:11

There are a few ways, and some new ones I am less familiar with, but two there that would be above AsyncTask our by SyncAdapter, and IntentService. If i interview someone who insists that AsyncTask is the way too go, they go to the bottom the resume pile.

@Brill Pappin 2018-08-08 15:06:17

@Brill Pappin 2018-08-08 15:07:04

I think here are some new techniques in the new Architecture Components that I am not familiar with yet.

@Brill Pappin 2018-08-08 15:08:41

@Sufian 2018-09-25 13:14:36

@BrillPappin I would insist AsyncTask and still get the job. Because if you follow MVP, you're never going to leak the Activity or cause the crash. To make it sweeter, if you follow this MVP template, you'll even retain the AsyncTask on rotation since it uses Loader. However I think the more recent Android Architecture Components might be a better way to solve it now, but not sure since I haven't worked with it.

@Brill Pappin 2018-09-26 04:41:02

Not if I was interviewing you Sufian.

@HeyJude 2019-04-11 22:23:18

@BrillPappin, FWIW, this Android Developer Guide uses AsyncTask, and takes care of a configuration change.

@Ravindra babu 2017-05-05 20:11:56

New Thread and AsyncTask solutions have been explained already.

AsyncTask should ideally be used for short operations. Normal Thread is not preferable for Android.

Have a look at alternate solution using HandlerThread and Handler

HandlerThread

Handy class for starting a new thread that has a looper. The looper can then be used to create handler classes. Note that start() must still be called.

Handler:

A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.

Solution:

  1. Create HandlerThread

  2. Call start() on HandlerThread

  3. Create Handler by getting Looper from HanlerThread

  4. Embed your Network operation related code in Runnable object

  5. Submit Runnable task to Handler

Sample code snippet, which address NetworkOnMainThreadException

HandlerThread handlerThread = new HandlerThread("URLConnection");
handlerThread.start();
handler mainHandler = new Handler(handlerThread.getLooper());

Runnable myRunnable = new Runnable() {
    @Override
    public void run() {
        try {
            Log.d("Ravi", "Before IO call");
            URL page = new URL("http://www.google.com");
            StringBuffer text = new StringBuffer();
            HttpURLConnection conn = (HttpURLConnection) page.openConnection();
            conn.connect();
            InputStreamReader in = new InputStreamReader((InputStream) conn.getContent());
            BufferedReader buff = new BufferedReader(in);
            String line;
            while ( (line =  buff.readLine()) != null) {
                text.append(line + "\n");
            }
            Log.d("Ravi", "After IO call");
            Log.d("Ravi",text.toString());

        }catch( Exception err){
            err.printStackTrace();
        }
    }
};
mainHandler.post(myRunnable);

Pros of using this approach:

  1. Creating new Thread/AsyncTask for each network operation is expensive. The Thread/AsyncTask will be destroyed and re-created for next Network operations. But with Handler and HandlerThread approach, you can submit many network operations (as Runnable tasks) to single HandlerThread by using Handler.

@Thecave3 2019-01-19 17:33:30

This shall be the correct answer.

@Shinoo Goyal 2017-06-09 05:57:25

RxAndroid is another better alternative to this problem and it saves us from hassles of creating threads and then posting results on Android UI thread. We just need to specify threads on which tasks need to be executed and everything is handled internally.

Observable<List<String>> musicShowsObservable = Observable.fromCallable(new Callable<List<String>>() { 

  @Override 
  public List<String> call() { 
    return mRestClient.getFavoriteMusicShows(); 
  }
});

mMusicShowSubscription = musicShowsObservable
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<List<String>>() {

    @Override 
    public void onCompleted() { }

    @Override 
    public void onError(Throwable e) { }

    @Override 
    public void onNext(List<String> musicShows){
        listMusicShows(musicShows);
    }
});
  1. By specifiying (Schedulers.io()),RxAndroid will run getFavoriteMusicShows() on a different thread.

  2. By using AndroidSchedulers.mainThread() we want to observe this Observable on the UI thread, i.e. we want our onNext() callback to be called on the UI thread

@Ashwin S Ashok 2014-07-16 06:09:37

The error is due to executing long running operations in main thread,You can easily rectify the problem by using AsynTask or Thread. You can checkout this library AsyncHTTPClient for better handling.

AsyncHttpClient client = new AsyncHttpClient();
client.get("http://www.google.com", new AsyncHttpResponseHandler() {

    @Override
    public void onStart() {
        // Called before a request is started
    }

    @Override
    public void onSuccess(int statusCode, Header[] headers, byte[] response) {
        // Called when response HTTP status is "200 OK"
    }

    @Override
    public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
        // Called when response HTTP status is "4XX" (for example, 401, 403, 404)
    }

    @Override
    public void onRetry(int retryNo) {
        // Called when request is retried
    }
});

@Rahul 2017-08-01 17:31:34

Never do any long running work on UI thread, that long running work can be communication with server, read/write on file etc. These tasks should be on background thread, thats why Service, AsyncTask, Threads created. You can disable StrictMode that will prevent crash but that never recommended.

I would suggest you take an advantage of StrictMode atleast in Debug mode. Use below code to get logs of any issue which slows down your App on main thread.

StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
            .detectAll()
            .penaltyLog()
            .build());

You can set different penalties -

penaltyLog() // to print log
penaltyDeath() // This will crash you App(so costly penalty)
penaltyDialog() // Show alert when something went lazy on Main thread

There is so much about https://developer.android.com/reference/android/os/StrictMode.html

@J.D.1731 2017-07-10 09:06:55

You can either use KOTLIN and ANKO.

Kotlin is new official language for Android more about it you can find here https://kotlinlang.org/docs/tutorials/kotlin-android.html

Anko supported library for Kotlin in Android, some doc here https://github.com/Kotlin/anko

The solution which is really useful and have only few lines of code written by @AntonioLeiva https://antonioleiva.com/anko-background-kotlin-android/

doAsync {
    var result = runLongTask()
    uiThread {
        toast(result)
    }
}

Simple as it is, NetworkOnMainThread occurs when you run background job on UI Thread so one thing you have to do is to run your longTask job in the background. You can do this using this method and Kotlin with Anko in your Android App.

@Mansuu.... 2017-01-16 04:56:58

android.os.NetworkOnMainThreadException is thrown when network operations are performed on the main thread. You better do this in AsyncTask to remove this Exception. Write it this way:

    new AsyncTask<Void,String,String>(){

        @Override
        protected Void doInBackground(Void... params) {
            // Perform your network operation.
            // Get JSON or XML string from the server.
            // Store in a local variable (say response) and return.
            return response;
        }

        protected void onPostExecute(String results){
            // Response returned by doInBackGround() will be received
            // by onPostExecute(String results).
            // Now manipulate your jason/xml String(results).
        }

    }.execute();
}

@Himanshu 2017-02-19 11:31:11

You can also resolve this issue by using Strict Mode using the below code. It's also an alternative to resolving this issue.

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

But the best practice would be to use AsyncTask.

@Hossain Ahamed 2017-03-17 06:00:44

You can not call network on the main thread or UI thread. On Android if you want to call network there are two options -

  1. Call asynctask, which will run one background thread to handle the network operation.
  2. You can create your own runnable thread to handle the network operation.

Personally I prefer asynctask. For further information you can refer this link.

@aks 2017-03-02 16:16:14

As Android is working on a single thread, you should not do any network operation on the main thread. There are various ways to avoid this.

Use the following way to perform a network operation

  • Asysnctask: For small operations which don't take much time.
  • Intent Service: For network operation which take a big amount of time.
  • Use a custom library like Volley and Retrofit for handling complex network operations

Never use StrictMode.setThreadPolicy(policy), as it will freeze your UI and is not at all a good idea.

@Stevie 2014-01-22 13:17:32

The accepted answer has some significant down-sides. It is not advisable to use AsyncTask for networking unless you really know what you are doing. Some of the down-sides include:

  • AsyncTask's created as non-static inner classes have an implicit reference to the enclosing Activity object, its context, and the entire View hierarchy created by that activity. This reference prevents the Activity from being garbage collected until the AsyncTask's background work completes. If the user's connection is slow, and/or the download is large, these short-term memory leaks can become a problem - for example if the orientation changes several times (and you don't cancel the executing tasks), or the user navigates away from the Activity.
  • AsyncTask has different execution characteristics depending on the platform it executes on: prior to API level 4 AsyncTasks execute serially on a single background thread; from API level 4 through API level 10, AsyncTasks execute on a pool of up to 128 threads; from API level 11 onwards AsyncTask executes serially on a single background thread (unless you use the overloaded executeOnExecutor method and supply an alternative executor). Code that works fine when run serially on ICS may break when executed concurrently on Gingerbread, say, if you have inadvertent order-of-execution dependencies.

If you want to avoid short-term memory leaks, have well defined execution characteristics across all platforms, and have a base to build really robust network handling, you might want to consider:

  1. Using a library that does a nice job of this for you - there's a nice comparison of networking libs in this question, or
  2. Using a Service or IntentService instead, perhaps with a PendingIntent to return the result via the Activity's onActivityResult method.

IntentService approach

Down-sides:

  • More code and complexity than AsyncTask, though not as much as you might think
  • Will queue requests and run them on a single background thread. You can easily control this by replacing IntentService with an equivalent Service implementation, perhaps like this one.
  • Um, I can't think of any others right now actually

Up-sides:

  • Avoids the short-term memory leak problem
  • If your activity restarts while network operations are in-flight it can still receive the result of the download via its onActivityResult method
  • Better platform than AsyncTask to build and re-use robust networking code. Example: if you need to do an important upload, you could do it from AsyncTask in an Activity, but if the user context-switches out of the app to take a phone-call, the system may kill the app before the upload completes. It is less likely to kill an application with an active Service.
  • If you use your own concurrent version of IntentService (like the one I linked above) you can control the level of concurrency via the Executor.

Implementation summary

You can implement an IntentService to perform downloads on a single background thread quite easily.

Step 1: Create an IntentService to perform the download. You can tell it what to download via Intent extra's, and pass it a PendingIntent to use to return the result to the Activity:

import android.app.IntentService;
import android.app.PendingIntent;
import android.content.Intent;
import android.util.Log;

import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

public class DownloadIntentService extends IntentService {

    private static final String TAG = DownloadIntentService.class.getSimpleName();

    public static final String PENDING_RESULT_EXTRA = "pending_result";
    public static final String URL_EXTRA = "url";
    public static final String RSS_RESULT_EXTRA = "url";

    public static final int RESULT_CODE = 0;
    public static final int INVALID_URL_CODE = 1;
    public static final int ERROR_CODE = 2;

    private IllustrativeRSSParser parser;

    public DownloadIntentService() {
        super(TAG);

        // make one and re-use, in the case where more than one intent is queued
        parser = new IllustrativeRSSParser();
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        PendingIntent reply = intent.getParcelableExtra(PENDING_RESULT_EXTRA);
        InputStream in = null;
        try {
            try {
                URL url = new URL(intent.getStringExtra(URL_EXTRA));
                IllustrativeRSS rss = parser.parse(in = url.openStream());

                Intent result = new Intent();
                result.putExtra(RSS_RESULT_EXTRA, rss);

                reply.send(this, RESULT_CODE, result);
            } catch (MalformedURLException exc) {
                reply.send(INVALID_URL_CODE);
            } catch (Exception exc) {
                // could do better by treating the different sax/xml exceptions individually
                reply.send(ERROR_CODE);
            }
        } catch (PendingIntent.CanceledException exc) {
            Log.i(TAG, "reply cancelled", exc);
        }
    }
}

Step 2: Register the service in the manifest:

<service
        android:name=".DownloadIntentService"
        android:exported="false"/>

Step 3: Invoke the service from the Activity, passing a PendingResult object which the Service will use to return the result:

PendingIntent pendingResult = createPendingResult(
    RSS_DOWNLOAD_REQUEST_CODE, new Intent(), 0);
Intent intent = new Intent(getApplicationContext(), DownloadIntentService.class);
intent.putExtra(DownloadIntentService.URL_EXTRA, URL);
intent.putExtra(DownloadIntentService.PENDING_RESULT_EXTRA, pendingResult);
startService(intent);

Step 4: Handle the result in onActivityResult:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == RSS_DOWNLOAD_REQUEST_CODE) {
        switch (resultCode) {
            case DownloadIntentService.INVALID_URL_CODE:
                handleInvalidURL();
                break;
            case DownloadIntentService.ERROR_CODE:
                handleError(data);
                break;
            case DownloadIntentService.RESULT_CODE:
                handleRSS(data);
                break;
        }
        handleRSS(data);
    }
    super.onActivityResult(requestCode, resultCode, data);
}

A github project containing a complete working Android-Studio/gradle project is available here.

@Brill Pappin 2016-09-10 14:59:39

IntentService is the correct way to do this, not uprooting because AsyncTask is exactly the way not to do it.

@Stevie 2017-03-13 12:56:14

@BrillPappin I almost entirely agree and have re-worded to emphasize the drawbacks of AsyncTask. (I still think there are a very small number of cases where - if you really know what you are doing - it might be OK to use AsyncTask, but the accepted answer doesn't point out any drawbacks and is way too popular for the good of Android).

@Cullub 2018-04-14 19:13:12

Do you actually need IllustrativeRSS? What if you're not working with RSS stuff?

@Daniel Arechiga 2019-02-01 16:00:43

I think this is the best answer, it does not focus only on getting rid of the exception but actually considers optimal conditions.

@Lovekush Vishwakarma 2016-10-04 08:00:51

How to fix android.os.NetworkOnMainThreadException

What is NetworkOnMainThreadException:

In Android all the UI operations we have to do on the UI thread (main thread). If we perform background operations or some network operation on the main thread then we risk this exception will occur and the app will not respond.

How to fix it:

To avoid this problem, you have to use another thread for background operations or network operations, like using asyncTask and use some library for network operations like Volley, AsyncHttp, etc.

@Dr.Luiji 2013-01-21 16:31:35

I solved this problem using a new Thread.

Thread thread = new Thread(new Runnable() {

    @Override
    public void run() {
        try  {
            //Your code goes here
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
});

thread.start(); 

@Alex Lockwood 2013-01-27 18:06:36

Instead of creating a new thread each time you want to perform a network operation, you could use a single thread executor service too.

@Stevie 2014-06-19 12:39:39

Simple but dangerous. The anonymous Runnable has an implicit reference to the enclosing class (e.g. your Activity or Fragment), preventing it from being garbage collected until the thread completes. You should at least set the priority to Process.BACKGROUND, else this thread will run at the same priority as the main/ui thread, contending with lifecycle methods and ui frame rates (watch out for warnings in log from the choreographer).

@J. K. 2015-05-31 13:26:02

@Stevie how to set the priority? neither runnble nor the executorService have such a setter method

@Stevie 2015-06-01 19:14:03

@J.K. Supply your ExecutorService with a custom ThreadFactory and call Thread.setPriority on the thread before returning it.

@john16384 2016-01-27 13:09:20

Setting priority for something that is intended to do a network call (which will block) seems overkill.

@Stevie 2016-02-01 16:36:25

@john16384 I'd argue it is overkill to do networking (or any other background work) on a thread at the same priority as main when its a one liner to lower the priority :) Besides, most times you'll want to do something with the response like parsing json / xml / whatever.

@bhavesh kaila 2016-04-07 11:27:54

This is a good idea but we didn't get thread finish callback over here

@henry4343 2013-12-24 14:33:08

Do the network actions on another thread

For Example:

new Thread(new Runnable(){
    @Override
    public void run() {
        // Do network action in this function
    }
}).start();

And add this to AndroidManifest.xml

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

@Piyush Soni 2014-01-04 23:30:41

But how can we find out when the thread finishes in this so that we can carry out the next set of tasks in the UI thread? The AsyncTask provides the facility to do that. Is there a way to do the same using runnable threads?

@henry4343 2014-01-05 02:18:05

It will process your code step by step, so in the end of the code is finish, you need to use handler back to UI thread

@henry4343 2014-01-06 00:50:28

@Chetan Chaudhari 2017-04-19 20:05:38

You can use async task or intent service, because it's execute on worker thread.

@Alex Shutov 2016-06-23 22:00:02

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.

@Prakhar1001 2016-09-15 14:10:50

quite an extensive approach it would to be schedule by our own and i don't know why we should if it is already being an option on Android side?

@BalaramNayak 2016-01-19 09:52:56

The NetworkOnMainThread exception occurs because you have called some network operation on the default thread, that is, the UI thread. As per Android version Android 3 (Honeycomb) which is not allowed, you should call network operation outside the main thread.

You can use AsyncTask, IntentService, or creating your own thread and calling inside the run method. For more information, visit Connecting to the Network.

@Adnan Abdollah Zaki 2016-01-15 16:47:54

This exception is thrown when an application attempts to perform a networking operation on its main thread. If your task took above five seconds, it takes a force close.

Run your code in AsyncTask:

class RetrieveFeedTask extends AsyncTask<String, Void, Boolean> {

    protected RSSFeed doInBackground(String... urls) {
       // TODO: Connect
    }

    protected void onPostExecute(RSSFeed feed) {
        // TODO: Check this.exception
        // TODO: Do something with the feed
    }
}

@Krishna 2015-12-18 09:23:21

You are not allowed to implement network operations on the UI thread on Android. You will have to use AsyncTask class to perform network related operations like sending API request, downloading image from a URL, etc. and using callback methods of AsyncTask, you can get you result in onPostExecute menthod and you will be in the UI thread and you can populate UI with data from web service or something like that.

Example: Suppose you want to download image from an URL: https://www.samplewebsite.com/sampleimage.jpg

Solution using AsyncTask: are respectively.

    public class MyDownloader extends AsyncTask<String,Void,Bitmap>
    {
        @Override
        protected void onPreExecute() {
            // Show progress dialog
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            //Populate Ui
            super.onPostExecute(bitmap);
        }

        @Override
        protected Bitmap doInBackground(String... params) {
            // Open URL connection read bitmaps and return form here
            return result;
        }

        @Override
        protected void onProgressUpdate(Void... values) {
            // Show progress update
            super.onProgressUpdate(values);
        }


    }
}

Note: Do not forget to add the Internet permission in the Android manifest file. It will work like a charm. :)

@RevanthKrishnaKumar V. 2015-08-13 08:26:14

Accessing network resources from the main (UI) thread cause this exception. Use a separate thread or AsyncTask for accessing a network resource to avoid this problem.

@Nabin 2015-07-22 02:05:44

In simple words,

DO NOT DO NETWORK WORK IN THE UI THREAD

For example, if you do an HTTP request, that is a network action.

Solution:

  1. You have to create a new Thread
  2. Or use AsyncTask class

Way:

Put all your works inside

  1. run() method of new thread
  2. Or doInBackground() method of AsyncTask class.

But:

When you get something from Network response and want to show it on your view (like display response message in TextView), you need to return back to the UI thread.

If you don't do it, you will get ViewRootImpl$CalledFromWrongThreadException.

How to?

  1. While using AsyncTask, update view from onPostExecute() method
  2. Or call runOnUiThread() method and update view inside the run() method.

@Ponsuyambu Velladurai 2015-06-25 07:42:59

On Android, network operations cannot be run on the main thread. You can use Thread, AsyncTask (short-running tasks), Service (long-running tasks) to do network operations.

Related Questions

Sponsored Content

60 Answered Questions

[SOLVED] How do I read / convert an InputStream into a String in Java?

64 Answered Questions

[SOLVED] How do I generate random integers within a specific range in Java?

  • 2008-12-12 18:20:57
  • user42155
  • 3787996 View
  • 3205 Score
  • 64 Answer
  • Tags:   java random integer

45 Answered Questions

[SOLVED] How do I convert a String to an int in Java?

38 Answered Questions

[SOLVED] How do I efficiently iterate over each entry in a Java Map?

42 Answered Questions

47 Answered Questions

40 Answered Questions

[SOLVED] Can't start Eclipse - Java was started but returned exit code=13

12 Answered Questions

77 Answered Questions

3 Answered Questions

Sponsored Content