Android: NullPointerException 使用 getCacheDir()

Android: NullPointerException using getCacheDir()

我正在构建一个允许用户录制和上传 <30 秒声音的应用程序,我正在尝试找出一种方法将声音临时存储在设备上(以便用户可以查看它,等),直到它被上传到服务器。我认为对文件路径使用 getCacheDir() 应该是解决方案,但无论我尝试哪种形式,我都会不断收到 NPE。其他人已经 运行 解决了这个问题,并在 SO 上询问了它,但从未真正得到满意的答案或解决方法。有关如何修复它或替代临时存储方法的任何建议?我的应用程序的最低 SDK 为 Android 2.0,因此我无法使用 getExternalCacheDir()。

对于上下文,这是我的声明:

Context context;    
private String fileName = context.getCacheDir().getAbsolutePath() + "/wavesaudio/" + "temp" +".3gp";

和用法:

public void startRecording() {
        mRecorder = new MediaRecorder();
        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        mRecorder.setOutputFile(fileName);
        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        recordTime = 0;

播放的用法类似。我收到的错误消息说这是一个 NPE,并指向声明 fileName 字符串的确切行。

谢谢!

您正在尝试使用 context,然后才给它赋值。

您应该在 Activity.onCreate() 方法中对 filename 进行赋值,如:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    context = this; // "context" may not be needed

    // Note: you don't need to use "context" here, since the Activity is itself a Context.
    fileName = getCacheDir().getAbsolutePath() + "/wavesaudio/" + "temp" +".3gp";

    // Rest of your onCreate() code ...
}

您必须在 activity 的 onCreate() 中分配您的文件名。

public class MainActivity extends Activity {
  private String fileName;
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    fileName = getApplicationContext().getCacheDir().getAbsolutePath() + "/wavesaudio/" + "temp" +".3gp";