How to resolve android bug.os.NetworkOnMainThreadException?

0 like 0 dislike
5 views
Hello.

The app has added a button which should pass the HTTP request to the WEB service

package com.example.drno.android_app_1; import android.content.Context; import android.hardware.Sensor; import android.hardware.In the sensorevent; import android.hardware.By implementing the sensoreventlistener; import android.hardware.SensorManager; import android.os.Build; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import java.io.*; import java.lang.Math; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Random; import static android.util.Half.EPSILON; import static java.lang.Math.sin; import static java.lang.Math.cos; import static java.lang.Math.sqrt; import android.os.StrictMode; public class MainActivity extends AppCompatActivity implements by implementing the sensoreventlistener { private TextView textView; private Button button; private TextView textView_HTTP; private Sensor mTemperature; private final static String NOT_SUPPORTED_MESSAGE = "Sorry, sensor not available for this device."; private TextView accelerometerlabel; // private Sensor senAccelerometer; private long lastUpdate = 0; private float last_x, last_y, last_z; private static final int SHAKE_THRESHOLD = 600; private TextView gyroscopelabel; private senGyroscope Sensor; private SensorManager mSensorManager; private Sensor mLight; private Sensor mAccelerometer; private String Send_http; private final String USER_AGENT = "Mozilla/5.0"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R. layout.activity_main); // if (android.os.Build.VERSION.SDK_INT > 9) { // StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); // StrictMode.setThreadPolicy(policy); // } // use to exit the application button =(Button) findViewById(R. id.button_exit); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub finish(); System.exit(0); } }); textView=(TextView) findViewById(R. id.textView_HTTP); // press start measurement button =(Button) findViewById(R. id.button_start); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // new MainActivity(); onResume(); } }); // clicking the stop measurement button =(Button) findViewById(R. id.button_stop); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onPause(); } }); accelerometerlabel = (TextView) findViewById(R. id.textView_Accelerometer); mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); gyroscopelabel = (TextView) findViewById(R. id.textView_Gyroscope); senGyroscope = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE); } public void sayHello(View View) throws IOException { textView_HTTP.setText("Text should be changed"); TextView textv = (TextView)findViewById(R. id.textView_HTTP); String url="http://31.220.63.13:5005/accelerometer"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // optional default is GET con.setRequestMethod("GET"); //add request header con.setRequestProperty("User-Agent", USER_AGENT); int responseCode = con.getResponseCode(); System.out.println("\Sending 'GET' request to URL : "+ url); System.out.println("Response Code :" + responseCode); BufferedReader in = new BufferedReader( new the InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); System.out.println(response.toString()); textView_HTTP.setText(response.toString()); } private void getRandomNumber() { NumbersGenerated ArrayList = new ArrayList(); for (int i = 0; i < 6; i++) { Random randNumber = new Random(); int iNumber = randNumber.nextInt(48) + 1; if(!numbersGenerated.contains(iNumber)) { numbersGenerated.add(iNumber); } else { i--; } } } // HTTP GET request private String sendGet(String URL) throws Exception { URL obj = new URL(URL); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // optional default is GET con.setRequestMethod("GET"); //add request header con.setRequestProperty("User-Agent", USER_AGENT); int responseCode = con.getResponseCode(); System.out.println("\Sending 'GET' request to URL : "+ URL); System.out.println("Response Code :" + responseCode); BufferedReader in = new BufferedReader( new the InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); //print result // System.out.println(response.toString()); return(response.toString()); } @Override public void onSensorChanged(in the sensorevent in the sensorevent) { Sensor mySensor = in the sensorevent.sensor; } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } @Override protected void onResume() { } @Override protected void onPause() { } }


an error is returned

android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:384) at android.view.View.performClick(View.java:6294) at android.view.View$PerformClick.run(View.java:24770) at android.os.Handler.handleCallback(Handler.java:790) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6494) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807) Caused by: android.os.NetworkOnMainThreadException at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1450)

Why and how to solve it?

p.s.

in AndroidManifest.xml prescribed permissions


tried to add

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


link to ishodnyh project
by | 5 views

1 Answer

0 like 0 dislike
Well in black and white writes. You cannot go to the network on the main thread. It is necessary to make a separate thread. Strictmode disconnect - go to hell for negligent students.
by

Related questions

0 like 0 dislike
1 answer
0 like 0 dislike
1 answer
0 like 0 dislike
1 answer
asked May 12, 2019 by dmitriyprog
0 like 0 dislike
1 answer
asked May 10, 2019 by Drew20
110,608 questions
257,186 answers
0 comments
28,741 users