Ad

Code Works In Old Project, Doesn't In New Project

- 1 answer

I have an old project from around May last year which works like intended, but when I copy/paste the code into a new project it throws an exception. The code in question is a simple TCP/IP Client.

When pasted into a new project it throws a NPE exception:

com.example.myapplication E/AndroidRuntime: FATAL EXCEPTION: Thread-5 
Process: com.example.myapplication, PID: 32308
java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.DataOutputStream.writeBytes(java.lang.String)' on a null object reference
    at com.example.myapplication.MainActivity$sendMessage.run(MainActivity.java:212)
    at java.lang.Thread.run(Thread.java:761)

I tried looking for answers about Socket NPE but I couldn't find any relevant to me since this code was (and is) working when running in the older project.

I used the Studios debugger and as one would expect "socket = null" is shown. Here is the initialization of my socket inside "try" block with "catch":

InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
                socket = new Socket(serverAddr, 502);
                os = new DataOutputStream(socket.getOutputStream());
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

And the full code:

public class MainActivity extends AppCompatActivity
{

    public EditText serverIp,smessage;
    public TextView chat,VALUE0,VALUE1,VALUE2,VALUE3;
    public Button connectPhones,disconnectPhones,send;
    public String serverIpAddress = "",msg = "",msg1 = "",str = "";
    public String substrVALUE,substrMSG = "";
    public Handler handler = new Handler();
    public Socket socket;
    public DataOutputStream os;
    public BufferedReader in;
    public int i,ID,TYPE;

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

        serverIp = (EditText) findViewById(R.id.server_ip);
        smessage = (EditText) findViewById(R.id.smessage);
        chat = (TextView) findViewById(R.id.chat);
        VALUE0 = (TextView) findViewById(R.id.VALUE0);
        VALUE1 = (TextView) findViewById(R.id.VALUE1);
        VALUE2 = (TextView) findViewById(R.id.VALUE2);
        VALUE3 = (TextView) findViewById(R.id.VALUE3);

        send = (Button) findViewById(R.id.send_button);
        connectPhones = (Button) findViewById(R.id.connectPhones);
        disconnectPhones = (Button) findViewById(R.id.disconnectPhones);

        connectPhones.setEnabled(true);
        disconnectPhones.setEnabled(false);
        send.setEnabled(false);

        connectPhones.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                connectPhones.setEnabled(false);
                disconnectPhones.setEnabled(true);
                send.setEnabled(true);
                serverIpAddress = serverIp.getText().toString();
                str = "";
                if (!serverIpAddress.equals(""))
                {
                    Thread clientThread = new Thread(new ClientThread());
                    clientThread.start();
                }
            }
        });

        send.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                 Thread sendThread = new Thread(new sendMessage());
                 sendThread.start();
            }
        });

        disconnectPhones.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
           {
              connectPhones.setEnabled(true);
              disconnectPhones.setEnabled(false);
              send.setEnabled(false);
                  try
                  {
                      socket.close();
                      handler.post(new Runnable() {
                          @Override
                          public void run() {
                              chat.setText("");
                              str = "";
                          }
                      });
                  }
                  catch (IOException e)
                  {
                  }
                  str = "";
                  msg = "";
           }
        });
    }

    public class ClientThread implements Runnable
    {
        public void run()
        {
            try
            {
                InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
                socket = new Socket(serverAddr, 502);
                os = new DataOutputStream(socket.getOutputStream());
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));


                while(true) {

                    String line = null;
                    while ((line = in.readLine()) != null)
                    {
                        msg1 = line;
                        substrMSG=msg1.toString();

                        //if ( substrMSG.substring(0,1).matches("S"))
                        //{
                            i = 0;
                            while (i < msg1.length())
                            {
                                String cutting and printing to textView
                    }
                    Thread.sleep(100);
                }
            }
            catch (Exception e)
            {
            }
        }
    }

    class sendMessage implements Runnable
    {
        @Override
        public void run()
        {
            try
            {
                str = smessage.getText().toString();
                str = str + "\n";
                msg = msg + "C: " + str;
                handler.post(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        chat.setText(msg);
                    }
                });
                os.writeBytes(str);
                os.flush();
            }
            catch(IOException e)
            {
            }
        }
    }
}

What must I change to make it work?

Ad

Answer

As EpicPandaForce commented, I forgot to set the correct permissions.

Ad
source: stackoverflow.com
Ad