Android NetworkOnMainThreadException异常

时间:2014-09-25 20:04:42

标签: java android json android-asynctask

我的活动中有这个Networkonmainthread异常。我搜索了问题的解决方案。在我搜索的过程中,我发现我应该使用AsyncTask。在我尝试AsyncTask后,我仍然面临同样的问题。

这是我的注册活动:

    private class MyAsyncTask extends AsyncTask<String, Void, JSONObject> {

        protected JSONObject doInBackground(String... params) {
            UserFunctions userFunction = new UserFunctions();
            if (params.length != 3)
                return null;
            JSONObject json = userFunction.registerUser(params[0], params[1], params[2]);
            return json;
        }

        protected void onPostExecute(JSONObject json) {
            // check for login response
            try {
                if (json != null && json.getString(KEY_SUCCESS) != null) {
                    registerErrorMsg.setText("");
                    String res = json.getString(KEY_SUCCESS); 
                    if(Integer.parseInt(res) == 1){
                        // user successfully registred
                        // Store user details in SQLite Database
                        DatabaseHandler db = new DatabaseHandler(getApplicationContext());
                        JSONObject json_user = json.getJSONObject("user");

                        // Clear all previous data in database
                        UserFunctions userFunction = new UserFunctions();
                        userFunction.logoutUser(getApplicationContext());
                        db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));                        
                        // Launch Dashboard Screen
                        Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);
                        // Close all views before launching Dashboard
                        dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(dashboard);
                        // Close Registration Screen
                        finish();
                    }else{
                        // Error in registration
                        registerErrorMsg.setText("Error occured in registration");
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }




    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);

        // Importing all assets like buttons, text fields
        inputFullName = (EditText) findViewById(R.id.registerName);
        inputEmail = (EditText) findViewById(R.id.registerEmail);
        inputPassword = (EditText) findViewById(R.id.registerPassword);
        btnRegister = (Button) findViewById(R.id.btnRegister);
        btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);
        registerErrorMsg = (TextView) findViewById(R.id.register_error);

        // Register Button Click event
        btnRegister.setOnClickListener(new View.OnClickListener() {         
            public void onClick(View view) {
                String name = inputFullName.getText().toString();
                String email = inputEmail.getText().toString();
                String password = inputPassword.getText().toString();
                new MyAsyncTask().execute(name, email, password);
                UserFunctions userFunction = new UserFunctions();
                JSONObject json = userFunction.registerUser(name, email, password);

                // check for login response
                try {
                    if (json.getString(KEY_SUCCESS) != null) {
                        registerErrorMsg.setText("");
                        String res = json.getString(KEY_SUCCESS); 
                        if(Integer.parseInt(res) == 1){
                            // user successfully registred
                            // Store user details in SQLite Database
                            DatabaseHandler db = new DatabaseHandler(getApplicationContext());
                            JSONObject json_user = json.getJSONObject("user");

                            // Clear all previous data in database
                            userFunction.logoutUser(getApplicationContext());
                            db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));                        
                            // Launch Dashboard Screen
                            Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);
                            // Close all views before launching Dashboard
                            dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            startActivity(dashboard);
                            // Close Registration Screen
                            finish();
                        }else{
                            // Error in registration
                            registerErrorMsg.setText("Error occured in registration");
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

        // Link to Login Screen
        btnLinkToLogin.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                Intent i = new Intent(getApplicationContext(),
                        LoginActivity.class);
                startActivity(i);
                // Close Registration View
                finish();
            }
        });
    }
}

这是我的logcat:

09-26 00:56:23.865: D/AndroidRuntime(791): Shutting down VM
09-26 00:56:23.875: W/dalvikvm(791): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
09-26 00:56:23.925: E/AndroidRuntime(791): FATAL EXCEPTION: main
09-26 00:56:23.925: E/AndroidRuntime(791): android.os.NetworkOnMainThreadException
09-26 00:56:23.925: E/AndroidRuntime(791):  at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
09-26 00:56:23.925: E/AndroidRuntime(791):  at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
09-26 00:56:23.925: E/AndroidRuntime(791):  at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
09-26 00:56:23.925: E/AndroidRuntime(791):  at libcore.io.IoBridge.connect(IoBridge.java:112)
09-26 00:56:23.925: E/AndroidRuntime(791):  at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
09-26 00:56:23.925: E/AndroidRuntime(791):  at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
09-26 00:56:23.925: E/AndroidRuntime(791):  at java.net.Socket.connect(Socket.java:842)
09-26 00:56:23.925: E/AndroidRuntime(791):  at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
09-26 00:56:23.925: E/AndroidRuntime(791):  at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
09-26 00:56:23.925: E/AndroidRuntime(791):  at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
09-26 00:56:23.925: E/AndroidRuntime(791):  at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
09-26 00:56:23.925: E/AndroidRuntime(791):  at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
09-26 00:56:23.925: E/AndroidRuntime(791):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
09-26 00:56:23.925: E/AndroidRuntime(791):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
09-26 00:56:23.925: E/AndroidRuntime(791):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
09-26 00:56:23.925: E/AndroidRuntime(791):  at library.JSONParser.getJSONFromUrl(JSONParser.java:45)
09-26 00:56:23.925: E/AndroidRuntime(791):  at library.UserFunctions.registerUser(UserFunctions.java:62)
09-26 00:56:23.925: E/AndroidRuntime(791):  at com.example.bustracker.RegisterActivity$1.onClick(RegisterActivity.java:105)
09-26 00:56:23.925: E/AndroidRuntime(791):  at android.view.View.performClick(View.java:4084)
09-26 00:56:23.925: E/AndroidRuntime(791):  at android.view.View$PerformClick.run(View.java:16966)
09-26 00:56:23.925: E/AndroidRuntime(791):  at android.os.Handler.handleCallback(Handler.java:615)
09-26 00:56:23.925: E/AndroidRuntime(791):  at android.os.Handler.dispatchMessage(Handler.java:92)
09-26 00:56:23.925: E/AndroidRuntime(791):  at android.os.Looper.loop(Looper.java:137)
09-26 00:56:23.925: E/AndroidRuntime(791):  at android.app.ActivityThread.main(ActivityThread.java:4745)
09-26 00:56:23.925: E/AndroidRuntime(791):  at java.lang.reflect.Method.invokeNative(Native Method)
09-26 00:56:23.925: E/AndroidRuntime(791):  at java.lang.reflect.Method.invoke(Method.java:511)
09-26 00:56:23.925: E/AndroidRuntime(791):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
09-26 00:56:23.925: E/AndroidRuntime(791):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
09-26 00:56:23.925: E/AndroidRuntime(791):  at dalvik.system.NativeStart.main(Native Method)
09-26 00:56:24.215: W/System.err(791): org.apache.http.conn.HttpHostConnectException: Connection to http:// refused
09-26 00:56:24.436: W/System.err(791):  at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:183)
09-26 00:56:24.546: W/System.err(791):  at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
09-26 00:56:24.786: W/System.err(791):  at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
09-26 00:56:24.967: W/System.err(791):  at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
09-26 00:56:24.995: W/System.err(791):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
09-26 00:56:25.017: W/System.err(791):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
09-26 00:56:25.017: W/System.err(791):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
09-26 00:56:25.165: W/System.err(791):  at library.JSONParser.getJSONFromUrl(JSONParser.java:45)
09-26 00:56:25.235: W/System.err(791):  at library.UserFunctions.registerUser(UserFunctions.java:62)
09-26 00:56:25.264: W/System.err(791):  at com.example.bustracker.RegisterActivity$MyAsyncTask.doInBackground(RegisterActivity.java:43)
09-26 00:56:25.265: W/System.err(791):  at com.example.bustracker.RegisterActivity$MyAsyncTask.doInBackground(RegisterActivity.java:1)
09-26 00:56:25.285: W/System.err(791):  at android.os.AsyncTask$2.call(AsyncTask.java:287)
09-26 00:56:25.305: W/System.err(791):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
09-26 00:56:25.535: W/System.err(791):  at java.util.concurrent.FutureTask.run(FutureTask.java:137)
09-26 00:56:25.535: W/System.err(791):  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
09-26 00:56:25.675: W/System.err(791):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
09-26 00:56:25.956: W/System.err(791):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
09-26 00:56:26.115: W/System.err(791):  at java.lang.Thread.run(Thread.java:856)
09-26 00:56:26.147: W/System.err(791): Caused by: java.net.ConnectException: failed to connect to /127.0.0.1 (port 8888): connect failed: ECONNREFUSED (Connection refused)
09-26 00:56:26.226: W/System.err(791):  at libcore.io.IoBridge.connect(IoBridge.java:114)
09-26 00:56:26.226: W/System.err(791):  at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
09-26 00:56:26.236: W/System.err(791):  at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
09-26 00:56:26.236: W/System.err(791):  at java.net.Socket.connect(Socket.java:842)
09-26 00:56:26.246: W/System.err(791):  at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
09-26 00:56:26.255: W/System.err(791):  at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
09-26 00:56:26.255: W/System.err(791):  ... 17 more
09-26 00:56:26.266: W/System.err(791): Caused by: libcore.io.ErrnoException: connect failed: ECONNREFUSED (Connection refused)
09-26 00:56:26.276: W/System.err(791):  at libcore.io.Posix.connect(Native Method)
09-26 00:56:26.286: W/System.err(791):  at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:85)
09-26 00:56:26.286: W/System.err(791):  at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
09-26 00:56:26.286: W/System.err(791):  at libcore.io.IoBridge.connect(IoBridge.java:112)
09-26 00:56:26.296: W/System.err(791):  ... 22 more
09-26 00:56:26.296: E/Buffer Error(791): Error converting result java.lang.NullPointerException
09-26 00:56:26.305: E/JSON Parser(791): Error parsing data org.json.JSONException: End of input at character 0 of 
09-26 00:56:27.146: I/Process(791): Sending signal. PID: 791 SIG: 9

我做错了什么?

3 个答案:

答案 0 :(得分:2)

stacktrace表示你正在调用getJSONFromUrl()中的网络操作并在registerUser()中的UI线程上调用它。这里的代码看起来是罪魁祸首:

new MyAsyncTask().execute(name, email, password);
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.registerUser(name, email, password);

你首先在后台asynctask中调用registerUser()(好!)然后只有几行后来在主线程上再次做同样的事情(坏!)。删除后者。

答案 1 :(得分:0)

我打赌userFunction.logoutUser(getApplicationContext());发出网络请求注销用户因此在主线程上访问网络导致的错误(onPostResult在ui线程上运行,与doInBackground相反)

答案 2 :(得分:0)

根据帖子中的代码,您仍然可以直接从onClickListener处理程序内部调用userFunction.registerUser - 在调用MyAsyncTask.execute之后。这是registerUser调用logcat输出所抱怨的,而不是AsyncTask中的那个。您是否意味着在将该逻辑移动到AsyncTask之后从onClickListener处理程序中删除重复调用?