Error sending edittext in java server. See code

2019-03-03 15:06发布

Here is a working code of mine. But when I try to click the buttont that connects my client to port, my app crashes. See my code.

public class Order extends Activity {
    Button GoBackHome;
    private Button button1, button3;  
    private EditText txtbox1,txtbox2,txtbox3,txtbox4,textField;  
    private TextView tv;
    Button PayNow;
    CheckBox chxbx1, chxbx2, chxbx3,chxbx4;

    @Override
    public void onBackPressed() {
    }

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

            GoBackHome = (Button) findViewById(R.id.gohomebutton);
            PayNow = (Button) findViewById(R.id.button2);
            txtbox1= (EditText) findViewById(R.id.editText1);  
            button1 = (Button) findViewById(R.id.button1);  
            tv = (TextView) findViewById(R.id.editText5);  
            txtbox2= (EditText) findViewById(R.id.editText2);
            txtbox3= (EditText) findViewById(R.id.editText3);
            txtbox4= (EditText) findViewById(R.id.editText4);
            chxbx1 = (CheckBox)findViewById(R.id.checkbox1);
            chxbx2 = (CheckBox)findViewById(R.id.checkbox2);
            chxbx3 = (CheckBox)findViewById(R.id.checkbox3);
            chxbx4 = (CheckBox)findViewById(R.id.checkbox4);
            button3 = (Button) findViewById(R.id.button3);
            textField = (EditText) findViewById(R.id.editText6);
            button1.setOnClickListener(new clicker());
            Button get_view_button = (Button) findViewById(R.id.viewsummary);
            get_view_button.setOnClickListener(get_view_button_listener);

            GoBackHome.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    final Intent i = new Intent(Order.this, MainActivity.class);               
                    startActivity(i);
                }
            });

            PayNow.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    final Intent i = new Intent(Order.this, Payment.class);               
                    startActivity(i);
                }
            });

            chxbx1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView,
                    boolean isChecked) {
                    if (chxbx1.isChecked()) {
                        txtbox1.setEnabled(true);
                        txtbox1.setFocusable(true);
                    } else {
                        txtbox1.setEnabled(false);
                        txtbox1.setFocusable(false);
                    }
                }
            });

            chxbx2.setOnCheckedChangeListener(new OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView,
                    boolean isChecked) {
                    if (chxbx2.isChecked()) {
                        txtbox2.setEnabled(true);
                        txtbox2.setFocusable(true);
                    } else {
                        txtbox2.setEnabled(false);
                        txtbox2.setFocusable(false);
                    }
                }
            });

            chxbx3.setOnCheckedChangeListener(new OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView,
                    boolean isChecked) {
                    if (chxbx3.isChecked()) {
                        txtbox3.setEnabled(true);
                        txtbox3.setFocusable(true);
                    } else {
                        txtbox3.setEnabled(false);
                        txtbox3.setFocusable(false);
                    }
                }
            });

            chxbx4.setOnCheckedChangeListener(new OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView,
                    boolean isChecked) {
                    if (chxbx4.isChecked()) {
                        txtbox4.setEnabled(true);
                        txtbox4.setFocusable(true);
                    } else {
                        txtbox4.setEnabled(false);
                        txtbox4.setFocusable(false);
                    }
                }
            });



    }

    private Button.OnClickListener get_view_button_listener = new Button.OnClickListener() {
        public void onClick(View v) {
          String r = "";
          if (chxbx1.isChecked()) {
            r = r + "\n" + chxbx1.getText() + ".............." + txtbox1.getText().toString();
            txtbox1.setEnabled(true);
            txtbox1.setFocusable(true);
          }
          if (chxbx2.isChecked()) {
            r = r + "\n" + chxbx2.getText() + ".............." + txtbox2.getText().toString();
            txtbox2.setEnabled(true);
            txtbox2.setFocusable(true);
          }
          if (chxbx3.isChecked()) {
            r = r + "\n" + chxbx3.getText() + ".............." + txtbox3.getText().toString();
            txtbox3.setEnabled(true);
            txtbox3.setFocusable(true);
          }
          if (chxbx4.isChecked()) {
            r = r + "\n" + chxbx4.getText() + ".............." + txtbox4.getText().toString();
            txtbox4.setEnabled(true);
            txtbox4.setFocusable(true);
          }
          textField.setText(r);

          button3.setOnClickListener(new View.OnClickListener()
          {

              public void onClick(View v)
              {
                  new ConnectToServerTask().execute(textField);
              }
          });

        }


      };



    class clicker implements Button.OnClickListener  
    {  
        public void onClick(View v)  
        {  
            String a,b,c,d;  
            Integer vis;  
            a = txtbox1.getText().toString();  
            b = txtbox2.getText().toString();
            c = txtbox3.getText().toString();
            d = txtbox4.getText().toString();
            vis = Integer.parseInt(a)*2+Integer.parseInt(b)*3+Integer.parseInt(c)*4+Integer.parseInt(d)*5;  
            tv.setText(vis.toString());  


        }  

    }  



}

I dont know if the positioning of the below code is on its right section.

button3.setOnClickListener(new View.OnClickListener()
          {

              public void onClick(View v)
              {
                  new ConnectToServerTask().execute

(textField);
              }
          });

Here is my code on the server side:

public class TestTCP { private static final int PORT = 1485;

private static ServerSocket serverSocket;
private static Socket clientSocket;
private static InputStreamReader inputStreamReader;
private static BufferedReader bufferedReader;
private static String message;
private static String multiple;

public static void main(String[] args)
{
    try
    {
        serverSocket = new ServerSocket(PORT, 0, InetAddress.getLocalHost());

        System.out.println("IP:  " + serverSocket.getInetAddress() + "  Port:  " +  serverSocket.getLocalPort());

    } catch (IOException e)
    {
        System.out.println("Could not listen on port: 1447");
    }

    System.out.println("Server started. Listening to the port 1447");

    while (true)
    {
        try
        {{
            clientSocket = serverSocket.accept(); // accept the client connection
            inputStreamReader = new InputStreamReader(clientSocket.getInputStream());
            bufferedReader = new BufferedReader(inputStreamReader); // get the client message
            message = bufferedReader.readLine();

            while ((message = bufferedReader.readLine()) != null) {
                System.out.println("Message from Table 1: " + message);}
                inputStreamReader.close();
                clientSocket.close();}

        } catch (IOException ex)
        {
            ex.printStackTrace();
            System.out.println("Problem in message reading");
        }
        finally {
            try {
                if (bufferedReader != null)bufferedReader.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
    }
}}}

And this is for the Asynctask (If you want to see it):

public class ConnectToServerTask extends AsyncTask<View, Integer, Socket>
{
    private static final String IP_ADDRESS = "192.168.1.102";  // Kerv Server
    private static final int DEST_PORT = 1485; //port that is used

    private EditText mTextField;

    /**
     * Store provided views (used later in onPostExecute(...)).
     * 
     * Create socket to communicate with server (blocking call).
     */
    protected Socket doInBackground(View... params)
    {
        // Store provided views.
        if (params.length != 1)
            throw new IllegalArgumentException();

        mTextField = (EditText) params[0];


        // Create socket.
        Socket client = null;

        try
        {
            client = new Socket(IP_ADDRESS, DEST_PORT); // connect to server
        } catch (UnknownHostException e)
        {
            e.printStackTrace();
        } catch (IOException e)
        {
            e.printStackTrace();
        }

        return client;
    }

    /**
     * Write to server.
     */
    protected void onPostExecute(Socket client)
    {
        try
        {
            PrintWriter printwriter;
            String messsage;

            messsage = mTextField.getText().toString(); // get the text message on the text field
            mTextField.setText("\n"); // Reset the text field to blank

            printwriter = new PrintWriter(client.getOutputStream(), true);
            printwriter.write(messsage); // write the message to output stream

            printwriter.flush();
            printwriter.close();

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

LOGCAT:

08-29 07:36:54.398: E/AndroidRuntime(31968): FATAL EXCEPTION: main
08-29 07:36:54.398: E/AndroidRuntime(31968): java.lang.NullPointerException
08-29 07:36:54.398: E/AndroidRuntime(31968):    at com.example.controlsystemfinale.ConnectToServerTask.onPostExecute(ConnectToServerTask.java:72)
08-29 07:36:54.398: E/AndroidRuntime(31968):    at com.example.controlsystemfinale.ConnectToServerTask.onPostExecute(ConnectToServerTask.java:1)
08-29 07:36:54.398: E/AndroidRuntime(31968):    at android.os.AsyncTask.finish(AsyncTask.java:602)
08-29 07:36:54.398: E/AndroidRuntime(31968):    at android.os.AsyncTask.access$600(AsyncTask.java:156)
08-29 07:36:54.398: E/AndroidRuntime(31968):    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
08-29 07:36:54.398: E/AndroidRuntime(31968):    at android.os.Handler.dispatchMessage(Handler.java:99)
08-29 07:36:54.398: E/AndroidRuntime(31968):    at android.os.Looper.loop(Looper.java:154)
08-29 07:36:54.398: E/AndroidRuntime(31968):    at android.app.ActivityThread.main(ActivityThread.java:4945)
08-29 07:36:54.398: E/AndroidRuntime(31968):    at java.lang.reflect.Method.invokeNative(Native Method)
08-29 07:36:54.398: E/AndroidRuntime(31968):    at java.lang.reflect.Method.invoke(Method.java:511)
08-29 07:36:54.398: E/AndroidRuntime(31968):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
08-29 07:36:54.398: E/AndroidRuntime(31968):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
08-29 07:36:54.398: E/AndroidRuntime(31968):    at dalvik.system.NativeStart.main(Native Method)

1条回答
放荡不羁爱自由
2楼-- · 2019-03-03 15:35

It looks like the problem is that mTextField is null in ConnectToServerTask. You either need to create a constructor in that class to accept an EditText which you are trying to pass it in your onClick() but it looks wrong or make it an inner class. If you are going to pass it then it should be like

new ConnectToServerTask(textField).execute;

then have a constructor to take an EditText like

public ConnectToServerTask(EditText textField)
{
    mTextField = textField;
}

which is going to cause you more problems. But if you make your AsyncTask an inner class of your Activity and textField is a member variable then your AsyncTask will already have access to it without passing anything.

Edit

public class Order extends Activity {
    Button GoBackHome;
    private Button button1, button3;  
    private EditText txtbox1,txtbox2,txtbox3,txtbox4,textField;  
    private TextView tv;
    Button PayNow;
    CheckBox chxbx1, chxbx2, chxbx3,chxbx4;


    // other functions such as onCreate()
    private class ConnectToServerTask extends AsyncTask<View, Integer, Socket> // inner class here inside your Activity
{
    private static final String IP_ADDRESS = "192.168.1.102";  // Kerv Server
    private static final int DEST_PORT = 1485; //port that is used

    private EditText mTextField;

    /**
    * Store provided views (used later in onPostExecute(...)).
    * 
    * Create socket to communicate with server (blocking call).
    */
    protected Socket doInBackground(View... params)
    {
查看更多
登录 后发表回答