Lucas Arrefelt
Lucas Arrefelt

Reputation: 3929

Thread only loops once

ive been thinking about this for hours and im not closer to an solution! My thread just stops looping when im fetching a message from an server for some reason, and works perfectly when im not doing it.

This works and prints refreshing every second:

 public class ChatRoom extends Activity implements OnClickListener, Runnable {
        private Thread t = new Thread(this);

        public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.chatroom);

                Button send = (Button) findViewById(R.id.send);
                send.setOnClickListener(this);

                Intent receiver = getIntent();
                String host = receiver.getStringExtra("Host");
                int port = receiver.getIntExtra("Port", 4456);


                try
                {
                    socket = new Socket(host, port);
                    this.receive = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
                    this.send = new PrintWriter(this.socket.getOutputStream(), true);

                } 
                catch(IOException ioe) { System.out.println(ioe); }
                t.start();


            }

            public void run()
            {
                String message = "";

                while(true)
                {
                    try
                    {
                        // message = receive.readLine(); BufferedReader
                        t.sleep(1000);
                    } 
                    //catch(IOException ioe)            { System.out.println(ioe); }
                    catch (NullPointerException npe)    { System.out.println(npe); } 
                    catch (InterruptedException e)      { System.out.println(e);   }

                    System.out.println("Refreshing...");

                }
            }

And when i use my commented code, it actually works and i get a message from the server but it loops just once! Why is that?

Output:
Server Message
Refreshing...

I get no Exception or errors, but i had an error before with some similar code that said that i cant change UI on other threads. So ive been looking at some runOnUiThread but it didnt make it better, and i dont know why it should :(

Upvotes: 1

Views: 886

Answers (3)

Dororo
Dororo

Reputation: 3440

A few things here:

  • Swap from System.out.println("string"); to Log.d("tagname","string"); then look on DDMS for output lines.

I don't think you're creating a thread properly, and you certainly aren't providing any interface to kill it, which may cause issues when you test it. I would separate the thread into a new file, say NameOfThread:

//File "NameOfThread"
public class NameOfThread extends Thread{
//any fields you want here to mess with e.g.
private String message;
private boolean running;


public NameOfThread(){
    message = "";
    running = true;
}

@Override
public void run(){
    while(running){
        //do stuff
    }   
}

public void setRunning(boolean run){
    running = run;
}   

}

//When you want to call it
NameOfThread varThread = new NameOfThread();
varThread.start();

//when you want to kill the thread
varThread.setRunning(false);

You may think 'why bother with this whole running variable junk, I don't need it.' but how else will this thread end gracefully? There is another method of killing the thread properly, which is using InterruptedException and your cleanup code goes there, but that's just an alternative.

Try doing this first, then you'll need to sort out the message itself (the method you're using currently isn't great since readLine() will block until a line is received (meaning you'll get "Refreshing..." when you get a new line rather than once per second.

Upvotes: 3

Howard
Howard

Reputation: 39197

The method BufferedReader.readLine() blocks until a newline character is received. If there is no newline in your receiver stream it will block forever.

Upvotes: 3

Egor
Egor

Reputation: 40203

You're surely getting some exceptions thrown, you just can't see them cause you're trying to print them on the standard output, which is missing on Android. Your exception is handled correctly and the code finishes. To properly get the exception information use Logs, or just throw a RuntimeException. Hope this helps.

Upvotes: 0

Related Questions