2012-07-09 117 views
0

我想通过网络接收图像,我设置了一个服务器,如下显示java.lang.NullPointerException的ServerSocket.accept中的()

public class IServerActivity extends Activity { 
    ServerSocket ss = null; 
    Bitmap bp ; 
    Thread myCommsThread = null; 
    protected static final int MSG_ID = 0x1337; 
    public static final int SERVERPORT = 6000; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     //TextView tv = (TextView) findViewById(R.id.TextView01);  
     this.myCommsThread = new Thread(new CommsThread()); 
     this.myCommsThread.start(); 
    } 

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

    Handler myUpdateHandler = new Handler() { 
     public void handleMessage(Message msg) { 
     switch (msg.what) { 
     case MSG_ID: 
      ImageView iv = (ImageView) findViewById(R.id.imageView01); 
      iv.setImageBitmap(bp);; 
      break; 
     default: 
      break; 
     } 
     super.handleMessage(msg); 
     } 
    }; 
    class CommsThread implements Runnable { 
     public void run() { 
     Socket s = null; 
     try { 
      ss = new ServerSocket(SERVERPORT); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     while (!Thread.currentThread().isInterrupted()) { 
      Message m = new Message(); 
      m.what = MSG_ID; 
      try { 
       if (s == null) 
        s = ss.accept(); 
       bp= BitmapFactory.decodeStream(s.getInputStream()); 
       myUpdateHandler.sendMessage(m); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
     } 
    } 
} 

但它显示了在运行时错误

java.lang.NullPointerException 
E/AndroidRuntime(3047):atExample.IServer.IServerActivity$CommsThread.run(IServerActivity.java:68) 

它显示空指针异常在s = ss.accept();一行。 请帮助我不知道什么是错的。

+0

is“ss = new ServerSocket(SERVERPORT);”抛出异常? PLease检查控制台是否“e.printStackTrace();”被执行 – 2012-07-09 06:46:50

+0

不,“s = ss.accept();”抛出一个空指针异常。并且是“e.printStackTrace()”被执行。 – Akshay 2012-07-09 06:54:23

+0

请帮我卡在这.. – Akshay 2012-07-09 06:55:06

回答

2

如果您收到该行一个空指针异常,它只能意味着早期:

ss = new ServerSocket(SERVERPORT); 

声明没有正常返回。这是唯一的合理的方式,ss可能是null


(其实,有一个其他可能解释。由于ss变量是包私营和final,在同一个包中的一些其他类可以达到并分配null它。但我)

+0

和我能做些什么来让“ss = new ServerSocket(SERVERPORT);”正常返回。 – Akshay 2012-07-09 07:02:16

+1

除非你告诉我们抛出什么异常,否则不可能说。你已经写了一个堆栈跟踪到System.err ...告诉我们它包含了什么。 – 2012-07-09 08:32:30

相关问题