Proper use of context within inner class when using openFileOutput?

pottheoto

New Member
I am trying to adapt the Android BluetoothChat example to save the InputStream to file using openFileOutput from within the BluetoothChatService class. When using the Environment.getExternalStorageDirectory and saving to the sdcard using filewriter there is no problem, but using the openFileOutput method with MODE_PRIVATE returns a nullPointerException as mentioned in several other questions/answers. I cant for the life of me figure out the correct way to get the correct context. \[code\] 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; } } }\[/code\]
 
Top