简体   繁体   English

java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“int java.io.InputStream.read(byte[])”

[英]java.lang.NullPointerException: Attempt to invoke virtual method 'int java.io.InputStream.read(byte[])' on a null object reference

I am trying to create a Chat Application using WiFip2p.Everything is done in this application.我正在尝试使用 WiFip2p 创建一个聊天应用程序。一切都在这个应用程序中完成。 Before send and receive message app was working good.在发送和接收消息应用程序运行良好之前。 After that, I got this error.在那之后,我得到了这个错误。 I am getting this error when I connect to another device.当我连接到另一台设备时出现此错误。 It shows a null object reference.它显示了一个空对象引用。 I don't know why I need a solution can anyone help me thank you.我不知道为什么我需要一个解决方案,任何人都可以帮助我谢谢。

 public class WiFi_Activity extends AppCompatActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wi_fi_);

        FINDVIEWBYID();
        CLICKLISTINER();
    }


    Handler handler=new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {

            switch (msg.what)
            {
                case MESSAGE_READ:

                    byte[]  readbuffer=(byte[])msg.obj;
                    String tempmez=new String(readbuffer,0,msg.arg1);
                    txt_message.setText(tempmez);
                    break;
            }

            return true;
        }
    });

    private void FINDVIEWBYID() {

            btn_onoff=findViewById(R.id.onOff);
            btn_discover=findViewById(R.id.discover);
            btn_send=findViewById(R.id.sendButton);
            listView=findViewById(R.id.peerListView);
            txt_connectionsts=findViewById(R.id.connectionStatus);
            txt_message=findViewById(R.id.readMsg);
            edit_message=findViewById(R.id.writeMsg);

        wifiManager= (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);

        wifiP2pManager= (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);

        channel=wifiP2pManager.initialize(this,getMainLooper(),null);

        broadcastReceiver=new Wifi_broadcast_reciever(wifiP2pManager,channel,this);

        intentFilter=new IntentFilter();

        intentFilter.addAction(wifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
        intentFilter.addAction(wifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
        intentFilter.addAction(wifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
        intentFilter.addAction(wifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);

    }
    private void CLICKLISTINER() {

        btn_onoff.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                if (wifiManager.isWifiEnabled())
                {
                    wifiManager.setWifiEnabled(false);
                    btn_onoff.setText("ON");
                }
                else
                {
                    wifiManager.setWifiEnabled(true);
                    btn_onoff.setText("OFF");
                }

            }
        });

        btn_discover.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                wifiP2pManager.discoverPeers(channel, new WifiP2pManager.ActionListener() {
                    @Override
                    public void onSuccess() {

                        txt_connectionsts.setText("Discovery Started");
                    }

                    @Override
                    public void onFailure(int reason) {

                        txt_connectionsts.setText("Discovery starting failuree"+String.valueOf(reason));
                    }
                });
            }
        });

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                 final  WifiP2pDevice wifiP2pDevice=devicearray[position];
                WifiP2pConfig config=new WifiP2pConfig();
                config.deviceAddress=wifiP2pDevice.deviceAddress;
                wifiP2pManager.connect(channel, config, new WifiP2pManager.ActionListener() {
                    @Override
                    public void onSuccess() {

                        Toast.makeText(WiFi_Activity.this, "Connect with"+ wifiP2pDevice.deviceName, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onFailure(int reason) {

                        Toast.makeText(WiFi_Activity.this, "Not connected", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });

        btn_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String msz=edit_message.getText().toString();
                sendRecieve.write(msz.getBytes());
            }
        });
    }

    WifiP2pManager.PeerListListener peerListListener=new WifiP2pManager.PeerListListener() {
        @Override
        public void onPeersAvailable(WifiP2pDeviceList peerslist) {

            if (!peerslist.getDeviceList().equals(peers));
            {
                peers.clear();
                peers.addAll(peerslist.getDeviceList());

                devicename_array=new String[peerslist.getDeviceList().size()];
                devicearray=new WifiP2pDevice[peerslist.getDeviceList().size()];
                int index= 0;

                 for (WifiP2pDevice device:peerslist.getDeviceList())
                 {
                     devicename_array[index]=device.deviceName;
                     devicearray[index]=device;
                     index++;
                 }

                 ArrayAdapter<String> arrayAdapter=new ArrayAdapter<String>(getApplicationContext(),R.layout.support_simple_spinner_dropdown_item,devicename_array);
                 listView.setAdapter(arrayAdapter);
            }

            if (peers.size()==0)
            {
                Toast.makeText(WiFi_Activity.this, "No discover show", Toast.LENGTH_SHORT).show();
            }
        }
    };

    WifiP2pManager.ConnectionInfoListener connectionInfoListener=new WifiP2pManager.ConnectionInfoListener() {
        @Override
        public void onConnectionInfoAvailable(WifiP2pInfo info) {

            final InetAddress owneraddress= info.groupOwnerAddress;

            if (info.groupFormed && info.isGroupOwner)
            {
                txt_connectionsts.setText("Host");
                serverclass=new Serverclass();
                serverclass.start();
            }
            else if (info.groupFormed)
            {
                txt_connectionsts.setText("Client");
                clientclass = new Clientclass(owneraddress);
                clientclass.start();

            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(broadcastReceiver,intentFilter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(broadcastReceiver);
    }

    public class Serverclass extends Thread
    {
        Socket socket;
        ServerSocket serverSocket;

        @Override
        public void run() {

            try {
                serverSocket=new ServerSocket(1111);
                socket=serverSocket.accept();
                sendRecieve=new SendRecieve(socket);
                sendRecieve.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public class Clientclass extends Thread
    {

        Socket socket;
        String host_address;

        public Clientclass(InetAddress hostaddress){

            host_address=hostaddress.getHostAddress();
            socket=new Socket();
            sendRecieve=new SendRecieve(socket);
            sendRecieve.start();
        }

        @Override
        public void run() {

            try {
                socket.connect(new InetSocketAddress(host_address,1111),500);


            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private class SendRecieve extends Thread
    {
        private Socket socket;
        private InputStream inputStream;
        private OutputStream outputStream;

        public SendRecieve(Socket skt)
        {

            socket=skt;

            try {
                inputStream=socket.getInputStream();
                outputStream=socket.getOutputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void run() {

            byte[] buffer=new byte[2048];
            int bytes;

            while (socket!=null)
            {
                try {
                    bytes=inputStream.read(buffer);
                    if (bytes>0)
                    {
                        handler.obtainMessage(MESSAGE_READ,bytes,-1,buffer).sendToTarget();
                    }
                } catch (IOException e) {

                    Log.d("error",e.getMessage());
                }
            }
        }


        public void write(byte[] bytes)
        {
            try {
                outputStream.write(bytes);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

I am getting this error on this part of code:-我在这部分代码上收到此错误:-

  @Override
    public void run() {

        byte[] buffer=new byte[2048];
        int bytes;

        while (socket!=null)
        {
            try {
                bytes=inputStream.read(buffer);
                if (bytes>0)
                {
                    handler.obtainMessage(MESSAGE_READ,bytes,-1,buffer).sendToTarget();
                }
            } catch (IOException e) {

                Log.d("error",e.getMessage());
            }
        }
    }

The only thing I can see as being an issue is that you're catching (and ignoring) errors from getInputStream() and getOutputStream() .我能看到的唯一问题是您正在捕获(并忽略)来自getInputStream()getOutputStream() The exception is stopping execution, so if getInputStream() errors out, it doesn't get set.异常是停止执行,所以如果getInputStream()出错,它不会被设置。 Both of your streams would be null.您的两个流都将为空。

Since you're at least printing the stacktrace, check for other stacktraces before the actual crash.由于您至少要打印堆栈跟踪,因此请在实际崩溃之前检查其他堆栈跟踪。 It may tell you more about what went wrong.它可能会告诉您更多关于出了什么问题的信息。

To get around this, I suggest not catching the exception and instead making the constructor throw IOException .为了解决这个问题,我建议不要捕捉异常,而是让构造函数抛出IOException If you catch it early, it will cause less problems for you later on.如果你早点抓住它,它会给你以后带来更少的麻烦。

Edit: I've looked at your classes a bit more, and I see that you don't set the address of the Socket in time.编辑:我多看了你的类,我发现你没有及时设置Socket的地址。 Do that before you get the data streams for it.在获取数据流之前执行此操作。 Not using the fields will work.不使用字段将起作用。

private Socket socket;

public SendRecieve(Socket skt) {
    this.socket = skt;
}

@Override
public void run() {
    try {
        InputStream in = socket.getInputStream();
        ... etc
    } ...
}

You calling Sendreceiver start before Clientclas run executes, so the following is necessary:您在 Clientclas 运行执行之前调用 Sendreceiver start,因此需要执行以下操作:

public class Clientclass extends Thread {

Socket socket;
String host_address;

public Clientclass(InetAddress hostaddress){

    host_address=hostaddress.getHostAddress();
    socket=new Socket();
}

@Override
public void run() {

    try {
        socket.connect(new InetSocketAddress(host_address,1111),500);

    sendRecieve=new SendRecieve(socket);
    sendRecieve.start();

    } catch (IOException e) {
        e.printStackTrace();
    }
}
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 KSoap2 throws Attempt to invoke virtual method 'int java.io.InputStream.read(byte[], int, int)' on a null object reference for some reason - KSoap2 throws Attempt to invoke virtual method 'int java.io.InputStream.read(byte[], int, int)' on a null object reference for some reason java.lang.NullPointerException:尝试在空对象引用上调用虚方法&#39;ActionBar.setNavigationMode(int)&#39; - java.lang.NullPointerException: Attempt to invoke virtual method 'ActionBar.setNavigationMode(int)' on a null object reference java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法FloatingActionButton.setImageResource(int)&#39; - java.lang.NullPointerException: Attempt to invoke virtual method FloatingActionButton.setImageResource(int)' on a null object reference java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“boolean java.io.File.exists()” - java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.io.File.exists()' on a null object reference java.lang.NullPointerException:尝试在空对象引用上调用虚方法,而它不为空 - java.lang.NullPointerException: Attempt to invoke virtual method on a null object reference, while its not null java.lang.NullPointerException:尝试在空对象引用上调用虚方法&#39;int android.view.ViewGroup.getPaddingLeft()&#39; - java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.ViewGroup.getPaddingLeft()' on a null object reference java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“ void android.widget.CardView.setVisibility(int)” - java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.CardView.setVisibility(int)' on a null object reference java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getBottom()' on a null object reference - java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getBottom()' on a null object reference java.lang.NullPointerException:尝试在空对象引用上调用虚方法'android.view.View .MainActivity.findViewById(int)' - java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View .MainActivity.findViewById(int)' on a null object reference java.lang.NullPointerException:尝试对空对象引用调用虚拟方法。 应用程序在运行时崩溃 - java.lang.NullPointerException: Attempt to invoke virtual method on a null object reference. App crashes on run
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM