N
N
Nikolay Baranenko2018-04-06 01:35:38
Android
Nikolay Baranenko, 2018-04-06 01:35:38

How to resolve android.os.NetworkOnMainThreadException error?

Hello.
Added a button in the application, by pressing which an HTTP request to the WEB service should go through

package com.example.drno.android_app_1;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.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 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 Sensor senGyroscope;

    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);
//        }


//        нажатие выход из приложения
        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);


//        нажатие старт измерений
        button =(Button) findViewById(R.id.button_start);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//              new MainActivity();
              onResume();

            }
        });
//        нажатие стоп измерений
        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("Текст должен быть изменен");
        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("\nSending 'GET' request to URL : " + url);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(
                new 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() {
        ArrayList numbersGenerated = 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("\nSending 'GET' request to URL : " + URL);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(
                new 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(SensorEvent sensorEvent) {
        Sensor mySensor = 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 resolve it?
ps
in AndroidManifest.xml registered permissions
<uses-permission android:name="android.permission.INTERNET"/>
<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>

            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>
</application>

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 original project

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2018-04-06
@drno-reg

Well, he writes in black and white. You can not go to the network on the main thread. Should be moved to a separate thread. If you turn off Strictmod, you will go to hell for negligent students.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question