title: java.lang.IllegalStateException When Stopping MediaRecorder
body: <p>I know this question has been asked a lot but none have solved my problem. The mediaRecorder works perfectly when its recording audio but when the button is pressed to stop it, it throws <code>java.lang.IllegalStateException</code>. Thank you in advance.
  Here is the code:</p>
  
  <pre><code>File rootPath = new File(Environment.getExternalStorageDirectory(), "Recording");
      if(!rootPath.exists()) {
          rootPath.mkdirs();
      }
  
      buttonStart = (ImageButton) findViewById(R.id.RecordingButton);
      buttonStop = (Button) findViewById(R.id.StopRecordingButton);
  
      buttonStart.setEnabled(true);
      buttonStop.setEnabled(false);
  
      buttonStart.setOnClickListener(new View.OnClickListener() {
                  @Override
                  public void onClick(View view) {
  
              if(checkPermission()) {
                  datetimeLog = DateString();
                  AudioSavePathInDevice = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Recording/" + datetimeLog + "_AudioRecording.3gp";
                  try {
                      mediaRecorder=new MediaRecorder();
                      mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                      mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
                      mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
                      mediaRecorder.setOutputFile(AudioSavePathInDevice);
                      mediaRecorder.prepare();
                      mediaRecorder.start();
                  } catch (IllegalStateException e) {
                      e.printStackTrace();
                  } catch (IOException e) {
                      e.printStackTrace();
                  }
  
                  buttonStart.setEnabled(false);
                  buttonStop.setEnabled(true);
  
                  Toast.makeText(MainActivity.this, "Recording Started...", Toast.LENGTH_LONG).show();
              } else {
                  requestPermission();
              }
          }
      });
  
      buttonStop.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View view) {
              System.out.println(mediaRecorder);
              mediaRecorder.stop();
              //mediaRecorder.reset();
              mediaRecorder.release();
              mediaRecorder = null;
              buttonStart.setEnabled(true);
              buttonStop.setEnabled(false);
              Toast.makeText(MainActivity.this, "Recording Stopped", Toast.LENGTH_LONG).show();
              showAddItemDialog(MainActivity.this);
          }
      });
  }
  
  private String DateString() {
      Date c = Calendar.getInstance().getTime();
      SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy-h-m-s");
      String formattedDate = df.format(c);
      return formattedDate;
  }
  
  private void showAddItemDialog(final Context c) {
      final EditText taskEditText = new EditText(c);
      AlertDialog dialog = new AlertDialog.Builder(c)
              .setTitle("Save Recording as?")
              .setMessage("Name of Audio Recording (Make this a short)")
              .setView(taskEditText)
              .setPositiveButton("Save", new DialogInterface.OnClickListener() {
                  @Override
                  public void onClick(DialogInterface dialog, int which) {
                      logName = taskEditText.getText().toString().replaceAll("\n","");
                      //AudioSavePathInDevice
                      //datetimeLog
                      //save to file
                      String toWrite = logName + "," + AudioSavePathInDevice + "," + datetimeLog + "\n";
                      myFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Recording/Logs.txt");
                      try {
                          buff = new BufferedWriter ( new FileWriter ( myFile,true));
                          buff.append(toWrite);
                          buff.close();
                      } catch (IOException e) {
                          e.printStackTrace();
                      }
                  }
              }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                  @Override
                  public void onClick(DialogInterface dialog, int which) {
                      File file = new File(AudioSavePathInDevice);
                      boolean deletedfile = file.delete();
                  }
              }).create();
      dialog.show();
  }
  
  private void requestPermission() {
      ActivityCompat.requestPermissions(MainActivity.this, new
              String[]{WRITE_EXTERNAL_STORAGE, RECORD_AUDIO, WAKE_LOCK}, RequestPermissionCode);
  }
  
  @Override
  public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
      switch (requestCode) {
          case RequestPermissionCode:
              if (grantResults.length&gt; 0) {
                  boolean StoragePermission = grantResults[0] ==
                          PackageManager.PERMISSION_GRANTED;
                  boolean RecordPermission = grantResults[1] ==
                          PackageManager.PERMISSION_GRANTED;
  
                  if (StoragePermission &amp;&amp; RecordPermission) {
                      Toast.makeText(MainActivity.this, "Permission Granted",
                              Toast.LENGTH_LONG).show();
                  } else {
                      Toast.makeText(MainActivity.this,"Permission Denied",Toast.LENGTH_LONG).show();
                  }
              }
              break;
      }
  }
  
  public boolean checkPermission() {
      int result = ContextCompat.checkSelfPermission(getApplicationContext(), WRITE_EXTERNAL_STORAGE);
      int result1 = ContextCompat.checkSelfPermission(getApplicationContext(), RECORD_AUDIO);
      int result2 = ContextCompat.checkSelfPermission(getApplicationContext(), WAKE_LOCK);
      return result == PackageManager.PERMISSION_GRANTED &amp;&amp;
              result1 == PackageManager.PERMISSION_GRANTED &amp;&amp; result2 == PackageManager.PERMISSION_GRANTED;
  }
  </code></pre>
  
  <p>}</p>
  
  <pre><code>&lt;uses-permission android:name="android.permission.RECORD_AUDIO" /&gt;
  &lt;uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /&gt;
  &lt;uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /&gt;
  &lt;uses-permission android:name="android.permission.WAKE_LOCK" /&gt;
  </code></pre>
  
  <p>Here is the error message:</p>
  
  <pre><code>E/MediaRecorder: stop called in an invalid state: 4
  D/AndroidRuntime: Shutting down VM
  E/AndroidRuntime: FATAL EXCEPTION: main
  Process: com.ee.project, PID: 29167
  java.lang.IllegalStateException
      at android.media.MediaRecorder.stop(Native Method)
      at com.example.project.MainActivity$2.onClick(MainActivity.java:114)
      at android.view.View.performClick(View.java:7125)
      at android.view.View.performClickInternal(View.java:7102)
      at android.view.View.access$3500(View.java:801)
      at android.view.View$PerformClick.run(View.java:27336)
      at android.os.Handler.handleCallback(Handler.java:883)
      at android.os.Handler.dispatchMessage(Handler.java:100)
      at android.os.Looper.loop(Looper.java:214)
      at android.app.ActivityThread.main(ActivityThread.java:7356)
      at java.lang.reflect.Method.invoke(Native Method)
      at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
  </code></pre>