How to get pdf and doc files using Media.Files - android

Right Now I am getting my files using a particular piece of code which is working fine but in some of cell phones where there is no software like google drive I am getting message like no application installed for request. So I have searched and found that We can get files using Media.Files but not enough documentation is present to carry out the task.
Code:
warantyButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("application/pdf,application/msword");
Intent i = Intent.createChooser(intent, "File");
getActivity().startActivityForResult(i, FILE_REQ_CODE);
//Toast.makeText(getContext(),"Files",Toast.LENGTH_SHORT).show();
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == FILE_REQ_CODE) {
if (resultCode == RESULT_OK) {
String path="";
Uri uri = data.getData();
if (uri != null) {
try {
file = new File(getPath(getContext(),uri));
if(file!=null){
ext = getMimeType(uri);
sendFileToServer(file,ext);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
public static String getPath(Context context, Uri uri) throws URISyntaxException {
if ("content".equalsIgnoreCase(uri.getScheme())) {
String[] projection = { "_data" };
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow("_data");
if (cursor.moveToFirst()) {
return cursor.getString(column_index);
}
} catch (Exception e) {
// Eat it
}
}
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}

Related

Get the user selected file's name and path irrespective of its location [ either in internal or external memory ] in Android?

Instead of the hard coded storage location in the code below, I would like to get the [name & path] of any Excelsheet that user selects, for data import operation. Found that getExternalStorageDirectory is deprecated, not sure how to achieve the requirement for accessing Excelfile from both Internal / External storage of Android.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data == null)
return;
switch (requestCode) {
case imrequestcode:
// Need help at this LOC where filepath could be user selected one.
String FilePath = "/mnt/sdcard/" + "sampleinput.xls";
try {
if (resultCode == RESULT_OK) {
//// Import function goes here
}
} catch (Exception ex) {
lbl.setText("Error " + e);
}
break;
}
}
Intent : Pick an excel sheet which has inputdata
bimport.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent fileintent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
fileintent.addCategory(Intent.CATEGORY_OPENABLE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_LOCATION_ACCESS);
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
MY_PERMISSIONS_READ_EXTERNAL_STORAGE);
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE);
}
fileintent.setType("application/vnd.ms-excel");
try {
startActivityForResult(fileintent, importrequestcode);
fileintent.addFlags(FLAG_GRANT_READ_URI_PERMISSION);
if (Build.VERSION.SDK_INT > 22) {
requestPermissions(new String[]{"FLAG_GRANT_READ_URI_PERMISSION"}, 11);
}
} catch (ActivityNotFoundException e) {
lbl.setText("No file picker activity.");
}
}
});
}
To get the Filename:
private String getFileName(Uri uri) {
Cursor mCursor =
getApplicationContext().getContentResolver().query(uri, null, null, null, null);
int indexedname = mCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
mCursor.moveToFirst();
String filename = mCursor.getString(indexedname);
mCursor.close();
return filename;
}
To get the FilePath:
[Checkthislink](https://stackoverflow.com/questions/13209494/how-to-get-the-full-file-path-from-uri/55469368#55469368)
Call the method and class in onActivityResult:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data == null)
return;
switch (requestCode) {
case imrequestcode:
Uri fileuri = data.getData();
String Nameoffile_selected = getFileName(fileuri);
String Pathoffile_selected = FileUtils.getPath(this, fileuri);
try {
if (resultCode == RESULT_OK) {
//// Import function goes here
}
} catch (Exception ex) {
lbl.setText("Error " + e);
}
break;
}
}

java illegal Argument Exception: inputFile Does not Exists

I am Developing a that takes a video from Storage via intent. So i am Facing this problem
Problem:-
java.lang.illegalArgumentException:inputFile not exists:/document/video:105065
Code:-
Intent
public void videotext( View v ) {
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.setType("video/*");
startActivityForResult(i, request);
}
On Activity Result
#Override
protected void onActivityResult( int requestCode, int resultCode, Intent data ) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == request) {
uri = data.getData();
mSurfaceView.setVideoURI(uri);
//MediaController media1=new MediaController(this);
media.setAnchorView(mSurfaceView);
mSurfaceView.setMediaController(media);
mSurfaceView.start();
inputFile=new File(uri.getPath());
inputFile=inputFile.getAbsoluteFile();
VideoCompress(inputFile,OutputFile);
}
}
}
VideoCompress is a method to Compress video..
public void VideoCompress(File inputFile,File OutputFile)
{
GiraffeCompressor.create() //two implementations: mediacodec and ffmpeg,default is mediacodec
.input(inputFile) //set video to be compressed
.output(OutputFile) //set compressed video output
.bitRate(2073600)//set bitrate 码率
.resizeFactor(Float.parseFloat(String.valueOf(1.0)))//set video resize factor 分辨率缩放,默认保持原分辨率
// .watermark("/sdcard/videoCompressor/watermarker.png")//add watermark(take a long time) 水印图片(需要长时间处理)
.ready()
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<GiraffeCompressor.Result>() {
#Override
public void onCompleted() {
Toast.makeText(UploadVideo.this,"Compressing",Toast.LENGTH_LONG).show();
}
#Override
public void onError(Throwable e) {
Toast.makeText(UploadVideo.this,e.toString(),Toast.LENGTH_LONG).show();
}
#Override
public void onNext(GiraffeCompressor.Result s) {
Toast.makeText(UploadVideo.this,"Compressed",Toast.LENGTH_LONG).show();
}
});
}
Use this Method to get Path for your Uri :
public static String getPath(Context context,Uri uri) {
Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
use it like mSurfaceView.setVideoURI(data.getData());

How to get image from gallery in android marshmallow?

Hi i am working in app were user can select image when he is registering an account. I am able to get image on lollipop but when i am testing it in marshmallow then i am not getting file and its name, I am able to ask permission from user and when i am selecting image from gallery i am not getting any file or its name
This is my Code
select_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(Build.VERSION.SDK_INT >=23) {
if (checkPermission()){
Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
}else{
requestPermission();
}
}else{
Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
}
}
});
My Permissions
private boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(Register.this, Manifest.permission.READ_EXTERNAL_STORAGE );
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
private void requestPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(Register.this, android.Manifest.permission.READ_EXTERNAL_STORAGE)) {
Toast.makeText(Register.this, "Write External Storage permission allows us to access images. Please allow this permission in App Settings.", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(Register.this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[], #NonNull int[] grantResults) {
if(requestCode == PERMISSION_REQUEST_CODE){
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Accepted", Toast.LENGTH_SHORT).show();
Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
} else {
Log.e("value", "Permission Denied, You cannot use local drive .");
}
}
}
After Selecting Image
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
filePath = data.getData();
if (null != filePath) {
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), filePath);
// img.setImageBitmap(bitmap);
if (filePath.getScheme().equals("content")) {
try (Cursor cursor = getContentResolver().query(filePath, null, null, null, null)) {
if (cursor != null && cursor.moveToFirst()) {
file_name = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
Toast.makeText(this, file_name, Toast.LENGTH_SHORT).show();
img_name.setText(file_name);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
I am not getting why its not working in marshmallow even i have given permissions
I solved it.
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
filePath = data.getData();
if (null != filePath) {
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), filePath);
// img.setImageBitmap(bitmap);
if (filePath.getScheme().equals("content")) {
try (Cursor cursor = getContentResolver().query(filePath, null, null, null, null)) {
if (cursor != null && cursor.moveToFirst()) {
file_name = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
Toast.makeText(this, file_name, Toast.LENGTH_SHORT).show();
img_name.setText(file_name);
}
}
}else {
String path= data.getData().getPath();
file_name=path.substring(path.lastIndexOf("/")+1);
img_name.setText(file_name);
Toast.makeText(this, file_name, Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
When i was selecting file , then i was not going to this condition
if (filePath.getScheme().equals("content"))
so in else condition i have given this
String path= data.getData().getPath();
file_name=path.substring(path.lastIndexOf("/")+1);
img_name.setText(file_name);
Toast.makeText(this, file_name, Toast.LENGTH_SHORT).show();
To get image from gallery on any api level then follow this :
Copy and paste all 4 function to your activity
And call this to open gallery galleryPermissionDialog();
Variable used
final private int REQUEST_CODE_ASK_PERMISSIONS = 123;
protected static final int REQUEST_CODE_MANUAL = 5;
Permission need to add for lower than marshmallow
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Function 1:
void openGallry() {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1);
}
Function 2 :
void galleryPermissionDialog() {
int hasWriteContactsPermission = ContextCompat.checkSelfPermission(ActivityProfile.this,
android.Manifest.permission.READ_EXTERNAL_STORAGE);
if (hasWriteContactsPermission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(ActivityProfile.this,
new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_CODE_ASK_PERMISSIONS);
return;
} else {
openGallry();
}
}
Function 3 :
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_ASK_PERMISSIONS: {
Map<String, Integer> perms = new HashMap<String, Integer>();
// Initial
perms.put(android.Manifest.permission.READ_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
// Fill with results
for (int i = 0; i < permissions.length; i++)
perms.put(permissions[i], grantResults[i]);
// Check for READ_EXTERNAL_STORAGE
boolean showRationale = false;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
if (perms.get(android.Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
// All Permissions Granted
galleryPermissionDialog();
} else {
showRationale = ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.READ_EXTERNAL_STORAGE);
if (showRationale) {
showMessageOKCancel("Read Storage Permission required for this app ",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
galleryPermissionDialog();
}
});
} else {
showMessageOKCancel("Read Storage Permission required for this app ",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(ActivityProfile.this, "Please Enable the Read Storage permission in permission", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivityForResult(intent, REQUEST_CODE_MANUAL);
}
});
//proceed with logic by disabling the related features or quit the app.
}
}
} else {
galleryPermissionDialog();
}
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
Function 4 :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case 1:
if (resultCode == RESULT_OK) {
try {
final Uri imageUri = imageReturnedIntent.getData();
/* final InputStream imageStream = getContentResolver().openInputStream(imageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
img_profile.setImageBitmap(selectedImage);*/
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(imageUri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
pictureFile = saveBitmapToFile(new File(picturePath));
Picasso.with(getApplicationContext()).load(new File(picturePath)).transform(new CircleTransform()).into(imgProfile);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Function 5 :
public void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
new AlertDialog.Builder(ActivityProfile.this)
.setTitle(R.string.app_name)
.setMessage(message)
.setCancelable(false)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", null)
.create()
.show();
}
file/* is not a valid MIME type. You should use / if you want to support any type of file. The files you see are unselectable because they are not of the correct MIME type.
With the introduction of virtual files in Android 7.0 (files that don't have a bytestream and therefore cannot be directly uploaded), you should most definitely add CATEGORY_OPENABLE to your Intent:
https://developer.android.com/about/versions/nougat/android-7.0.html#virtual_files
https://developer.android.com/reference/android/content/Intent.html#CATEGORY_OPENABLE
private void showFileChooser() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//sets the select file to all types of files
intent.setType("*/*");
// Only get openable files
intent.addCategory(Intent.CATEGORY_OPENABLE);
//starts new activity to select file and return data
startActivityForResult(Intent.createChooser(intent,
"Choose File to Upload.."), PICK_FILE_REQUEST);
}
public String getFileName(Uri uri) {
String result = null;
if (uri.getScheme().equals("content")) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
try {
if (cursor != null && cursor.moveToFirst()) {
result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
} finally {
cursor.close();
}
}
if (result == null) {
result = uri.getPath();
int cut = result.lastIndexOf('/');
if (cut != -1) {
result = result.substring(cut + 1);
}
}
return result;
}
String filename =getFileName(yourfileuri);

Cant pick picture from gallery. Result code always cancelled

The complete code of my Fragment:
public class ProfileEditPictureFragment extends BaseFragment implements OnClickListener {
private ImageView imageView = null;
private Button buttonPick = null;
private Button buttonSave = null;
private Button buttonCancel = null;
private File tempFile = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setRetainInstance(true);
this.sessionProfilePreferences = new SessionProfilePreferences(this.getActivity());
this.sessionLoginPreferences = new SessionLoginPreferences(this.getActivity());
this.sessionLoginSingleton = SessionLoginSingleton.getInstance(this.getActivity());
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
this.tempFile = new File(Environment.getExternalStorageDirectory(), "temp_photo.jpg");
}
else {
this.tempFile = new File(this.getActivity().getFilesDir(), "temp_photo.jpg");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_profile_picture_edit, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
this.imageView = (ImageView) view.findViewById(R.id.profile_picture_edit_imageview_photo);
this.buttonPick = (Button) view.findViewById(R.id.profile_picture_edit_button_pick);
this.buttonPick.setOnClickListener(this);
this.buttonSave = (Button) view.findViewById(R.id.profile_picture_edit_button_save);
this.buttonSave.setOnClickListener(this);
this.buttonCancel = (Button) view.findViewById(R.id.profile_picture_edit_button_cancel);
this.buttonCancel.setOnClickListener(this);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.v("ProfileEditPicture", "requestCode: " + requestCode);
Log.v("ProfileEditPicture", "resultCode: " + resultCode);
Log.v("ProfileEditPicture", "data: " + data);
Bitmap bitmap = null;
if(resultCode == Activity.RESULT_OK) {
if (requestCode == Globals.REQUEST_PICK_PHOTO) {
try {
InputStream inputStream = this.getActivity().getContentResolver().openInputStream(data.getData());
FileOutputStream fileOutputStream = new FileOutputStream(this.tempFile);
Helper.copyStream(inputStream, fileOutputStream);
fileOutputStream.close();
inputStream.close();
this.startCropImage();
} catch (Exception e) {}
} else if (requestCode == Globals.REQUEST_CROP_PHOTO) {
String path = data.getStringExtra(CropActivity.IMAGE_PATH);
if (path == null) {
return;
}
bitmap = BitmapFactory.decodeFile(this.tempFile.getPath());
this.imageView.setImageBitmap(bitmap);
}
}
}
#Override
public void onClick(View view) {
switch(view.getId()) {
case R.id.profile_picture_edit_button_pick : {
this.pickPicture();
} break;
case R.id.profile_picture_edit_button_save : {
} break;
case R.id.profile_picture_edit_button_cancel : {
this.getActivity().finish();
}
}
}
private void pickPicture() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
this.startActivityForResult(Intent.createChooser(intent, "Select Picture"), Globals.REQUEST_PICK_PHOTO);
}
private void startCropImage() {
Intent intent = new Intent(this.getActivity(), CropActivity.class);
intent.putExtra(CropActivity.IMAGE_PATH, this.tempFile.getPath());
intent.putExtra(CropActivity.SCALE, true);
intent.putExtra(CropActivity.ASPECT_X, 3);
intent.putExtra(CropActivity.ASPECT_Y, 2);
this.startActivityForResult(intent, Globals.REQUEST_CROP_PHOTO);
}
}
But the resultCode is always 0 and the data is always null. Permissions are set ofcourse.
So how can i pick images from the gallery?
I test it on Nexus 4 with Android 5.0.1
Try ACTION_PICK like this
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
And on Activity result
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
ImageView imgView = (ImageView) findViewById(R.id.imgView);
imgView.setImageBitmap(BitmapFactory
.decodeFile(imgDecodableString));
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
I was having same problem in one of my activities when I set launchMode="singleInstance" in manifest for that activity. It works fine when I remove that attribute. Although I don't know reason for this behaviour.

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