I need to fetch an audio file from SD Card and play it. I think this can be done by getting URI of an audio file. So, to pick an audio file I'm using following code:
Intent intent = new Intent();
intent.setType("audio/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Audio "), reqCode);
Now, I can browse for audio files and select one of them.
QUESTION: How to read the URI of picked file in my onActivityResult?
You can put below codes in your project when you want to select audio.
Intent intent_upload = new Intent();
intent_upload.setType("audio/*");
intent_upload.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent_upload,1);
And override onActivityResult in the same Activity, as below
#Override
protected void onActivityResult(int requestCode,int resultCode,Intent data){
if(requestCode == 1){
if(resultCode == RESULT_OK){
//the selected audio.
Uri uri = data.getData();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
first of all open gallery through intent -
public void openGalleryForAudio() {
Intent videoIntent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(Intent.createChooser(videoIntent, "Select Audio"), AUDIO_REQUEST);
}
Then onActivityResult you should catch data -
if (requestCode == AUDIO_REQUEST && null != data) {
if (requestCode == AUDIO_REQUEST) {
Uri uri = data.getData();
try {
String uriString = uri.toString();
File myFile = new File(uriString);
// String path = myFile.getAbsolutePath();
String displayName = null;
String path2 = getAudioPath(uri);
File f = new File(path2);
long fileSizeInBytes = f.length();
long fileSizeInKB = fileSizeInBytes / 1024;
long fileSizeInMB = fileSizeInKB / 1024;
if (fileSizeInMB > 8) {
customAlterDialog("Can't Upload ", "sorry file size is large");
} else {
profilePicUrl = path2;
isPicSelect = true;
}
} catch (Exception e) {
//handle exception
Toast.makeText(GroupDetailsActivity.this, "Unable to process,try again", Toast.LENGTH_SHORT).show();
}
// String path1 = uri.getPath();
}
}
This function is use for absolute path of audio file
private String getAudioPath(Uri uri) {
String[] data = {MediaStore.Audio.Media.DATA};
CursorLoader loader = new CursorLoader(getApplicationContext(), uri, data, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
No need to add type here like audio/*. It will crash to search such type of action.
Try this. It worked for me.
val intent = Intent(Intent.ACTION_PICK, android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI)
startActivityForResult(intent, AUDIO_REQUEST_CODE)
final Uri uri=Uri.parse(Environment.getExternalStorageDirectory()+"/Audio/abc.mp3");
Replace /Audio/abc.mp3 with your path of mp3 file on sdcard.
Dont forget to check if the external storage is mounted.
Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
//To pick audio file from device. Place below code in calling activity
int REQUEST_CODE = 1001;
Intent audioIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(audioIntent,REQUEST_CODE);
// Override onActivityForResult method in activity
#Override
protected void onActivityResult(int requestCode,int resultCode,Intent data){
if(requestCode == REQUEST_CODE && resultCode == RESULT_OK ){
//the selected audio.Do some thing with uri
Uri uri = data.getData();
}
super.onActivityResult(requestCode, resultCode, data);
}
Related
public void getPhoto() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file/*");
startActivityForResult(intent, 1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null) {
Uri selectedImage = data.getData();
try {
if(clicked==true){
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
Log.i("Photo", "Received");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
ParseFile file = new ParseFile("image.png", byteArray);
}
I'm struggling to sort out this problem somebody tell how to get pdf file and convert into Byte array
use this code to get pick pdf file and get the name, path, file, and Byte[];
public void getPhoto() {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("application/pdf");
startActivityForResult(intent, 1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null) {
Uri selectedImage = data.getData();
try {
if(clicked==true){
Uri uri = data.getData();
String uriString = uri.toString();
File myFile = new File(uriString);
String path = myFile.getAbsolutePath();
String displayName = null;
Byte[] fileToByteArray=org.apache.commons.io.FileUtils.readFileToByteArray(myFile);
if (uriString.startsWith("content://")) {
Cursor cursor = null;
try {
cursor = getActivity().getContentResolver().query(uri, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
} finally {
cursor.close();
}
} else if (uriString.startsWith("file://")) {
displayName = myFile.getName();
}
}
Use below code and declare provider in your manifest.xml. and also create a provider.xml in your xml folder and provide the desired path in provider.xml and use the byte array for following code.
File pdf = new File(Environment.getExternalStorageDirectory(), "Download" +"/"+ fileName+ ".pdf");
Uri fileURI = FileProvider.getUriForFile(MainActivity.this, "your package name" + ".provider", file1);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(fileURI, "application/pdf");
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
I am trying to get the real path of a URI.
First I start the gallery app through an intent:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select picture"), SELECT_IMAGE );
After that the onActivityResult gets called, where I try to get the absolut path of the URI.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (resultCode == RESULT_OK) {
Uri uri;
if (requestCode == SELECT_IMAGE) {
final Uri uri_data = data.getData();
// Get the path from the Uri
final String path = getPathFromURI(uri_data);
if (path != null) {
File f = new File(path);
uri = Uri.fromFile(f);
}
}
}
} catch (Exception e) {
Log.e("FileSelectorActivity", "File select error", e);
}
}
The uri_data contains "content://com.android.providers.media.documents/document/image%3A67", but the resulting path is null.
The pathFromUri method looks like this:
private String getPathFromURI(Uri contentUri) {
String res = null;
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
if (cursor.moveToFirst()) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
res = cursor.getString(column_index);
}
cursor.close();
return res;
}
Here the column_index is 0, but cursor.getString returns null.
Why does this happen?
I have the permission android.permission.READ_EXTERNAL_STORAGE
EDIT:
So I want to take a picture through the camera app, and the user then chooses the image. So the file should be acutally stored on the phone (which is, since I am testing it on my phone)
EDIT:
Okey, the solution was to request the permissions at runtime...sorry guys
i am new to android and trying to make an app using existing camera.
i am trying to save the image in the dcim directory.
for now the app create a file but no images, how could i advance,how to save the image
thanks in advance
======================== CAMERA ===============================
public static class App {
public static File file;
public static File directory;
}
private void CreateDirectoryForPictures() {
File path= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
App.directory = new File(path,"Mahapach_Images");
if (!App.directory.exists()) {
App.directory.getParentFile().mkdirs();
}
}
private void takeAPicture(){
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
CreateDirectoryForPictures();
Intent intent =new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
App.file = new File(App.directory,imageFileName);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(App.file));
startActivityForResult(intent,1);
}
private void choosePhotoFromGallery() {
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
//make it available in the gallery
Intent mediaScanIntent = new Intent (Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(App.file);
mediaScanIntent.setData(contentUri);
sendBroadcast(mediaScanIntent);
}
else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Log.e("path image from gallery", picturePath + "");
infoWindowImageView.setImageBitmap(thumbnail);
}
}
}
You can easily find many tutorial by just google, and that can do your task like this one i found here
OR
There is better way, use Easy Image library which can do your task with ease click here but remember you have to take care of permission for marshmallow and above android versions.
how to get file path using intent. I am using this code to choose the file
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
// intent.setData(uri);
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(
Intent.createChooser(intent, "Select a File to Upload"),PICKFILE_RESULT_CODE);
} catch (android.content.ActivityNotFoundException ex)
{// Potentially direct the user to the Market with a Dialog
Toast.makeText(getApplicationContext(), "Please install a File Manager.", Toast.LENGTH_LONG).show();
}
now i want to get actual file path in
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICKFILE_RESULT_CODE && resultCode == RESULT_OK
&& data != null) {
Uri selectedFile = data.getData();
String[] filePathColum = { };
Cursor cursor = getContentResolver().query(selectedFile,
filePathColum, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColum[0]);
String FilePath = cursor.getString(columnIndex);
but when i try to get file path it crashed
how i get file path
I call camera intent and try to save capture image in sd card.but camera intent give me null data.what is the problem i can't understood.my code is as follow
imgBtnPicture.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String fileName="ashraful.jpg";
String root = Environment.getExternalStorageDirectory().toString();
new File(root + "/photofolder").mkdirs();
File outputfile=new File(root+"/photofolder/", fileName);
Uri outputFileUri = Uri.fromFile(outputfile);
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
if(data!=null)
{
Bitmap photo = (Bitmap) data.getExtras().get("data");
Bitmap icon1=ResizeBitmap(photo,200,200);
imgBtnPicture.setImageBitmap(icon1);
}
}
}
but i get null data? how to solve my problem?plz help
private void takeNewPicture() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
ContentValues values = new ContentValues(3);
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
cameraImagePath = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, cameraImagePath);
startActivityForResult(takePictureIntent, CAMERA_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Uri imageFilePathUri = null;
if (cameraImagePath != null) {
Cursor imageCursor = getContentResolver().query(
cameraImagePath, filePathColumn, null, null, null);
if (imageCursor != null && imageCursor.moveToFirst()) {
int columnIndex = imageCursor.getColumnIndex(filePathColumn[0]);
String filePath = imageCursor.getString(columnIndex);
imageCursor.close();
imageFilePathUri = filePath != null ? Uri
.parse(filePath) : null;
}
}
}
}
cameraImagePath is a Uri object
Read this Android Training post carefully to figure things out. As the post says,
The Android Camera application saves a full-size photo if you give it a file to save into.
so if you did pass the Uri of a file, you should access the image using this Uri.