-1

I making android applicaton and i have java.lang.NullPointerException with this code. Java server is on the comuter. Thanks for help.

try {
    ok.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                Socket socket;
                socket = new Socket("192.168.0.179", 5450);
                os = new PrintStream(socket.getOutputStream());
                is = new DataInputStream(socket.getInputStream());
                in = is.readLine().trim();

                if(in == "hello") {
                    os.print(edit.getText().toString());
                    os.flush();
                    Log.d("LoL", in);
                    Log.d("LoL", edit.getText().toString());
                    in = is.readLine().trim();
                    edit.setText(in);
                    os.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    });
} catch (Exception e) {
    Log.d("LoL",e.toString());
}
stealthjong
  • 10,858
  • 13
  • 45
  • 84

1 Answers1

1

The in == "hello" expression will always return false, because you'll want to compare the contents of the strings in and "hello"; that expression checks that they are the same object, and that will never happen. For any non-primitive type like strings, we should write "hello".equals(in). (you may also write in.equals("hello") but the latter form prevents another possible NullPointerException)

Since that expression will always return false, the if block will never execute. Therefore, the NPE may happen only in two places:

  • in ok.setOnClickListener: if the ok variable is null, e.g. is not initialized, calling any method on it will lead to NPE;
  • in in = is.readLine().trim();: if the InputStream is empty (e.g. got no data or EOF from the server) is.readLine() will return null, and calling trim() on a null object will lead to NPE.

BTW, InputStream.readLine() is deprecated, better use BufferedReader instead. That's explained here.

Community
  • 1
  • 1
ris8_allo_zen0
  • 1,537
  • 1
  • 15
  • 35