Development issue/problem:

I have this exception, and I read a thread about it, and it seemed confusing:

How can I repair android.os.NetworkOnMainThreadException?

I’ve already added this line to my manifesto:

In this discussion they explain how the thread of an application cannot perform network functions. I’m interested in how I can rebuild my code to meet Android best practices.

Here’s my activity lesson over:

com.problemio package ;

Import java.io.InputStream;
Import java.util.ArrayList ;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair ;

import android.app.Activity;
import android.content.intentional;
import android.os.bundle;
import android.util.log;
import android.view.view;
import android.widget.button;
import android.widget.editText;
public class LoginActivity expands activity
{
public null and void onCreate(Bundle storedInstanceState)
{
super.onCreate(storedInstanceState);
setContentView(R.layout.login;)

// Show the form for login_email
final EditText loginEmail = (EditText) findViewById(R.id.login_email) ;
String name = loginEmail.getText().toString() ;

// Display password field
final EditText password = (EditText) findViewById(R.id.password);
String text = password.getText().toString() ;

// Show send button
Send button = (button)findViewById(R.id.submit) ;

// Show options to create the profile and forget the password

submit.setOnClickListener(new button.OnClickListener()
{
public null and void onClick(View v)
{
String email = loginEmail.getText().toString();
String pass = password.getText().toString();
sendFeedback(pass, email);
}
});
}).

public invalid sendFeedback(String pass , String email)
{
Log.d( 1 , pass ) ;
Log.d( 1 , email ) ;

// Go to db and check if these r
are legal // How? 🙂
ArrayList postParameters = new ArrayList() ;
postParameters.add(new BasicNameValuePair(username, e-mail)) ;
postParameters.add(new BasicNameValuePair(password, e-mail))

String responseString = null ;

try
{
HttpClient httpclient = new DefaultHttpClient() ;
HttpPost httppost = new HttpPost(myUrl) ;

// no idea what he’s doing 🙂
httppost.setEntity(new UrlEncodedFormEntity(postParameters)) ;

// This is the string that sends the
HttpResponse response = httpclient.execute(httppost);

HttpEntity = response.getEntity() ;

InputStream is = entity.getContent();}catch (Exception e){Log.e(log_tag, Error in http connection +e.toString());}}}}

What am I doing wrong here and what can I do about it? Thank you so much!

How can I solve this problem?

Solution 1:

NetworkOnMainThreadException : Exception thrown when an application tries to perform a network operation on the main wire.

You have to call the return method on the asynctask, then only the above code works. Since the web server takes a long time, the main response flow becomes insensitive. To prevent this from happening, you have to put it in a different jacket. That’s why asynktasca is better.

Here is a link that illustrates the use of asynct bag

Solution 2:

NetworkOnMainThreadException is started when your application tries to connect to the main thread.

To fix this, you can use a closed internal class in Activity that android.os.AsyncTask<Params, Progress, Result> that makes server calls to things.

Something like that,

The SendfeedbackJob private lesson expands AsyncTask {

@General
protected string doInBackground(String[] params) {
// execute above server call from
return each message;
}

@ProtectedVacancy
protectedVacancy onPostExcute(String message) {
//process message
}
}

Then call the above login class, setOnClickListener, as shown below,

SendfeedbackJob job = new SendfeedbackJob() ;
job.execute(pass, e-mail) ;

Android &#8211; android.os.NetworkOnMainThreadException &#8211;

References

AsyncTask document

Example of AsyncTask for Android

Solution 3:

if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().allowAll().build();
StrictMode.setThreadPolicy(policy);
}

Solution 4:

try
{
HttpClient httpclient = new DefaultHttpClient() ;
HttpPost httppost = new HttpPost(myUrl) ;

// no idea what he’s doing 🙂
httppost.setEntity(new UrlEncodedFormEntity(postParameters)) ;

// This is the string that sends the
HttpResponse response = httpclient.execute(httppost);

HttpEntity = response.getEntity() ;

InputStream is = entity.getContent();
}
catch (Exception e)
{
Log.e(log_tag, Error in http connection +e.toString());
}

Here’s your problem. Starting with api 11, this exception informs you that you perform long tasks in the onion thread (http communication in your classroom), which is not possible under the new StrictGuard policy. So you have two different options.

  1. Use flow or syntax to accomplish a long-term task (the best way).

Solution No 5:

You made a network call on the main wire, which is against Android rules. Therefore, you need to make a network call on a separate wire as an asynktak or handler, etc.

Solution No 6:

You can simply create an asynchronous class as described below.

The Retrievedata class expands AsyncTask {
@Override
protected String doInBackground(String… params) {
try{
//your code
}
return zero ;
}
}.

You can simply paste all your code into the doInBackground method.

Solution No 7:

Consult this link: https://developer.android.com/reference/android/os/NetworkOnMainThreadException.html

Exception thrown when an application tries to perform a network operation on the main wire.
Applications aimed at earlier versions of the SDK may be connected to the wires of the event’s main loop, but this is not desirable at all.

If you set minSdkVersion <11, your application will run and you can perform network operations in the main thread.

Solution No 8:

After a lot of research (half a day) I have found a solution to my problem that is similar to the one mentioned here. The exception that appeared in my Android Studio 2.3.3 was the following:

android.os.network on an exception

The problem was based on the inability to define the variable UI in MainActivity. So I watched the next video and solved my problem. I hope it will be useful for others too:

How to avoid the NetworkOnMainThreadException android

Good luck!

You May Also Like

Why Does My Car Stereo Cut Out at High Volume?

This is one of the most common questions we get from do-it-yourself…

Something happened and your PIN isn’t available [SOLVED]

Another pin problem you may encounter is the pin of Windows Hello,…

How to Enable and Configure User Disk Quotas in Windows?

Disk quotas allow Windows administrators to control and limit the space users…

Offseting the center of the MapFragment for an animation moving both the target lat/lng and the zoom level –

Development issue/problem: I have a user interface where a MapFragment is placed…