- How to Fix “android.os.Network On Main Thread Exception error” in Android Studio?
- Solutions
- Solution 1
- Solution 2
- Solution 3
- Solution 4
- android os network on main thread exception
- 4 Answers 4
- Retrofit — android.os.NetworkOnMainThreadException
- How to fix NetworkonMainThreadException in Android? [duplicate]
- 3 Answers 3
- Network OnMain Thread Exception Class
- Definition
- Remarks
- Constructors
- Fields
- Properties
- Methods
- Explicit Interface Implementations
- Extension Methods
How to Fix “android.os.Network On Main Thread Exception error” in Android Studio?
The main reason for Network On Main Thread Exception Error is because the newer versions of android are very strict against the UI thread abuse. Whenever we open an app, a new “main” thread is created which helps applications interact with the running components of an app’s UI and is responsible for dispatching events to assigned widgets. The entire User Interface is blocked when time-consuming actions are performed on the UI thread.
When an app attempts to perform networking operations on the main thread a Network On Main Thread Exception Error is thrown. The error shows on all applications targeting Honeycomb SDK or higher. Applications get disabled to download files, connect to remote MySQL database, perform HTTP requests or establish a socket connection.
Solutions
The solution is to completely wrap any task that attempts to perform actions like download files, connect to remote MySQL database, perform HTTP requests or establish a socket connection into a separate async function. A new thread is created by the async function, and hence, these processes do not run on the UI thread. We can also override the instruction, but in this situation, the task manager may have to kill the application and it will make the application unresponsive.
Solution 1
To overcome this situation, add the following to the class where the user is performing network operations:
Add the following permissions to the manifest.xml file:
Solution 2
To solve this problem we will use a new Thread
Example:
Solution 3
- Do not use strictMode (only in debug mode)
- Do not change the SDK version
- Do not use a separate thread
Solution 4
When an app attempts to perform networking operations on the main thread a Network On Main Thread Exception Error is thrown.
Источник
android os network on main thread exception
i make this code in single application working, but if join with other application , show this dialog «android os network on main thread exception»
in permission i active that and still not working
4 Answers 4
You need to run internet activities on a thread separate from main (UI) thread, you can do that by wrapping your code in the following block:
Execute your Network related operation in AsyncTask
You can also refer here Android AsyncTask
you can create an AsynTask .. Your code should run in background in order to be responsive.. otherwise it will show Not Responding ..
You can create a seperate thread for it .. using multitasking.
Right the code in the onCreate after setContentView
While all of the answers posted in this thread is correct, asynctasks are not really considering to be a good tool to user for network transactions anymore. The main reasons for this is that the asynctasks are very closely tied to activities so alot issues arise like. «what happens if the activity is destroyed before the network call returns?».
If you really want to implement android best practices (and not to mention impress your fellow Android devs) then why not perform a network task in a service?
I would suggest looking at the Path FOSS project android-prioriy-queue. They make it ridiculously easy to perform task in a service.
Источник
Retrofit — android.os.NetworkOnMainThreadException
I am using Retrofit 2 to get json and parse it to POJO. My purpose is getting one value of that object.
Here I found great great tool to create service:
Then I am creating new service using Service generator class:
When I am trying to run this code I am getting this error:
android.os.NetworkOnMainThreadException at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147) at java.net.InetAddress.lookupHostByName(InetAddress.java:418) at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252) at java.net.InetAddress.getAllByName(InetAddress.java:215) at okhttp3.Dns$1.lookup(Dns.java:39) at okhttp3.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:173) at okhttp3.internal.http.RouteSelector.nextProxy(RouteSelector.java:139) at okhttp3.internal.http.RouteSelector.next(RouteSelector.java:81) at okhttp3.internal.http.StreamAllocation.findConnection(StreamAllocation.java:174) at okhttp3.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:127) at okhttp3.internal.http.StreamAllocation.newStream(StreamAllocation.java:97) at okhttp3.internal.http.HttpEngine.connect(HttpEngine.java:289) at okhttp3.internal.http.HttpEngine.sendRequest(HttpEngine.java:241) at okhttp3.RealCall.getResponse(RealCall.java:240) at okhttp3.RealCall$ApplicationInterceptorChain.proceed(RealCall.java:198) at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:160) at okhttp3.RealCall.execute(RealCall.java:57) at retrofit2.OkHttpCall.execute(OkHttpCall.java:177) at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall.execute(ExecutorCallAdapterFactory.java:87) at uz.cp.ox.data.MyRepository.getMyItem(MyRepository.java:31) at uz.cp.ox.presenters.MyPresenter.do(MyPresenter.java:30) at uz.cp.ox.activities.MyActivity.onClick(MyActivity.java:52) at android.view.View.performClick(View.java:4756) at android.view.View$PerformClick.run(View.java:19749) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5221) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
I thought that Retrofit automatically does the job in the background thread. Or I misunderstood something. What is wrong in this situation and how to solve it?
Источник
How to fix NetworkonMainThreadException in Android? [duplicate]
I’m creating an project for assignment, I’m new to Android, and I wanted to access json from very common url http://api.androidhive.info/contacts/ ,
Problem: I’m trying to read the url and fetch and parse the json returned by this url,
I’ve already added following line into my AndroidManifest.xml
Preferences: and my android preferences are
and this is how I’m trying to read the url
The Error Message
3 Answers 3
Your Exception actually tells you exactly what you are doing wrong. You are not using another thread to perform NetworkOperations. Instead, you perform the network operation on your UI-Thread, which cannot (does not) work on Android.
Your code that connects to the url should be executed for example inside an AsyncTasks doInBackground() method, off the UI-Thread.
Take a look at this question on how to use the AsyncTask: How to use AsyncTask
Updated Answer:
Potentially long running operations such as network operations should be done in a worker thread.
The most effective way to create a worker thread for longer operations is with the AsyncTask class. Simply extend AsyncTask and implement the doInBackground() method to perform the work.
Many libraries are available to do network operations such as Volley, retrofit etc.
Old Answer:
Add following lines in your activity onCreate method
Источник
Network OnMain Thread Exception Class
Definition
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
The exception that is thrown when an application attempts to perform a networking operation on its main thread.
Remarks
Portions of this page are modifications based on work created andВ shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.
Constructors
A constructor used when creating managed representations of JNI objects; called by the runtime.
Fields
Properties
Returns the cause of this throwable or null if the cause is nonexistent or unknown.
(Inherited from Throwable)
The handle to the underlying Android instance.
(Inherited from Throwable)
Creates a localized description of this throwable.
(Inherited from Throwable)
Returns the detail message string of this throwable.
(Inherited from Throwable)
This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.
This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.
Methods
Appends the specified exception to the exceptions that were suppressed in order to deliver this exception.
(Inherited from Throwable)
Fills in the execution stack trace.
(Inherited from Throwable)
Provides programmatic access to the stack trace information printed by #printStackTrace() .
(Inherited from Throwable)
Returns an array containing all of the exceptions that were suppressed, typically by the try -with-resources statement, in order to deliver this exception.
(Inherited from Throwable)
Initializes the cause of this throwable to the specified value.
(Inherited from Throwable)
Prints this throwable and its backtrace to the standard error stream.
(Inherited from Throwable)
Prints this throwable and its backtrace to the standard error stream.
(Inherited from Throwable)
Prints this throwable and its backtrace to the standard error stream.
(Inherited from Throwable)
Sets the Handle property.
(Inherited from Throwable)
Sets the stack trace elements that will be returned by #getStackTrace() and printed by #printStackTrace() and related methods.
(Inherited from Throwable)
Explicit Interface Implementations
IJavaPeerable.Disposed() | (Inherited from Throwable) |
IJavaPeerable.DisposeUnlessReferenced() | (Inherited from Throwable) |
IJavaPeerable.Finalized() | (Inherited from Throwable) |
IJavaPeerable.JniManagedPeerState | (Inherited from Throwable) |
IJavaPeerable.SetJniIdentityHashCode(Int32) | (Inherited from Throwable) |
IJavaPeerable.SetJniManagedPeerState(JniManagedPeerStates) | (Inherited from Throwable) |
IJavaPeerable.SetPeerReference(JniObjectReference) | (Inherited from Throwable) |
Extension Methods
Performs an Android runtime-checked type conversion.
Источник