2012-02-05 2 views
0

BluetoothChatService 클래스 내에서 openFileOutput을 사용하여 InputStream을 파일에 저장하기 위해 Android BluetoothChat 예제를 조정하려고합니다. Environment.getExternalStorageDirectory를 사용하고 filewriter를 사용하여 sdcard에 저장할 때 문제는 없지만 MODE_PRIVATE와 함께 openFileOutput 메소드를 사용하면 몇 가지 다른 질문/답변에서 언급 한 것처럼 nullPointerException을 반환합니다. 나는 내 삶에 대해 정확한 문맥을 얻는 정확한 방법을 찾아 낼 수 없다.openFileOutput을 사용할 때 내부 클래스에서 컨텍스트를 올바르게 사용합니까?

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; 
       } 
      } 
     } 

답변

0

글쎄, 지금은 mContext가 null입니다. 어디에도 아무 것도 지정하지 않은 것입니다. 그들은으로 아무것도하지 않는 점에 유의 ... 당신이 실제로 예를 들어 다음과 같은 경우

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

, 당신은 BluetoothChatService에서 물건의 동일한 유형을 할 수있는 : 당신은 그것을 전달하는 생성자 서명을 변경할 수 있습니다 전달 된 컨텍스트. 해당 컨텍스트를 필드에 저장하고 ConnectedThread에도 액세스 할 수 있습니다.

+1

이런 식으로 컨텍스트에 대한 참조를 유지하면 누출 될 수 있습니다. –

+0

이 것은 적어도 소멸자가 필요합니다. 디스플레이 관련 코드가 없으므로 애플리케이션 컨텍스트에 대한 참조를 얻는 것이 더 나은 접근 방법이라고 생각합니다. –

관련 문제