开发者

force close when try to call a class that implements a Client Thread

I have a client-sever app on android,both running on the same machine. In the first activity of my client app I try to call client class which should connect to the server application,but I get force close.

This is how I call the client class in the first activity of my app:

Thread cThread=new Thread(new ClientThread());
cThread.start(); 

and here is my client class:

public class ClientThread implements Runnable{
    private Handler handler=new Handler();
    Socket  socket;
    private TextView clientState;
    public void 开发者_如何学运维run()
    {
        try
        {
            InetAddress serverAddr=InetAddress.getByName("10.0.2.2");
            handler.post(new Runnable(){
                public void run(){
                    clientState.setText(" try to connect!");
                }
            });
        socket=new Socket(serverAddr, 8080);

            //connected=true;
        handler.post(new Runnable(){
                public void run(){
                    clientState.setText("Connected!");
                }
            });

        }
        catch(Exception e){
            handler.post(new Runnable(){
                public void run(){
                    clientState.setText("Error");
                    }
            });

            e.printStackTrace();
        }

    }

      protected void onStop() {
            super.onStop();
            try {
                 // make sure you close the socket upon exiting
                //out.close();
                 socket.close();
             } catch (IOException e) {
                 e.printStackTrace();
             }
        }

}

Can someone tell what is wrong or at least give me an ideea. One thing that I should say is that my client works fine-it connects to the server,when the client class is integrated in my first activity(I mean,initially I had no client class was all in the first activity...and it worked fine). I'm here for further details! Thank u in advance!


Without the stack trace it looks like it crashes cause you didn't initialize the textview.

package com.example.helloandroid;

import android.app.Activity;
import android.os.Bundle;

public class HelloAndroid extends Activity {
    TextView tv;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tv = (TextView)findViewById(R.id.mytextview);
    }

    public class ClientThread extends Thread {
    ...// Do NOT init textview
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜