Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android Build a Self-Destructing Message Android App Capturing Photos and Videos Selecting a Video from the Gallery

Sousheel Vunnam
Sousheel Vunnam
3,366 Points

Take Video is directing to gallery and toasting that file should be less than 10 mb.

Whenever I click on Take Video or Take Picture it directs me to gallery, like the choose picture. I couldn't find what was wrong with my code.

public class MyActivity extends FragmentActivity implements ActionBar.TabListener {

public static final String TAG = MyActivity.class.getSimpleName();

public static final int TAKE_PHOTO_REQUEST = 0;
public static final int TAKE_VIDEO_REQUEST = 1;
public static final int PICK_PHOTO_REQUEST = 2;
public static final int PICK_VIDEO_REQUEST = 3;

public static final int MEDIA_TYPE_IMAGE = 4;
public static final int MEDIA_TYPE_VIDEO = 5;

public static final int FILE_SIZE_LIMIT = 1024*1024*10;

protected Uri mMediaUri;

protected DialogInterface.OnClickListener mDialogListener = new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        switch (which) {
            case 0:
                //Take picture
                Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                mMediaUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
                if (mMediaUri == null) {
                    Toast.makeText(MyActivity.this, R.string.error_external_storage, Toast.LENGTH_LONG).show();
                }
                takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, mMediaUri);
                startActivityForResult(takePhotoIntent, TAKE_PHOTO_REQUEST);
            case 1:
                //Take Video
                Intent videoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
                mMediaUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
                if (mMediaUri == null) {
                    Toast.makeText(MyActivity.this, R.string.error_external_storage, Toast.LENGTH_LONG).show();
                }
                else {
                    videoIntent.putExtra(MediaStore.EXTRA_OUTPUT, mMediaUri);
                    videoIntent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 10);
                    videoIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
                    startActivityForResult(videoIntent, TAKE_VIDEO_REQUEST);
                }

            case 2:
                //Choose Picture
                Intent choosePhotoIntent = new Intent(Intent.ACTION_GET_CONTENT);
                choosePhotoIntent.setType("image/*");
                startActivityForResult(choosePhotoIntent, PICK_PHOTO_REQUEST);
            case 3:
                //Choose Video
                Intent chooseVideoIntent = new Intent(Intent.ACTION_GET_CONTENT);
                chooseVideoIntent.setType("video/*");
                Toast.makeText(MyActivity.this, R.string.video_file_size_warning, Toast.LENGTH_LONG).show();
                startActivityForResult(chooseVideoIntent, PICK_VIDEO_REQUEST);
        }
    }
};

private Uri getOutputMediaFileUri(int mediaType) {
    if(isExternalStorageAvailable()) {
        //get the URI

        //1. Get the external storage directory
        String appName = MyActivity.this.getString(R.string.app_name);
        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), appName);

        //2.Create our subdirectory
        if (!mediaStorageDir.exists()) {
            if(!mediaStorageDir.mkdirs()) {
                Log.e(TAG, "Failed to create directory");
                return null;
            }
        }

        //3. Create a file name
        File mediaFile;
        Date now = new Date();
        String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(now);
        String path = mediaStorageDir.getPath() + File.separator;

        //4. Create file
        if (mediaType == MEDIA_TYPE_IMAGE) {
            mediaFile = new File(path + "IMG_" + timestamp + ".jpg");
        }
        else if (mediaType == MEDIA_TYPE_VIDEO) {
            mediaFile = new File(path + "VID_" + timestamp + ".jpg");
        }
        else return null;

        Log.d(TAG, "File" + Uri.fromFile(mediaFile));

        //5. Return file URI
        return Uri.fromFile(mediaFile);
    }
    else {
        return null;
    }
}

private boolean isExternalStorageAvailable() {
    String state = Environment.getExternalStorageState();

    if(state.equals(Environment.MEDIA_MOUNTED)) {
        return true;
    }
    else {
        return false;
    }
}

/**
 * The {@link android.support.v4.view.PagerAdapter} that will provide
 * fragments for each of the sections. We use a
 * {@link FragmentPagerAdapter} derivative, which will keep every
 * loaded fragment in memory. If this becomes too memory intensive, it
 * may be best to switch to a
 * {@link android.support.v13.app.FragmentStatePagerAdapter}.
 */
SectionsPagerAdapter mSectionsPagerAdapter;

/**
 * The {@link ViewPager} that will host the section contents.
 */
ViewPager mViewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    setContentView(R.layout.activity_my);

    ParseUser currentUser = ParseUser.getCurrentUser();
    if (currentUser == null) {
        navigateToLogin();
    }
    else {

        Log.i(TAG, currentUser.getUsername());
    }

    // Set up the action bar.
    final ActionBar actionBar = getActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    // When swiping between different sections, select the corresponding
    // tab. We can also use ActionBar.Tab#select() to do this if we have
    // a reference to the Tab.
    mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            actionBar.setSelectedNavigationItem(position);
        }
    });

    // For each of the sections in the app, add a tab to the action bar.
    for (int i = 0; i <mSectionsPagerAdapter.getCount(); i++) {
        // Create a tab with text corresponding to the page title defined by
        // the adapter. Also specify this Activity object, which implements
        // the TabListener interface, as the callback (listener) for when
        // this tab is selected.
        actionBar.addTab(
                actionBar.newTab()
                        .setText(mSectionsPagerAdapter.getPageTitle(i))
                        .setTabListener(this));
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode == RESULT_OK) {
        //add to gallery

        if (requestCode == PICK_PHOTO_REQUEST || requestCode == PICK_VIDEO_REQUEST) {
            if (data == null) {
                Toast.makeText(this, getString(R.string.general_error), Toast.LENGTH_LONG);
            }
            else mMediaUri= data.getData();

            Log.i(TAG, "Media Uri: " + mMediaUri);
            if (requestCode == PICK_VIDEO_REQUEST) {
                //make sure file is less than 10 MB
                int filesize = 0;

                InputStream inputStream = null;
                try {
                    inputStream = getContentResolver().openInputStream(mMediaUri);
                    filesize = inputStream.available();
                } catch (FileNotFoundException e) {
                    Toast.makeText(this, getString(R.string.general_error), Toast.LENGTH_LONG);
                    return;
                }
                 catch (IOException e){
                    Toast.makeText(this, getString(R.string.general_error), Toast.LENGTH_LONG);
                     return;
                }
                finally {
                    try {
                        inputStream.close();
                    } catch (IOException e) {/*blank*/}
                }
                if (filesize>= FILE_SIZE_LIMIT) {
                    Toast.makeText(this, "The selected file is too large. Selet a new file", Toast.LENGTH_LONG);
                    return;
                }
            }
        }
        else {
            Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            mediaScanIntent.setData(mMediaUri);
            sendBroadcast(mediaScanIntent);
        }
    }
    else if (resultCode != RESULT_CANCELED) {
        Toast.makeText(this, R.string.general_error, Toast.LENGTH_LONG).show();
    }
}

}

1 Answer

You forgot your "break;" after each case in the switch.