使用openFileOutput时,在内部类中正确使用上下文?

时间:2012-02-05 18:03:22

标签: java android inner-classes android-context

我正在尝试调整Android BluetoothChat示例,以使用BluetoothChatService类中的openFileOutput将InputStream保存到文件。使用Environment.getExternalStorageDirectory并使用filewriter保存到sdcard时没有问题,但使用带有MODE_PRIVATE的openFileOutput方法会返回nullPointerException,如其他几个问题/答案中所述。我不能为我的生活找出正确的方法来获得正确的背景。

   private class ConnectedThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;
        private Context mContext;

        public ConnectedThread(BluetoothSocket socket) {
            Log.d(TAG, "create ConnectedThread");
            mmSocket = socket;
            InputStream tmpIn = null;
            OutputStream tmpOut = null;

            // Get the BluetoothSocket input and output streams
            try {
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e) {
                Log.e(TAG, "temp sockets not created", e);
            }

            mmInStream = tmpIn;
            mmOutStream = tmpOut;
        }

        public void run() {
            Log.i(TAG, "BEGIN mConnectedThread");
            byte[] buffer = new byte[1024];
            int bytes;

            // Keep listening to the InputStream while connected
            while (true) {
                try {
                    // Read from the InputStream
                    bytes = mmInStream.read(buffer);
                    // Save to file
                    String FILENAME = "chat.txt";

                    FileOutputStream fos = mContext.openFileOutput(FILENAME, Context.MODE_PRIVATE);
                    fos.write(bytes);
                    fos.close();
                    // Send the obtained bytes to the UI Activity
                    mHandler.obtainMessage(BluetoothChat.MESSAGE_READ, bytes, -1, buffer)
                            .sendToTarget();
                } catch (IOException e) {
                    Log.e(TAG, "disconnected", e);
                    connectionLost();
                    break;
                }
            }
        }

1 个答案:

答案 0 :(得分:0)

好吧,现在mContext为null。你不是在任何地方分配任何东西。您可以更改构造函数签名以将其传递到:

public ConnectedThread(Context context, BluetoothSocket socket) {
    this.mContext = context;
    ...
}

如果您真的关注这个示例,那么您可以在BluetoothChatService中执行相同类型的操作...请注意,它们不会对传入的上下文执行任何操作。将该上下文存储在字段,ConnectedThread也可以访问。