android应用程序崩溃NetworkOnMainThreadException

时间:2014-06-05 13:35:03

标签: android exception crash

您好我正在尝试使用Android应用程序(客户端)将字符串发送到我的java服务器但是当我点击“登录”按钮时我的应用程序崩溃和eclipse让我出现此错误:

    06-05 15:24:53.506: E/AndroidRuntime(2843): FATAL EXCEPTION: main
06-05 15:24:53.506: E/AndroidRuntime(2843): android.os.NetworkOnMainThreadException
06-05 15:24:53.506: E/AndroidRuntime(2843):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
06-05 15:24:53.506: E/AndroidRuntime(2843):     at libcore.io.BlockGuardOs.recvfrom(BlockGuardOs.java:163)
06-05 15:24:53.506: E/AndroidRuntime(2843):     at libcore.io.IoBridge.recvfrom(IoBridge.java:506)
06-05 15:24:53.506: E/AndroidRuntime(2843):     at java.net.PlainSocketImpl.read(PlainSocketImpl.java:488)
06-05 15:24:53.506: E/AndroidRuntime(2843):     at java.net.PlainSocketImpl.access$000(PlainSocketImpl.java:46)
06-05 15:24:53.506: E/AndroidRuntime(2843):     at java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.java:240)
06-05 15:24:53.506: E/AndroidRuntime(2843):     at libcore.io.Streams.readSingleByte(Streams.java:41)
06-05 15:24:53.506: E/AndroidRuntime(2843):     at java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.java:236)
06-05 15:24:53.506: E/AndroidRuntime(2843):     at java.io.FilterInputStream.read(FilterInputStream.java:114)
06-05 15:24:53.506: E/AndroidRuntime(2843):     at java.io.ObjectInputStream.checkReadPrimitiveTypes(ObjectInputStream.java:405)
06-05 15:24:53.506: E/AndroidRuntime(2843):     at java.io.ObjectInputStream.read(ObjectInputStream.java:564)
06-05 15:24:53.506: E/AndroidRuntime(2843):     at libcore.io.Streams.readFully(Streams.java:81)
06-05 15:24:53.506: E/AndroidRuntime(2843):     at java.io.DataInputStream.readShort(DataInputStream.java:169)
06-05 15:24:53.506: E/AndroidRuntime(2843):     at java.io.DataInputStream.readUnsignedShort(DataInputStream.java:182)
06-05 15:24:53.506: E/AndroidRuntime(2843):     at java.io.DataInputStream.readUTF(DataInputStream.java:186)
06-05 15:24:53.506: E/AndroidRuntime(2843):     at java.io.ObjectInputStream.readUTF(ObjectInputStream.java:2155)
06-05 15:24:53.506: E/AndroidRuntime(2843):     at com.example.social_network.Login$2.onClick(Login.java:120)
06-05 15:24:53.506: E/AndroidRuntime(2843):     at android.view.View.performClick(View.java:4240)
06-05 15:24:53.506: E/AndroidRuntime(2843):     at android.view.View$PerformClick.run(View.java:17721)
06-05 15:24:53.506: E/AndroidRuntime(2843):     at android.os.Handler.handleCallback(Handler.java:730)
06-05 15:24:53.506: E/AndroidRuntime(2843):     at android.os.Handler.dispatchMessage(Handler.java:92)
06-05 15:24:53.506: E/AndroidRuntime(2843):     at android.os.Looper.loop(Looper.java:137)
06-05 15:24:53.506: E/AndroidRuntime(2843):     at android.app.ActivityThread.main(ActivityThread.java:5103)
06-05 15:24:53.506: E/AndroidRuntime(2843):     at java.lang.reflect.Method.invokeNative(Native Method)
06-05 15:24:53.506: E/AndroidRuntime(2843):     at java.lang.reflect.Method.invoke(Method.java:525)
06-05 15:24:53.506: E/AndroidRuntime(2843):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
06-05 15:24:53.506: E/AndroidRuntime(2843):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
06-05 15:24:53.506: E/AndroidRuntime(2843):     at dalvik.system.NativeStart.main(Native Method)

我正在使用AsyncTask创建一个新的Socket,但我不知道哪个按钮监听器需要编写

- > android代码:

    public class Login extends ActionBarActivity {

    private TextView register;
    private TextView connection;
    private Button login;
    private EditText email;
    private EditText password;
    private static ObjectOutputStream oos;
    private static ObjectInputStream ois; 
    Socket client;

    private class myTask extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

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

           try {
                 client = new Socket("10.10.2.209", 4444);  //connect to server
                 oos = new ObjectOutputStream(client.getOutputStream());
                 ois = new ObjectInputStream(client.getInputStream());
           }catch (ConnectException e){
               return "Host not found";
           }catch (IOException e) {
               return "Exception Caught";
           }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {

            super.onPostExecute(result);   

            if ("Host not found".equalsIgnoreCase(result)){ 
                Toast.makeText(getApplicationContext(), "Host not found" ,Toast.LENGTH_LONG).show();
            }else if("Exception Caught".equalsIgnoreCase(result)){
                Toast.makeText(getApplicationContext(), "Connection error" ,Toast.LENGTH_LONG).show();
            }else{
                 Toast.makeText(getApplicationContext(), "Connection established" ,Toast.LENGTH_LONG).show();
             }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        register = (TextView)findViewById(R.id.register);
        login = (Button)findViewById(R.id.login);
        email = (EditText)findViewById(R.id.email);
        password = (EditText)findViewById(R.id.password);
        connection = (TextView)findViewById(R.id.connection);

        new myTask().execute();

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment())
                    .commit();
        }

        register.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View arg0) {
                startActivity(new Intent(Login.this, Register.class)); 
            }
        });

        login.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View arg0) {

                try {
                    oos.writeUTF("LOGIN");
                    oos.flush();

                    String emailText = email.getText().toString();
                    oos.writeUTF(emailText);
                    oos.flush();

                    String passwordText = password.getText().toString();
                    oos.writeUTF(passwordText);
                    oos.flush();

                    String string = ois.readUTF();
                    connection.setText(string);

                    if(string.equals("Login successfully Done!")){
                        connection.setText("Login done!");
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        });
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.login, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_login, container, false);
            return rootView;
        }
    }

}

感谢

1 个答案:

答案 0 :(得分:0)

  

我不知道如何在&#34; onPostExecute&#34;中调用按钮监听器。方法

您无法在onPostExecute()中调用按钮侦听器。你搬家了:

  • 套接字读取逻辑为doInBackground()

  • 将UI更新逻辑转换为onPostExecute()

然后,您从按钮侦听器执行AsyncTask