0

I have been building an Android app recently and I have had some issues with the networking part. First I got this error and now I have upgraded the program but now I have another problem. I have a separate class which starts it's own thread for sending and another for receiving. Here is the one for sending:

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

import android.widget.EditText;

public class Sender implements Runnable {

    private MulticastSocket so;
    private InetAddress serverAddress;
    private int port;
    private EditText messageBoard;
    private EditText eText1;
    private EditText eText2;
    private EditText eText3;
    private Thread myActivity = new Thread(this);

    public Sender(EditText etHost, EditText etPort, EditText messageBoard, EditText etSend) {
        eText1 = etHost;
        eText2 = etPort;
        eText3 = etSend;
        this.messageBoard = messageBoard;
        myActivity.start();
    }

    @Override
    public void run() {

        // convert the host name to InetAddress
        try {
            //serverAddress = InetAddress.getByName(eText1.getText().toString());
            serverAddress = InetAddress.getByName("atlas.dsv.su.se");
        } catch (Exception e) {}

        //convert the port to an int
        //port = Integer.parseInt(eText2.getText().toString());
        port = 4456;

        // create socket and start communicating
        try {
            so = new MulticastSocket(port);
            so.joinGroup(serverAddress);
        } catch (IOException e) {}

        // start listening for incoming messages
        new Receiver(so, messageBoard);
    }

    /**
     * This method copies the text from the input text field to the conversation text field and
     * cleans the input text field
     */
    public void sendMessage() {

        // get the text that they contain and add the new messages to the old ones
        String message = eText3.getText().toString();
        String conversation = messageBoard.getText().toString();
        String newConverstion = conversation.concat("\n[You] ").concat(message);

        // make the messages text view editable
        messageBoard.setFocusable(true);
        messageBoard.setText(newConverstion);   // add the new message to the text view
        messageBoard.setFocusable(false);   // make the messages text view not editable

        // erase the text on the second text view that has just been sent
        eText3.setText("");

        // Send message to server

        // convert message to bytes array
        byte[] data = (message).getBytes();

        // create and send a datagram
        DatagramPacket packet = new DatagramPacket(data, data.length, serverAddress, port);

        try {
            so.send(packet);
        } catch (IOException e) {}


    }   // end of sendMessage

}

and here is the one for receiving:

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.MulticastSocket;

import android.widget.EditText;

public class Receiver implements Runnable {

    private Thread myActivity = new Thread(this);
    private MulticastSocket so;
    private EditText messageBoard;

    public Receiver(MulticastSocket sock, EditText messBo) {
        so = sock;
        messageBoard = messBo; 
        myActivity.start();
    }

    @Override
    public void run() {
        byte[] data = new byte[1024];   // received data container

        while (true) {
            try {
                // create a datagram for receiving
                DatagramPacket packet = new DatagramPacket(data, data.length);

                // wait for the next message
                so.receive(packet);

                String message = new String(data, 0, packet.getLength());

                // add the new messages to the old ones
                String conversation = messageBoard.getText().toString();
                String newConverstion = conversation.concat("\n[Remote] ").concat(message);

                // make the messages text view editable
                messageBoard.setFocusable(true);
                messageBoard.setText(newConverstion);   // add the new message to the text view
                messageBoard.setFocusable(false);   // make the messages text view not editable


            } catch (IOException ioe) {}
        }
    }

}

When I run it I get:

01-25 00:23:27.281: W/dalvikvm(582): threadid=12: thread exiting with uncaught exception (group=0x409c01f8)
01-25 00:23:27.281: E/AndroidRuntime(582): FATAL EXCEPTION: Thread-80
01-25 00:23:27.281: E/AndroidRuntime(582): java.lang.NullPointerException
01-25 00:23:27.281: E/AndroidRuntime(582):  at com.regeduser00x.proj1.Receiver.run(Receiver.java:31)
01-25 00:23:27.281: E/AndroidRuntime(582):  at java.lang.Thread.run(Thread.java:856)

and line 31 is so.receive(packet); What is its problem?

Community
  • 1
  • 1
RegedUser00x
  • 2,313
  • 5
  • 27
  • 34
  • In `Sender.run` you have a couple of `try`/`catch` pairs, but if there is an exception you don't do anything and let the function continue as nothing happened. This might lead to `null` references if the code inside `try` fails. – Some programmer dude Jan 25 '12 at 06:56

1 Answers1

0

My best guess is that your socket is coming into your receiver constructor null. But without seeing how you are attempting to use this I wouldn't be able to say for sure.

I can say though you might find it simpler to implement your classes with AsyncTask. They were created specifically to make it easier to create and interact with threads.

Here are some things to look over that will aide you with what you are trying to achieve.

These two are part of the developer docs:

http://developer.android.com/resources/articles/painless-threading.html

http://developer.android.com/reference/android/os/AsyncTask.html

and this has a nice example of using an AsyncTask:

http://www.screaming-penguin.com/node/7746

FoamyGuy
  • 46,603
  • 18
  • 125
  • 156
  • That looks interesting but I don't get that part with the parameters. How do I read information from the interface and send it back to the interface if I cannot pass the interface components as types ´AsyncTask´ types? – RegedUser00x Jan 25 '12 at 00:53
  • Actually I deactivated the Receiver and now it crashes when I try to send. So something prevents me from sending and receiving though I have this in separate threads. The solution might be to use AsyncTask. Would somebody give a simple example how this can be rewriten with an AsyncTask? – RegedUser00x Jan 25 '12 at 01:19