Certain audio files not loading on Android 'File not found' - java

I have an app that allows you to pick an audio file and then load / playback etc.
For some reason certain files do not load, even though they are selectable, and are not unusual file types, for example, I am currently trying an MP3 audio file (6.5mb).
This is the process once selected;
// load audio to SoundController
public void initSound(String audioPath) {
File audioFile = new File(audioPath);
if (audioFile.exists()) {
String s = audioFile.getName();
mFileName = s.substring(0, s.length() - 4);
showProcessDialog();
try {
mSoundController.loadAudio(audioFile.getAbsolutePath());
mSoundController.loadVisualizer(visualizerView, false);
mSoundController.loadVisualizer(visualizerReverseView, true);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Cannot load audio file", Toast.LENGTH_SHORT).show();
closeProcessDiaglog();
}
} else {
Toast.makeText(getApplicationContext(), "File not found", Toast.LENGTH_SHORT).show();
}
}
The showProcessDialog;
void showProcessDialog() {
isLoadedAudio = false;
prcDialog = new ProgressDialog(this);
prcDialog.setMessage("Please Wait - Loading Audio - if this dialogue appears for more than 15 seconds, your file is not compatible so please try loading a different audio file.");
prcDialog.setCancelable(true);
prcDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Cancel & Try A Different Audio File",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
} );
prcDialog.show();
}
// Close Process dialog
void closeProcessDiaglog() {
if (prcDialog.isShowing()) {
prcDialog.dismiss();
}
checkAudioLoaded();
}
public void checkAudioLoaded() {
sbSongProcess.setEnabled(mSoundController.isPlaying());
if (mSoundController.isLoadedAudio()) {
playAudio.setEnabled(true);
playAudio.setChecked(mSoundController.isPlaying());
} else {
playAudio.setEnabled(false);
playAudio.setChecked(false);
}
}
Of course also onActivityResult;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == AppicationContants.OPEN_FILE_REQUEST && resultCode == RESULT_OK) {
mPath = data.getStringExtra("Path");
isLoadingFile = true;
}
}
This particular mp3 file, the dialogue shows, however does not ever dismiss and the file does not load, but other files will fire the 'File not found' Toast message found in my initSound method.
I am struggling to understand why, these are audio files that are downloaded onto my device.
The ManagerAudioActivity.java file handles the choosing of the file / opening.
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == AppicationContants.AUDIO_PICK_REQUEST_CODE && resultCode == RESULT_OK) {
try {
Uri uri = data.getData();
String arr1 = uri.toString().substring(0, uri.toString().lastIndexOf("/"));
String id = DocumentsContract.getDocumentId(uri);
String path = FilePath.getPath(this, uri);
File t = null;
// Alternatively, use FileUtils.getFile(Context, Uri)
if (path != null && FileUtils.isLocal(path)) {
t = new File(path);
}
mPath = path;
Toast.makeText(getApplicationContext(), mPath, Toast.LENGTH_LONG).show();
if(checkIfAudio(mPath)) {
if(t.exists()) {
String description = "Tempo:100 Pitch:+0 Key:+0";
Song newSong = new Song(t.getName().substring(0, t.getName().length() -4), description, t.getAbsolutePath());
if(!checkIfExisted(newSong.getName())) {
currentCategory.getSongs().add(newSong);
}
SongAdapter songAdapter = new SongAdapter(ManagerAudioActivity.this, currentCategory.getSongs());
lvListSong.setAdapter(songAdapter);
((CustomAdapter) lvListCategory.getAdapter()).updateItemList(categories);
saveData();
} else {
Toast.makeText(getApplicationContext(), "File not found", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(), "File in wrong format", Toast.LENGTH_SHORT).show();
}
} catch (Exception ex) {
Toast.makeText(getApplicationContext(), "File not found", Toast.LENGTH_SHORT).show();
}
}
}
public boolean checkIfAudio(String path)
{
boolean result = false;
try {
SoundStreamAudioPlayer audioPlayer = new SoundStreamAudioPlayer(10, path, 1.0f, 0.0f);
result = true;
audioPlayer = null;
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "error="+e.getMessage(), Toast.LENGTH_SHORT).show();
}
return result;
}
public boolean checkIfExisted(String name)
{
if(currentCategory!= null && currentCategory.getSongs().size()>0)
{
for(int i =0 ; i< currentCategory.getSongs().size() ; i++)
{
if(currentCategory.getSongs().get(i).getName().equals(name))
{
return true;
}
}
}
return false;
}

Related

Files not being deleted in android 11 using MediaStore.createDeleteRequest()

I am trying to delete audio recordings that I created before Re-installing my app. I'm using MediaStore.createDeleteRequest() and it successfully shows me a dialog box to ask for permission to delete the files, but when I click "Allow" it doesn't delete the files.
My Audio Recordings are stored in "storage/emulated/0/MUSIC/Wear Voice Recorder/"
This is my code :
public void onClick(View v) {
List<Uri> uris = new ArrayList<>();
for (Recordings rec : selectionList) {
String date = rec.getRecordingDate();
SimpleDateFormat original = new SimpleDateFormat("d MMM yy, hh:mm:ss a");
SimpleDateFormat target = new SimpleDateFormat("yyyyMMdd_HHmmss");
try {
tempDate = original.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
String fileName = rec.getRecordingName() + "_W_" + target.format(tempDate) + ".mp3";
File directory = Environment.getExternalStorageDirectory();
file = new File(directory + File.separator + Environment.DIRECTORY_MUSIC + File.separator + "Wear Voice Recorder");
File[] list = file.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".mp3");
}
});
for (File mediaFile : list) {
if (mediaFile.getName().equals(fileName)) {
arrList.remove(rec);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
long mediaID = getFilePathToMediaID(mediaFile.getPath(), RecordingsListActivity.this);
Uri Uri_one =ContentUris.withAppendedId(MediaStore.Audio.Media.getContentUri("internal"), mediaID);
uris.add(Uri_one);
}
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) {
try {
mediaFile.delete();
} catch (Exception e) {
Toast.makeText(RecordingsListActivity.this, "Recording Not Found", Toast.LENGTH_SHORT).show();
}
}
}
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
requestDeletePermission(RecordingsListActivity.this, uris);
System.out.println(uris+"");
}
adapter.notifyDataSetChanged();
endSelectionMode();
}
#RequiresApi(api = Build.VERSION_CODES.R)
private void requestDeletePermission(Context context, List<Uri> uri_one) {
PendingIntent pi = MediaStore.createDeleteRequest(context.getContentResolver(), uri_one);
try {
startIntentSenderForResult(pi.getIntentSender(), REQUEST_PERM_DELETE, null, 0, 0, 0);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
}
private long getFilePathToMediaID(String path, Context context) {
long id = 0;
ContentResolver cr = context.getContentResolver();
Uri uri = MediaStore.Files.getContentUri("internal");
String selection = MediaStore.Audio.Media.DATA;
String[] selectionArgs = {path};
String[] projection = {MediaStore.Audio.Media._ID};
String sortOrder = MediaStore.Audio.Media.TITLE + " ASC";
Cursor cursor = cr.query(uri, projection, selection + "=?", selectionArgs, null);
if (cursor != null) {
while (cursor.moveToNext()) {
int idIndex = cursor.getColumnIndex(MediaStore.Audio.Media._ID);
id = Long.parseLong(cursor.getString(idIndex));
}
}
return id;
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_PERM_DELETE:
if (resultCode == Activity.RESULT_OK) {
Toast.makeText(RecordingsListActivity.this, "Deleted successfully!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(RecordingsListActivity.this, "Failed to delete!", Toast.LENGTH_SHORT).show();
}
break;
}
}
I don't really know much about MediaStore, this is my first app and it's so frustrating to ask for permission to delete files that my app created before I uninstalled and re-installed.
I think there's something wrong with the URI, when I print the URI of different files, the URIs are the same.
It does show me the dialog box to delete the files and it also shows a toast saying "Deleted Successfully!" but the files are still there.
Uri uri = MediaStore.Files.getContentUri("internal");
Try:
Uri uri = MediaStore.Video.Media.getContentUri("internal");
But probably you should change "internal" to MediaStore.VOLUME_EXTERNAL too.

Running an app in background to copy a particular folder from pen drive to a physical device?

I am creating an app which I want to run it in the background. The project has a basic concept of copying files from pen drive to android device in local storage without app opening and also to copy only a single folder named thinpc whenever pen drive is attached to a device it automatically starts copying folder (thinpc) without any permission. I have done the copying part but the issue is that the app is not working automatically I have to do touch that folder to copy which I don't want to do.
Here is the reference link to complete code and also I am sharing the MainActivity.java
" https://github.com/magnusja/libaums "
MainActivity.java
private void discoverDevice() {
UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
massStorageDevices = UsbMassStorageDevice.getMassStorageDevices(this);
if (massStorageDevices.length == 0) {
Log.w(TAG, "no device found!");
android.support.v7.app.ActionBar actionBar = getSupportActionBar();
actionBar.setTitle("No Pen drive detected ");
listView.setAdapter(null);
return;
}else {
android.support.v7.app.ActionBar actionBar = getSupportActionBar();
actionBar.setTitle("thinpc");
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long rowId) {
UsbFile entry = adapter.getItem(position);
try {
if (entry.isDirectory()) {
dirs.push(adapter.getCurrentDir());
listView.setAdapter(adapter = new UsbFileListAdapter(this, entry));
} else {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Toast.makeText(this, R.string.request_write_storage_perm, Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_EXT_STORAGE_WRITE_PERM);
}
return;
}
CopyTaskParam param = new CopyTaskParam();
param.from = entry;
File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/thinpc/cache");
f.mkdirs();
int index = entry.getName().lastIndexOf(".") > 0
? entry.getName().lastIndexOf(".")
: entry.getName().length();
String prefix = entry.getName().substring(0, index);
String ext = entry.getName().substring(index);
// prefix must be at least 3 characters
if(prefix.length() < 3) {
prefix += "pad";
}
param.to = File.createTempFile(prefix, ext, f);
new CopyTask().execute(param);
}
} catch (IOException e) {
Log.e(TAG, "error staring to copy!", e);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != Activity.RESULT_OK) {
Log.w(TAG, "Activity result is not ok");
return;
}
if (requestCode == OPEN_STORAGE_PROVIDER_RESULT) {
Uri uri;
if (data != null) {
uri = data.getData();
Log.i(TAG, "Uri: " + uri.toString());
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(uri);
startActivity(i);
}
} else if (requestCode == COPY_STORAGE_PROVIDER_RESULT) {
Uri uri;
if (data != null) {
uri = data.getData();
Log.i(TAG, "Uri: " + uri.toString());
CopyToUsbTaskParam params = new CopyToUsbTaskParam();
params.from = uri;
new CopyToUsbTask().execute(params);
}
} else if (requestCode == OPEN_DOCUMENT_TREE_RESULT) {
Uri uri;
if (data != null) {
uri = data.getData();
Log.i(TAG, "Uri: " + uri.toString());
CopyToUsbTaskParam params = new CopyToUsbTaskParam();
params.from = uri;
new CopyFolderToUsbTask().execute(params);
}
}
}
Remaining code is in the reference link above
Thanks in advance

Android app crop photo

I have a question.
This is the code that my application already have and it works like this : takes photo >crop > upload.
I don't want to crop the photo .How can I do this? Just deleting the dispatchCropImageIntent method?
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(this.getClass().getSimpleName(), "onActivityResult");
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_IMAGE_CAPTURE) {
File imageFile = new File(mCurrentPhotoPath);
if (imageFile.exists()) {
dispatchCropImageIntent(Uri.fromFile(imageFile));
}
} else if (requestCode == REQUEST_IMAGE_FROM_GALLERY_SELECT) {
dispatchCropImageIntent(data.getData());
} else if (requestCode == REQUEST_PICTURE_CROP) {
String filePath = Environment.getExternalStorageDirectory()
+ "/temporary_holder.jpg";
setCurrentBitmap(BitmapFactory.decodeFile(filePath));
} else if(requestCode == CAMERA_ACTIVITY_CODE){
// Get path
String path = data.getStringExtra(CustomCamera.OUT_PATH);
// Read file
byte[] imgData = AppFS.readFileFromPath(path);
if (imgData != null) {
Bitmap bitmap = BitmapFactory.decodeByteArray(imgData , 0, imgData.length);
// TODO: Do something with the image, it should be okay
//((ImageView)findViewById(R.id.img)).setImageBitmap(bitmap);
} else {
Log.e("Main", "Data is null");
}
}
}
else{
onBackPressed();
}
}
And :
private void dispatchCropImageIntent(Uri uri) {
Intent cropImageIntent = new Intent("com.android.camera.action.CROP");
cropImageIntent.setDataAndType(uri, "image/*");
cropImageIntent.putExtra("crop", "true");
cropImageIntent.putExtra("noFaceDetection", true);
cropImageIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
// retrieve data on return
cropImageIntent.putExtra("return-data", true);
File f = new File(Environment.getExternalStorageDirectory(),
"/temporary_holder.jpg");
try {
f.createNewFile();
} catch (IOException ex) {
Log.e("io", ex.getMessage());
}
uri = Uri.fromFile(f);
cropImageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(cropImageIntent, REQUEST_PICTURE_CROP);
}
If I understand you correctly,you want to make your app working like this: takes photo > upload. So, you need to replace dispatchCropImageIntent() with setCurrentBitmap() or upload methond.

Saving an image to ExtSD in android using Java?

So after trying many answers for the same question, here are just two e.g;
Saving an image in android
and
Saving an image to a server using a Java applet
My app still fails in fact whatever I have done has made it worse, before it would actually save the image as "temp.jpg" in the ExtSD root folder, now when I click the tick to accept the photo nothing happens, no crashing, no nothing, I can retake the image and I can cancel the taking of a photo but nothing else happens.
What it does now:
Opens the camera (or gallery)
Takes the photo
Fails to save/set the photo
What I want it to do;
Take the photo
Store it with a unique name (timestamp)
Have the image set to CircleView
Here is my code (if you need more please ask for what you need);
CircleImageView circleImageView;
ImageButton b;
private void selectImage() {
final CharSequence[] options = { "Take a Pic", "Choose from Gallery", "Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Set Profile Pic");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take a Pic"))
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
String folder_main = "iDealer";
String sub_folder = "ProPics";
String timeStamp = new SimpleDateFormat("ddMMyyy_HHmmss").format(Calendar.getInstance().getTime());
String pro_pic_name = folder_main + "_" + timeStamp;
File f = new File(android.os.Environment.getExternalStorageDirectory() + "/" + folder_main + "/" + sub_folder + pro_pic_name);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
}
else if (options[item].equals("Choose from Gallery"))
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
circleImageView.setImageBitmap(bitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "iDealer" + File.separator + "default";
f.delete();
OutputStream outFile = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);
if (c != null) {
c.moveToFirst();
}
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Log.w("path from gallery = ", picturePath+"");
circleImageView.setImageBitmap(thumbnail);
}
}
}

onActivityResult not working on API 23

The onActivityResult method returns blank data or is not called when picking an image from Gallery. My implementation works fine on API 16, 17...22 but I am having problems with API 23. I read this article: https://guides.codepath.com/android/Accessing-the-Camera-and-Stored-Media , about permissions.
My client has tested the app on 3 phones running Android 6
and they all have the same behavior when picking a image. You can see an activity screenshot, there are 3 ImageButtons (a big one, and 2 small ones), when user clicks on an ImageButton the gallery is triggered for picking an image, when user picks an image the ImageButton just gets grey instead of showing the picked image.
////onclick method///photo2 is a imagebutton////SELECT_PICTURE2 is the code
photo2_evento.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
//startActivityForResult(Intent.createChooser(intent, "Escoge
una imagen"), SELECT_PICTURE2);
startActivityForResult(intent, SELECT_PICTURE2);
}
});
///onactivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
try{
Uri selectedImageUri = data.getData();
if (requestCode == SELECT_PICTURE1) {
photo1_path = getRealPathFromURI(selectedImageUri);
photo1_evento.setImageBitmap(decodeSampledBitmapFromResource(photo1_path, 400, 400));
}else if(requestCode == SELECT_PICTURE2){
photo2_path = getRealPathFromURI(selectedImageUri);
photo2_evento.setImageBitmap(decodeSampledBitmapFromResource(photo2_path, 100, 100));
}else if(requestCode == SELECT_PICTURE3){
photo3_path = getRealPathFromURI(selectedImageUri);
photo3_evento.setImageBitmap(decodeSampledBitmapFromResource(photo3_path, 100, 100));
}
}catch(Exception e){
e.printStackTrace();
}catch (OutOfMemoryError e) {
e.printStackTrace();
Toast.makeText(getBaseContext(),"memory error", Toast.LENGTH_LONG).show();
}
}
}
////decodeSampledBitmapFromResource is just a method provided by Google Android for sizing images.
////this method is for getting the URI path, I got this code from stackoverflow
public String getRealPathFromURI(Uri contentUri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = null;
try {
if (Build.VERSION.SDK_INT > 19) {
// Will return "image:x*"
String wholeID = DocumentsContract.getDocumentId(contentUri);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
cursor = Publicar_Eventos.this.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, sel, new String[] { id }, null);
} else {
cursor = Publicar_Eventos.this.getContentResolver().query(contentUri,
projection, null, null, null);
}
} catch (Exception e) {
e.printStackTrace();
}catch (OutOfMemoryError e) {
e.printStackTrace();
Toast.makeText(getBaseContext(),"error de memoria", Toast.LENGTH_LONG).show();
}
String path = null;
try {
int column_index = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
path = cursor.getString(column_index).toString();
cursor.close();
} catch (NullPointerException e) {
e.printStackTrace();
}
return path;
}

Categories