how to view video in activity that is chosen from the gallery - android

I am implementing video uploading functionality in an android application.I can choose a video from gallery but I can not view it in my activity.I dont know how to put a video from gallery to videoview of an activity
My code to select video from gallery is :
mChoose.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("video/*");
startActivityForResult(intent, REQUEST_ID);
}
});
onActivityResult Method code
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
InputStream stream = null;
if(requestCode == REQUEST_ID && resultCode == Activity.RESULT_OK)
{
try
{
stream = getContentResolver().openInputStream(data.getData());
//System.out.println(data.getData());
mVideo.setVideoPath(path);
path = getRealPathFromURI(getApplicationContext(), data.getData());
//getRealPathFromURI is method in class to obtain path from uri
System.out.println(path);
}
catch(Exception ex)
{
ex.printStackTrace();
}
if(stream != null)
{
try
{
stream.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
}

Use this Code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mVideo = (VideoView) findViewById(R.id.videoView);
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("video/*");
startActivityForResult(intent, 1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(requestCode == 1 && resultCode == Activity.RESULT_OK)
{
try
{
String path = data.getData().toString();
mVideo.setVideoPath(path);
mVideo.requestFocus();
mVideo.start();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}

VideoView videoView = (VideoView) findViewById(R.id.videoview);
Uri vidFile = Uri.parse(Environment.getExternalStorageDirectory()
.getAbsolutePath() + "path of the video");
videoView.setVideoURI(vidFile);
videoView
.setMediaController(new MediaController(PlayVideoActivity.this));
videoView.setVisibility(1);
videoView.bringToFront();
videoView.requestFocus();

Related

Select an mp3 file from SD card

I need to ask the user to select a media file from his SD card for playing. The following code doesn't work:
edit:
after I choose a mp3 file from the sd card folder I can't start him (play him). I think that the problem is that it doesn't entering to the "onActivityResult" function.
Intent i = new Intent();
i.setType("audio/*");
i.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(i, RESULT_OK);
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode==RESULT_OK)
{
Uri uri =data.getData();
if(uri!=null) {
try {
song.setDataSource(getApplicationContext(), uri);
song.prepare();
pl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
song.start();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
super.onActivityResult(CONTEXT_RESTRICTED, RESULT_OK, data);
}
}
Your question doesn't include definitions of some variables so I added my own and it played. Try this:-
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
Intent i = new Intent();
i.setType("audio/*");
i.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(i, 1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
Uri uri = data.getData();
if (uri != null) {
try {
MediaPlayer song = new MediaPlayer();
song.setDataSource(getApplicationContext(), uri);
song.prepare();
song.start();
} catch (Exception e) {
}
}
super.onActivityResult(CONTEXT_RESTRICTED, RESULT_OK, data);
}
}
MediaPlayer Docs here

Video file taken from Android device not playing in app

I am trying to attach video file in my app. I tried the following code to get video from Android device. After attaching the video, if I try to play it using the MediaController class, the screen becomes blank. Please help me with this.
void pickVideo() {
Intent videoIntent = new Intent(Intent.ACTION_GET_CONTENT);
videoIntent.setType("video/*");
startActivityForResult(videoIntent, PICK_VIDEO_FILE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (resultCode != Activity.RESULT_OK)
return;
switch (requestCode) {
case PICK_VIDEO_FILE:
Uri videoUri = data.getData();
if (mChooseFileDialogListener != null) {
mChooseFileDialogListener.onVideoClick(videoUri, ViewModel.FILE_TYPE_VIDEO);
}
break;
}
}
ChooseFileDialogFragment.ChooseFileDialogListener mChooseFileDialogListener = new ChooseFileDialogFragment.ChooseFileDialogListener() {
#Override
public void onVideoClick(Uri videoUri, int fileType) {
mPath = videoUri.toString();
}
}
AttachmentAdapter.ItemClickListener = new AttachmentAdapter.ItemClickListener() {
#Override
public void onClick(String path) {
playVideo(path);
}
}
private void playVideo(String path) {
MediaController mediaControls = new MediaController(getActivity());
try {
//set the media controller in the VideoView
mBinding.videoPlayer.setMediaController(mediaControls);
//set the uri of the video to be played
if (file != null) {
mBinding.videoPlayer.setVideoPath(path);
}
} catch (Exception e) {
e.printStackTrace();
}
}

Video recording using Intent saves empty file

This is the code i used to record video from an android device in MP4 format. The file is being created but is of 0 bytes size.
Here is my code :-
Button buttonStart;
File newFile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initUI();
buttonStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
newFile = File.createTempFile("vid", ".mp4", Environment.getExternalStorageDirectory());
} catch (IOException e) {
e.printStackTrace();
}
Uri outputFileUri = Uri.fromFile(newFile);
Intent record = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
record.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(record, 5);
}
});
}
protected void initUI(){
buttonStart = (Button) findViewById(R.id.buttonRecord);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == 5){
if(resultCode == RESULT_OK){
try {
newFile = File.createTempFile("vid", ".mp4", Environment.getExternalStorageDirectory());
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(this, "Video Captured Successfully...!!", Toast.LENGTH_LONG).show();
}
}
}
I don't understand what has gone wrong.
Can anybody help me ...
Thanks
String strVideoPath=null;//define global variable
to open an Intetn for video recording
void displayCamera() {
File imagesFolder = new File(Environment
.getExternalStorageDirectory(), getResources()
.getString(R.string.app_name) + "foldername");
try {
imagesFolder.mkdirs();
} catch (Exception e) {
}
File f_image = new File(imagesFolder, new Date().getTime() + ".mp4");
Uri uriSavedVideo = Uri.fromFile(f_image);
Intent intent = new Intent(
MediaStore.ACTION_VIDEO_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedVideo);
strVideoPath = f_image.getAbsolutePath();
try {
startActivityForResult(intent, 111);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
}
catch it on OnActivity Result
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 111) {
if (resultCode == mActivity.RESULT_OK) {
//do stuff here on success
}else{
strVideoPath=null;
}
}
}
first u need to create a directory
File newFileLocation;
try {
newFileLocation = new File(Environment.getExternalStorageDirectory(), "videoyo");
imagesFolder.mkdirs();
newFile = new File(newFileLocation , "vid" + ".mp4");
} catch (Exception e) {
}

onActivityResult not working after taken photo in Moto G

private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
intent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST);
}
/*
* Here we store the file url as it will be null after returning from camera
* app
*/
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on scren orientation
// changes
outState.putParcelable("file_uri", fileUri);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// get the file url
fileUri = savedInstanceState.getParcelable("file_uri");
}
/*
* Recording video
*/
/**
* Receiving activity result method will be called after closing the camera
* */
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST)
{
if (resultCode == RESULT_OK)
{
// successfully captured the image
// display it in image view
this.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
previewCapturedImage();
}
});
}
else if (resultCode == RESULT_CANCELED)
{
// user cancelled Image capture
Toast.makeText(getApplicationContext(),"User cancelled image capture", Toast.LENGTH_SHORT).show();
}
else
{
// failed to capture image
Toast.makeText(getApplicationContext(),"Sorry! Failed to capture image", Toast.LENGTH_SHORT).show();
}
}
}
this code is working on Google Nexus 4.4.4, but this same code is not working on Moto G 4.4.4.
I also used debugger but in the Moto G onActivityResult is not called.
Use this code:
ImageView profile=(ImageView)findviewById(R.id.imageview);
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, code);
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == code) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
try {
bmp = BitmapFactory.decodeStream(getContentResolver()
.openInputStream(selectedImage));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
profile.setImageBitmap(bmp);
}
}
}
For working on all devices you don't have to put Extra in intent, and you need to get the path of image inside OnActivityResult method, Example:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode==CAMERA_REQUEST) {
if (resultCode == RESULT_OK) {
if (data.hasExtra("data")) {
// retrieve the bitmap from the intent
bitmap = (Bitmap) data.getExtras().get("data");
Cursor cursor = getActivity().getContentResolver().query(Media.EXTERNAL_CONTENT_URI,new String[] {
Media.DATA,
Media.DATE_ADDED,
MediaStore.Images.ImageColumns.ORIENTATION },
Media.DATE_ADDED, null, "date_added ASC");
if (cursor != null && cursor.moveToFirst()) {
do {
Uri uri = Uri.parse(cursor.getString(cursor.getColumnIndex(Media.DATA)));
selectedImagePath = uri.toString();
} while (cursor.moveToNext());
cursor.close();
}
Log.e("path of the image from camera ====> ",selectedImagePath);
public void callCamera() {
//access to camara
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}

android code to select audio mp3 and play it

I am developing an application,in which user will select a single audio file and play the audio.
Then I will pass the audio to the next activity.
Here is my code it select the audio but it gives error setDataSource Failed:Status=0X80000000 kindly guide me what should I do
switch(v.getId())
{
case R.id.btnmusic:
/*Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
File file = new File("file:///sdcard/Music");
intent.setDataAndType(Uri.fromFile(file), "audio/*");*/
Intent pickMedia = new Intent(Intent.ACTION_GET_CONTENT);
pickMedia.setType("audio/*");
startActivityForResult(pickMedia,1);
break;
protected void onActivityResult(int RequestCode,int ResultCode,Intent data)
{
if(RequestCode==1)
{
if(data != null)
{
Uri muri=data.getData();
String uri=muri.getPath();
File track=new File(uri);
if(uri != null)
{
Uri urinew = MediaStore.Audio.Media.getContentUriForPath(track.getAbsolutePath());
//Toast.makeText(this, uri, Toast.LENGTH_SHORT).show();
MediaPlayer md=new MediaPlayer();
try{
md.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
md.setDataSource(AudioSelect.this, urinew);
md.prepare();
md.start();
}
catch(Exception e)
{
e.printStackTrace();
displayExceptionMessage(e.getMessage());
}
}
else
{
Toast.makeText(this, "No Image Data Recieved", Toast.LENGTH_SHORT).show();
}
}
}
}
1: Use Intent to choose audio file from sd card:
Intent audioIntent = new Intent();
audioIntent.setType("audio/*");
audioIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(audioIntent,PICK_AUDIO_REQUEST);
2: Handle the result in OnActivityResult
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != RESULT_OK || data == null || data.getData() == null) {
// error
return;
}
if (requestCode == PICK_AUDIO_REQUEST) {
try {
Uri uri= data.getData();
String path = getRealPathFromURI(uri);
// play audio file using MediaPlayer
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(path);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Note: getRealPathFromURI is a utility method :
private String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
CursorLoader loader = new CursorLoader(getContext(), contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;
}
md = MediaPlayer.create(this, Uri.parse(track.getAbsolutePath()));
but i want to send this muri to next activity so i can play the song in next activity.please guide me how can i do this.
protected void onActivityResult(int RequestCode,int ResultCode,Intent data)
{
if(RequestCode==1)
{
if(data != null)
{
Uri muri=data.getData();
Intent intent = new Intent(this,NextActivity.class);
intent.putExtra("uriToPlay",muri);
startActivity(intent);
}
else
{
Toast.makeText(this, "No Image Data Recieved",
Toast.LENGTH_SHORT).show();
}
}
}
Rest of the code (like Media player) in the next Activity.

Categories

Resources