将数据从公共方法传递到私有方法错误

时间:2018-04-16 07:30:16

标签: android bluetooth nullpointerexception

我正在创建一个蓝牙应用程序,我正在尝试从公共方法向私有方法发送数据但我收到此错误

  

java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'android.content.res.Resources android.content.Context.getResources()'

公共方法:

public void showTimeSet(long interval, Context context){
    if(interval !=0){
        Toast.makeText(context,"Countdown second is "+interval,Toast.LENGTH_LONG).show();
        String msg= String.valueOf(interval);
        try {
            sendMessage(msg);
        }catch (Exception e){
            Log.e(TAG, "showTimeSet Error sending message: "+e);
        }
    }
}

和sendMessage方法:

private void sendMessage(String message) {
    // Check that we're actually connected before trying anything
    if (mChatService.getState() != BluetoothService.STATE_CONNECTED) {
        Toast.makeText(getActivity(), R.string.not_connected, Toast.LENGTH_SHORT).show();
        return;
    }

    // Check that there's actually something to send
    if (message.length() > 0) {
        // Get the message bytes and tell the BluetoothService to write
        byte[] send = message.getBytes();
        mChatService.write(send);

        // Reset out string buffer to zero and clear the edit text field
        mOutStringBuffer.setLength(0);
        mOutEditText.setText(mOutStringBuffer);
    }
}

1 个答案:

答案 0 :(得分:0)

您传递给 showTimeSet 的参数上下文似乎是 null ,因此在尝试将该上下文用于Toast时会导致nullpointer异常。

检查你的函数调用 showTimeSet ,并确保上下文是一个实际的Activity / Fragment Context等,其中toast可以显示在。

相关问题