Question

So I have this very Spartan-looking app based on code from this wesbite

enter image description here

The purpose of it, is when the user hits the record button, it will prompt him or her for the name of the file, then record the sound. The user can record as many sounds as he or she will like until they go back to the main menu.

However, when I first launch the program, nothing will happen when I hit the record button. When I hit it a second time, it will start recording during the name prompt.

What is the issue here? In the code, I suspect the problem is that I initialize the string variable that holds the filename as null, but I did that in the event that the user hit cancel, so the program wouldn't record the sound into a sound file named null. The user gave it a name the first time he tried to fire up the program, shouldn't the null check pass?

Also, shouldn't the program wait until the name is set before firing up the recorder, per my code?

The code:

import java.io.IOException;


import android.media.MediaRecorder;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class RecordASound extends Activity {


    Button start;
    Button stop;
    Button mainMenu;
    private MediaRecorder myRecorder;
    private String outputFile = null;
    private String value = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_record_asound);



        start = (Button)findViewById(R.id.Record);
        start.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                startRecord(v);
            }
          });

          stop = (Button)findViewById(R.id.StopRecord);
          stop.setEnabled(false);
          stop.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                stopRecord(v);
            }
          });

          mainMenu = (Button)findViewById(R.id.MainMenu);
          mainMenu.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                    mainMenu(v);    
            }
          });


        // Make sure we're running on Honeycomb or higher to use ActionBar APIs
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            // For the main activity, make sure the app icon in the action bar
            // does not behave as a button
            ActionBar actionBar = getActionBar();
            actionBar.setHomeButtonEnabled(false);
        }//end if

    }//end onCreate

    public void startRecord(View view){

        AlertDialog.Builder alert = new AlertDialog.Builder(this);

        alert.setTitle("Name of Sound File");
        alert.setMessage("Please give your sound file a name.");

        // Set an EditText view to get user input 
        final EditText input = new EditText(this);
        alert.setView(input);

        alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
         value = input.getText().toString();

          }
        });

        alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int whichButton) {
              value = null;

          }
        });

        alert.show();

            //if the user hit cancel on the prompt, back out of the recorder
        if (value == null){
            return;
        }//end if
        else{
            outputFile = Environment.getExternalStorageDirectory().
                    getAbsolutePath() + "/" +  value + ".3gpp";

            myRecorder = new MediaRecorder();
            myRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            myRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
            myRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
            myRecorder.setOutputFile(outputFile);


            try {
                  myRecorder.prepare();
                  myRecorder.start();
         } catch (IllegalStateException e) {
                  // start:it is called before prepare()
                  // prepare: it is called after start() or before setOutputFormat()
                          e.printStackTrace();
                     } catch (IOException e) {
             // prepare() fails
                   e.printStackTrace();
                }

               start.setEnabled(false);
               stop.setEnabled(true);

               Toast.makeText(getApplicationContext(), "Start recording...",
                               Toast.LENGTH_SHORT).show();

        }//end else



    }//end startRecord

    public void stopRecord(View view){
        try { // TODO Auto-generated method stub
            myRecorder.stop();
            myRecorder.release();

            myRecorder = null;

            stop.setEnabled(false);
            start.setEnabled(true);

            Toast.makeText(getApplicationContext(), "Stop recording...",
                    Toast.LENGTH_SHORT).show();
        } catch (IllegalStateException e) {

            e.printStackTrace();
        } catch (RuntimeException e){
            //no valid audio/video data was collected
            e.printStackTrace();

        }//end catch

    }//end stopRecord

    public void mainMenu(View view){

        startActivity(new Intent(RecordASound.this, MainActivity.class));

    }//end mainMenu 


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.record_asound, menu);
        return true;
    }//end onCreateOptionsMenu

}//end class
Was it helpful?

Solution

Put the code inside setPositiveButton instead of having a check after AlertDialog is shown as Dialogs in Android are asynchronous.

OTHER TIPS

May be your record button have android:focusableInTouchMode="true"?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top