简体   繁体   中英

Java android project import NetworkOnMainThreadException

After project import on a different environment I'm getting a NetworkOnMainThreadException on calling a function inside the onCreate method of the main class.

The function acts as a collector for initializing different variables, so i think it shouldn't really do bad stuff...

Here is the onCreate:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    init_vars();        
}

Here is the function:

public void init_vars() {

    this.chat = new Chat();

    // init mode
    Map<String, String> l_mode = new HashMap<String, String>();
    l_mode.put("0", "world");
    l_mode.put("1", "free");
    l_mode.put("2", "joint");
    l_mode.put("3", "tool");
    l_mode.put("4", "comp");
    l_mode.put("selected", "0");
    l_mode.put("default", "0");
    setB_mode(l_mode);

    // init power
    Map<String, String> l_on_off = new HashMap<String, String>();
    l_on_off.put("0", "off");
    l_on_off.put("1", "on");
    l_on_off.put("selected", "0");
    l_on_off.put("default", "0");
    setB_on_off(l_on_off);

    // init power mode
    Map<String, String> l_system_mode = new HashMap<String, String>();
    l_system_mode.put("0", "auto");
    l_system_mode.put("1", "manual");
    l_system_mode.put("selected", "0");
    l_system_mode.put("default", "0");
    setB_system_mode(l_system_mode);

    // init disp
    Map<String, String> l_disp = new HashMap<String, String>();
    l_disp.put("0", "joint ");
    l_disp.put("1", "world ");
    l_disp.put("2", "status ");
    l_disp.put("3", "I/O ");
    l_disp.put("4", "last_error ");
    l_disp.put("selected", "0");
    l_disp.put("default", "0");
    setB_disp(l_disp);
    // set initial text
    TextView editText = (TextView) findViewById(R.id.editText1);
    editText.setText("Some text");

    // init errors array
    // NOT USED
    Map<String, String> l_error_types = new HashMap<String, String>();
    // set predefined error messages
    l_error_types.put("0", "error_message = go home");
    l_error_types.put("1", "error_message = go away");
    setB_error_types(l_error_types);
    // init errors reported
    // define a new error here like this:
    // l_errors.put("0", "1"); //1 represents error type
    Map<String, String> l_errors = new HashMap<String, String>();
    l_errors.put("0", "Error test 0");
    l_errors.put("1", "Error test 1");
    l_errors.put("2", "Error test 1");
    l_errors.put("3", "Error test 4");
    l_errors.put("4", "Error test 5");
    setB_errors(l_errors);
}

And the logcat:

    08-22 11:56:40.512: E/AndroidRuntime(1146): FATAL EXCEPTION: main
    08-22 11:56:40.512: E/AndroidRuntime(1146): Process: com.example.robot_industrial, PID: 1146
    08-22 11:56:40.512: E/AndroidRuntime(1146): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.robot_industrial/com.example.robot_industrial.MainActivity}: android.os.NetworkOnMainThreadException
    08-22 11:56:40.512: E/AndroidRuntime(1146):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2176)
    08-22 11:56:40.512: E/AndroidRuntime(1146):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2226)
    08-22 11:56:40.512: E/AndroidRuntime(1146):     at android.app.ActivityThread.access$700(ActivityThread.java:135)
    08-22 11:56:40.512: E/AndroidRuntime(1146):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1397)
    08-22 11:56:40.512: E/AndroidRuntime(1146):     at android.os.Handler.dispatchMessage(Handler.java:102)
    08-22 11:56:40.512: E/AndroidRuntime(1146):     at android.os.Looper.loop(Looper.java:137)
    08-22 11:56:40.512: E/AndroidRuntime(1146):     at android.app.ActivityThread.main(ActivityThread.java:4998)
    08-22 11:56:40.512: E/AndroidRuntime(1146):     at java.lang.reflect.Method.invokeNative(Native Method)
    08-22 11:56:40.512: E/AndroidRuntime(1146):     at java.lang.reflect.Method.invoke(Method.java:515)
    08-22 11:56:40.512: E/AndroidRuntime(1146):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
    08-22 11:56:40.512: E/AndroidRuntime(1146):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
    08-22 11:56:40.512: E/AndroidRuntime(1146):     at dalvik.system.NativeStart.main(Native Method)
    08-22 11:56:40.512: E/AndroidRuntime(1146): Caused by: android.os.NetworkOnMainThreadException
    08-22 11:56:40.512: E/AndroidRuntime(1146):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
    08-22 11:56:40.512: E/AndroidRuntime(1146):     at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
    08-22 11:56:40.512: E/AndroidRuntime(1146):     at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
    08-22 11:56:40.512: E/AndroidRuntime(1146):     at libcore.io.IoBridge.connect(IoBridge.java:112)
    08-22 11:56:40.512: E/AndroidRuntime(1146):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
    08-22 11:56:40.512: E/AndroidRuntime(1146):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    08-22 11:56:40.512: E/AndroidRuntime(1146):     at java.net.Socket.startupSocket(Socket.java:567)
    08-22 11:56:40.512: E/AndroidRuntime(1146):     at java.net.Socket.tryAllAddresses(Socket.java:128)
    08-22 11:56:40.512: E/AndroidRuntime(1146):     at java.net.Socket.<init>(Socket.java:178)
    08-22 11:56:40.512: E/AndroidRuntime(1146):     at java.net.Socket.<init>(Socket.java:150)
    08-22 11:56:40.512: E/AndroidRuntime(1146):     at com.example.robot_industrial.Chat.<init>(Chat.java:17)
    08-22 11:56:40.512: E/AndroidRuntime(1146):     at com.example.robot_industrial.MainActivity.init_vars(MainActivity.java:694)
    08-22 11:56:40.512: E/AndroidRuntime(1146):     at com.example.robot_industrial.MainActivity.onCreate(MainActivity.java:72)
    08-22 11:56:40.512: E/AndroidRuntime(1146):     at android.app.Activity.performCreate(Activity.java:5243)
    08-22 11:56:40.512: E/AndroidRuntime(1146):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
    08-22 11:56:40.512: E/AndroidRuntime(1146):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2140)
    08-22 11:56:40.512: E/AndroidRuntime(1146):     ... 11 more

Any ideas on what I'm doing wrong ?

You are creating an instance of your Chat object, which is opening up a socket connection with something. As the exception indicates, please do not do network I/O on the main application thread. Please initialize and use your Chat object on some form of background thread.

Execute your Network related operation in AsyncTask

This exception is thrown when an application attempts to perform a networking operation on its main thread.

This happens in Android 3.0 and above. From Android 3.0 and above, they have restricted using network operations (functions that access the Internet) from running in the main thread/UI thread (what spawns from your on create and on resume methods in the activity).

This is to encourage using separate threads for network operations. See AsyncTask for more details on how to perform network activities the right way.

You can also refer here Android AsyncTask

public class ExcuteNetworkOperation extends AsyncTask<Void, Void, String>{

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            /**
             * show dialog
             */
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(Void... params) {
            // TODO Auto-generated method stub
            /**
             * Do network related stuff
             * return string response.
             */
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            /**
             * update ui thread and remove dialog
             */
            super.onPostExecute(result);
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM