Android处理程序nullpointexception

时间:2018-04-10 13:17:06

标签: java android multithreading nullpointerexception handler

Android处理程序问题

我创建了一个单独的线程文件

请参阅另一项活动中的主题。

尝试使用处理程序更改UI时出现问题。

这部分是零点。

Message hdmsg= handler.obtainMessage();

我不知道哪个部分是问题。

ClientThread.java

public class ClientThread extends Thread{
    public ClientThread() {
    }
    public void run(){
        try{
            Thread currThread = Thread.currentThread();
            while (currThread == thisThread) {

                String recvData = ct_in.readUTF();

                StringTokenizer st = new StringTokenizer(recvData, SEPARATOR);
                int command = Integer.parseInt(st.nextToken());
                switch (command) {
                    case MDY_WAITINFO: {
                        StringTokenizer st1 = new StringTokenizer(st.nextToken(), DELIMETER);
                        StringTokenizer st2 = new StringTokenizer(st.nextToken(), DELIMETER); 
                                    /* 
                                     code~ 
                                    */
                        Message hdmsg= handler.obtainMessage();
                        hdmsg.obj=st;
                        handler.sendMessage(hdmsg);

                        break;
                    }
                }
            }
        } catch (IOException e) {
            System.out.println(e);
            release();
        }
    }
}

RoomList.java

public class HostRoomListActivity extends AppCompatActivity {
    public static Handler handler;
    protected void onCreate(Bundle savedInstanceState) {
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            SocketHostRoom client = new SocketHostRoom();
            client.start();
            handler = new Handler(){
                public void handleMessage(Message msg){
                    String txtmsg = msg.obj.toString();
                }
            };
        }
        class SocketHostRoom extends Thread{
            public void run(){
                ClientThread thread = new ClientThread();
                thread.start();
                thread.requestHostRoomList();
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

尝试拨打HostRoomListActivity.handler.obtainMessage();而不是handler.obtainMessage();

很抱歉这种混淆仍然需要以这种方式调用,但是在设置处理程序之前还要调用SocketHostRoom client = new SocketHostRoom();

       handler = new Handler(){ 
              public void handleMessage(Message msg){ 
                         String txtmsg = msg.obj.toString();  
              } 
       };

首先尝试设置处理程序,因为这是问题的原因,因为当您调用public static Handler handler;时,它会将其设置为空