Как починить android.os.NetworkOnMainThreadException

blits

Здравствуйте. Пытаюсь сделать POST запрос на ajax страницу с помощью HttpURLConnection. Сильно не пинайте, я только сегодня начал практиковать Java и Android. Тестю на API 22 (Intel x86). В обычном хроме та же страница нормально загружается. Logcat:

03-24 10:23:26.842 4679-4679/? I/art: Late-enabling -Xcheck:jni
03-24 10:23:27.402 4679-4679/com.gobonus.gobonus D/AndroidRuntime: Shutting down VM
03-24 10:23:27.427 4679-4679/com.gobonus.gobonus E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.gobonus.gobonus, PID: 4679    
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gobonus.gobonus/com.gobonus.gobonus.WelcomeActivity}: android.os.NetworkOnMainThreadException

    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2358)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2420)
    at android.app.ActivityThread.access$900(ActivityThread.java:154)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5294)
    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:904)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
Caused by: android.os.NetworkOnMainThreadException
    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
    at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:110)
    at libcore.io.IoBridge.connectErrno(IoBridge.java:137)
    at libcore.io.IoBridge.connect(IoBridge.java:122)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:456)
    at java.net.Socket.connect(Socket.java:882)
    at com.android.okhttp.internal.Platform.connectSocket(Platform.java:174)
    at com.android.okhttp.Connection.connect(Connection.java:152)
    at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:276)
    at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
    at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:382)
    at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:106)
    at com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:217)
    at com.gobonus.gobonus.Request.<init>(Request.java:65)
    at com.gobonus.gobonus.WelcomeActivity.onCreate(WelcomeActivity.java:15)
    at android.app.Activity.performCreate(Activity.java:5990)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2311)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2420) 
    at android.app.ActivityThread.access$900(ActivityThread.java:154) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321) 
    at android.os.Handler.dispatchMessage(Handler.java:102) 
    at android.os.Looper.loop(Looper.java:135) 
    at android.app.ActivityThread.main(ActivityThread.java:5294) 
    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:904) 
    at 
</init>

com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)  03-24 10:23:27.498 4679-4690/com.gobonus.gobonus W/art: Suspending all threads took: 26.757ms Request.java:

package com.gobonus.gobonus;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;


public class Request {

    private final String USER_AGENT = "GoBonus Android Client 1.0";
    private final String API_SERVER = "http://192.168.2.21";

    public String Content;


    public Request (String session_token, String uri, String params) {

        String urlParameters  = "session_token="+session_token+"&"+params; // url params
        byte[] postData       = new byte[0];

        System.setProperty("http.agent", USER_AGENT); // user agent truck

        // api = android.os.Build.VERSION_CODES.KITKAT) {
            postData = urlParameters.getBytes( StandardCharsets.UTF_8 );
        }
        else
            postData = urlParameters.getBytes(Charset.forName("UTF-8"));

        int    postDataLength = postData.length;
        URL    url            = null;

        try {
            url = new URL( API_SERVER + uri);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        HttpURLConnection conn= null;
        try {
            conn = (HttpURLConnection) url.openConnection();
        } catch (IOException e) {
            e.printStackTrace();
        }
        conn.setDoOutput( true );
        conn.setInstanceFollowRedirects( false );
        try {
            conn.setRequestMethod("POST");
        } catch (ProtocolException e) {
            e.printStackTrace();
        }
        conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty( "charset", "utf-8");
        conn.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));

        conn.setUseCaches( false );
        try {
            DataOutputStream wr = new DataOutputStream( conn.getOutputStream());
            wr.write( postData );
            conn.connect();
            Content = ConvertData(conn);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    protected String ConvertData (HttpURLConnection url) throws IOException {
        // local variables
        String line;
        StringBuffer text = new StringBuffer();

        InputStreamReader in = new InputStreamReader((InputStream) url.getContent());
        BufferedReader buff = new BufferedReader(in);
        do {
            line = buff.readLine();
            text.append(line + "\n");
        } while (line != null);
        return text.toString();
    }

}

WelcomeActivity.java

package com.gobonus.gobonus;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class WelcomeActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TextView WebTest = (TextView) findViewById(R.id.webTest);
        WebTest.setText(new Request("123", "/ajax", "foo=bar").Content);
        setContentView(R.layout.activity_welcome);
    }

    public void LoginGo(View view) {
        Intent intent = new Intent(WelcomeActivity.this, LoginActivity.class);
        startActivity(intent);
    }
}

Манифест

<!--?xml version="1.0" encoding="utf-8"?-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.gobonus.gobonus">

    <!-- To auto-complete the email text field in the login form with the user's emails -->
    <uses-permission android:name="android.permission.GET_ACCOUNTS">
    <uses-permission android:name="android.permission.READ_PROFILE">
    <uses-permission android:name="android.permission.READ_CONTACTS">
    <uses-permission android:name="android.permission.INTERNET">

    <application android:allowbackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsrtl="true" android:theme="@style/GB">
        <activity android:name=".WelcomeActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN">

                <category android:name="android.intent.category.LAUNCHER">
            </category></action></intent-filter>
        </activity>
        <activity android:name=".LoginActivity" android:label="@string/title_activity_login" android:parentactivityname=".WelcomeActivity">
            <meta-data android:name="android.support.PARENT_ACTIVITY" android:value="com.gobonus.gobonus.WelcomeActivity">
        </meta-data></activity>
    </application>

</uses-permission></uses-permission></uses-permission></uses-permission></manifest>

Layout

<!--?xml version="1.0" encoding="utf-8"?-->
    <relativelayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingbottom="@dimen/activity_vertical_margin" android:paddingleft="@dimen/activity_horizontal_margin" android:paddingright="@dimen/activity_horizontal_margin" android:paddingtop="@dimen/activity_vertical_margin" tools:context="com.gobonus.gobonus.WelcomeActivity">

        <button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/sign" android:id="@+id/button" android:background="#B6B6B6" android:layout_marginbottom="162dp" android:onclick="LoginGo" android:layout_alignparentbottom="true" android:layout_alignright="@+id/button2" android:layout_alignend="@+id/button2" android:layout_alignparentleft="true" android:layout_alignparentstart="true">

        </button><button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/reg" android:id="@+id/button2" android:background="#B6B6B6" android:layout_aligntop="@+id/button" android:layout_alignparentleft="true" android:layout_alignparentstart="true" android:layout_margintop="82dp" android:layout_alignparentright="true" android:layout_alignparentend="true">

        <textview android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="New Text" android:id="@+id/webTest" android:layout_alignparenttop="true" android:layout_centerhorizontal="true" android:layout_margintop="56dp">
    
</textview></button></relativelayout>
1 ответ

blits

Эксепшн NetworkOnMainThreadException говорит о том, что вы используете сетевые запросы в главном потоке, используйте AsyncTask для запуска запроса в отдельном от UI потока.

И Метод setContentView, нужно вызывать до того, как будете обращаться к элементам разметки.

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);
        TextView WebTest = (TextView) findViewById(R.id.webTest);
        WebTest.setText(new Request("123", "/ajax", "foo=bar").Content);

    }

UPD

Пример запроса через AsyncTask. Метод doInBackground выполняется в отдельном от UI потоке, после того, как вы выполнили запрос и получили ответ, ваши данные упадут в onPostExecute, который выполняется уже в потоке UI. Не обращайтесь к потоку UI в doInBackground, вызовет Exception.

public class WelcomeActivity extends AppCompatActivity {

    TextView WebTest;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);
        WebTest = (TextView) findViewById(R.id.webTest);
        new AsyncRequest().execute("123", "/ajax", "foo=bar");
    }

    class AsyncRequest extends AsyncTask<string, integer,="" string="">{

        @Override
        protected String doInBackground(String... arg) {

            return new Request(arg[0], arg[1], arg[2]).Content;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            WebTest.setText(s);
        }
    }
}
</string,>

licensed under cc by-sa 3.0 with attribution.