I am developing an application that contains a RecyclerView with some audio players. The app will download the .3gp files if they have not been downloaded.
When I click the playAudio button, the audio is not being played.
Here is my adapter code:
else if( item.getTipo().equals(AUDIO)){
MediaPlayer mediaPlayer = new MediaPlayer();
File folder = new File(Environment.getExternalStorageDirectory() +
File.separator + "Audios");
File file = new File(folder.getPath() + File.separator
+ item.getNomeArquivo());
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference httpsReference = storage.getReferenceFromUrl( item.getAudio());
File localFile = null;
boolean success = true;
if (!folder.exists()) {
success = folder.mkdirs();
}
if (success) {
localFile = new File(folder.getPath() + File.separator
+ item.getNomeArquivo());
File finalLocalFile = localFile;
httpsReference.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(context,"Baixado",Toast.LENGTH_SHORT);
holder.progressAudio.setVisibility(View.GONE);
holder.playAudio.setVisibility(View.VISIBLE);
holder.playAudio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mediaPlayer != null){
String path = Environment.getExternalStorageDirectory() +
File.separator + "Audios" + File.separator
+ item.getNomeArquivo();
Log.i("PATHA",path);
mediaPlayer.create(context,Uri.parse(path));
mediaPlayer.setVolume(50,50);
mediaPlayer.start();
}
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
Toast.makeText(context,"Erro ao fazer download",Toast.LENGTH_SHORT);
}
});
} else {
Toast.makeText(context, "Erro ao criar arquivo", Toast.LENGTH_SHORT).show();
}
}
How can I fix this?
Try replacing:
mediaPlayer.create(context,Uri.parse(path));
with:
mediaPlayer.create(context, Uri.fromFile(new File(path)));
Related
Android/Java, API level 12.
I'm trying to check if a .zip file exists in the Downloads folder. If it doesn't exist then I'm downloading it from the internet using DownloadManager. For the purposes of testing I'm running my checkIfFileExists immediately after the onReceive method of the DownloadManager, subject to the download being successful. My issue is that checkIfFileExists is returning false every time, even after I've just downloaded the file and I've checked manually that it does exist.
The relevant code is below.
DownloadManager dm;
long queueid;
String filename = "myfile.zip", url = "http://myurl/", uriString = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
[...]
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action))
{
DownloadManager.Query req_query = new DownloadManager.Query();
req_query.setFilterById(queueid);
Cursor c = dm.query(req_query);
if (c==null)
{
Toast.makeText(context, "Download not found!", Toast.LENGTH_SHORT).show();
}
else
{
if (c.moveToFirst())
{
int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL==c.getInt(columnIndex))
{
uriString = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
Toast.makeText(context, "Download finished.", Toast.LENGTH_SHORT).show();
Toast.makeText(context, uriString, Toast.LENGTH_LONG).show();
checkIfFileExists();
}
}
}
}
}
};
registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
public void onClickDownload(View v) // this method seems to be working with no issues.
{
dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, filename);
queueid = dm.enqueue(request);
}
private boolean checkIfFileExists()
{
File file = new File(uriString);
if(file.exists())
{
Toast.makeText(this, "Exists", Toast.LENGTH_SHORT).show();
return true;
}
else
{
Toast.makeText(this, "Doesn't exist", Toast.LENGTH_SHORT).show();
return false;
}
}
I was expecting if(file.exists()) to evaluate to true since the file does exist.
What actually happens is if(file.exists()) always evaluates as false.
Can anyone see what I'm doing wrong?
Change your method like this.:
private boolean checkIfFileExists(String zipName /*ex: fileName.zip*/) {
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), zipName);
if(file.exists()) {
Toast.makeText(this, "Exists", Toast.LENGTH_SHORT).show();
return true;
} else {
Toast.makeText(this, "Doesn't exist", Toast.LENGTH_SHORT).show();
return false;
}
}
I have made a media player app using Exoplayer. I am trying to implement the rename and delete functionality on the individual media files. But the operations are not working and file.renameTo(newFile) always returns false. I have checked other answers on StackOverflow about file permissions but it is not working. Please help!
Here is the code-
For deleting file
#Override
public void onClick(View view) {
AlertDialog.Builder alertDialog=new AlertDialog.Builder(context);
alertDialog.setTitle("Delete");
alertDialog.setMessage("Do you want to delete this file?");
alertDialog.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Uri contentUri=null;
if(mediaType.equals(MEDIA_TYPE_VIDEO))
contentUri= ContentUris.withAppendedId(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
Long.parseLong(mediaList.get(holder.getAbsoluteAdapterPosition()).getId()));
else if(mediaType.equals(MEDIA_TYPE_AUDIO))
contentUri=ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
Long.parseLong(mediaList.get(holder.getAbsoluteAdapterPosition()).getId()));
else
Toast.makeText(context.getApplicationContext(), "wrong media type!",Toast.LENGTH_SHORT).show();
File file=new File(mediaList.get(holder.getAbsoluteAdapterPosition()).getPath());
Log.i(TAG+" ###",""+file.getName());
boolean delete=file.delete();
if(delete)
{
context.getContentResolver().delete(contentUri,null,null);
mediaList.remove(holder.getAbsoluteAdapterPosition());
notifyItemRemoved(holder.getAbsoluteAdapterPosition());
notifyItemRangeChanged(holder.getAbsoluteAdapterPosition(),mediaList.size());
Toast.makeText(context,"File deleted successfully!",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(context,"Media file deletion failed!",Toast.LENGTH_SHORT).show();
}
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
alertDialog.show();
bottomSheetDialog.dismiss();
}
});```
**For renaming file-**
```bsView.findViewById(R.id.bs_rename).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("Rename To");
EditText editText = new EditText(context);
String path = mediaList.get(holder.getAbsoluteAdapterPosition()).getPath();
final File file = new File(path);
String mediaName = file.getName();
mediaName = mediaName.substring(0, mediaName.lastIndexOf("."));
editText.setText(mediaName);
alertDialog.setView(editText);
editText.requestFocus();
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Apply validation check
if(TextUtils.isEmpty(editText.getText().toString()))
{
Toast.makeText(context,"Can't rename empty file",Toast.LENGTH_SHORT).show();
return;
}
String onlyPath = file.getParentFile().getAbsolutePath();
Log.i(TAG + " ###", "Original Path: " + onlyPath);
String ext = file.getAbsolutePath();
Log.i(TAG + " ###", "ext: file.getAbsolutePath(): " + ext);
ext = ext.substring(ext.lastIndexOf("."));
Log.i(TAG + " ###", "ext: file.getAbsolutePath(): " + ext);
String newPath = onlyPath + "/" + editText.getText().toString().trim() + ext;
Log.i(TAG + " ###", "New Path: " + newPath);
File newFile = new File(newPath);
Log.i(TAG+" ###","renaming: in onClick(): newFile name: "+newFile.getName());
boolean rename=false;
try {
rename = file.renameTo(newFile);
Log.i(TAG+" ###","file name after renaming: "+file.getName());
} catch (Exception e) {
Log.e(TAG + " ###", "Exception while renaming: " + e);
}
Log.i(TAG + " ###", "rename: " + rename);
if (rename) {
ContentResolver resolver = context.getApplicationContext().getContentResolver();
resolver.delete(MediaStore.Files.getContentUri("external"),
MediaStore.MediaColumns.DATA + "=?", new String[]
{
file.getAbsolutePath()
});
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(newFile));
context.getApplicationContext().sendBroadcast(intent);
notifyDataSetChanged();
Toast.makeText(context, "File Renamed", Toast.LENGTH_SHORT).show();
//To show the instantaneous change in the name
//Otherwise we have to close and reopen the app to see the change
SystemClock.sleep(200);
((Activity) context).recreate();//automatically refreshes the activity
} else {
Toast.makeText(context, "Process Failed!", Toast.LENGTH_SHORT).show();
}
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//dismiss the dialog
dialogInterface.dismiss();
}
});
alertDialog.create().show();
bottomSheetDialog.dismiss();
}
});```
I have set the following permissions in the Manifest file-
```<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission
android:name="android.permission.MANAGE_EXTERNAL_STORAGE"
tools:ignore="ScopedStorage" />
<uses-permission
android:name="android.permission.WRITE_SETTINGS"
tools:ignore="ProtectedPermissions" />
<uses-permission android:name="android.permission.CHANGE_SYSTEM_SETTINGS" />```
i have problem when try share mp3 file from res/raw device throws an error "Invalid path"
My code:
Uri rawUri = getRawUri("sound1.mp3");
btn_shareaudio = (Button) findViewById(R.id.button);
btn_shareaudio.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
final Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("audio/*");
shareIntent.putExtra(Intent.EXTRA_STREAM, rawUri);
startActivity(Intent.createChooser(shareIntent, "Condividi attraverso:"));
}
});
public Uri getRawUri(String filename) {
return Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + File.pathSeparator + File.separator + getPackageName() + "/raw/" + filename);
}
When I am trying to save file to the firebase storage it always save it with the name 'null'.this is my code:
try {
localFile = createTempImageFile(getExternalCacheDir());
final File finalLocalFile = localFile;
mStorageRef.child("images/" + mRereference).getFile(localFile)
.addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
Picasso.with(getBaseContext())
.load(Uri.fromFile(finalLocalFile))
.into(mIVpicture1);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.i("Load","" + e);
}
});
} catch (IOException e) {
e.printStackTrace();
}
This is the metod createTempImageFile which doesn't work :
public static File createTempImageFile(File storageDir) throws
IOException
{
String timeStamp = new SimpleDateFormat("dd-MM-yyyy hh-mm-ss",
Locale.getDefault()).format(new Date());
String imageFileName = "photo_" + timeStamp;
return File.createTempFile(
imageFileName,
".jpg",
storageDir
);
}
This is a code for upploading a pictute to the firebase storage
public void uploadFileInFireBaseStorage (Uri uri){
UploadTask uploadTask = mStorageRef.child("images/" + mRereference).putFile(uri);
uploadTask.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred());
Log.i("Load","Upload is " + progress + "% done");
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> urlTask = taskSnapshot.getStorage().getDownloadUrl();
while (!urlTask.isSuccessful());
Uri downloadUrl = urlTask.getResult();
final String download_url = String.valueOf(downloadUrl);
Log.i("Load" , "Uri donwnload" + download_url);
}
});
}
Wassup Guys, i'm doing a college project, and my app is a meme generator. After the text plotted, i'm trying to save the image pushing the button. The toast appears, but, it takes more than an hour to the pic show on the gallery. How can i make this thing save immediately?
So there are my codes to create the button listener and the store function
save.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
View content = findViewById(R.id.lay);
Bitmap bitmap = getScreenShot(content);
currentImage = "meme" + System.currentTimeMillis() + ".png";
store(bitmap, currentImage);
share.setEnabled(true);
}
});
public void store(Bitmap bm, String fileName){
String dirPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Memes";
File dir = new File(dirPath);
if(!dir.exists()){
dir.mkdir();
}
File file = new File(dirPath, fileName);
try{
FileOutputStream fos = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
Toast.makeText(this, "SALVOU ARROMBADO", Toast.LENGTH_SHORT).show();
}catch (Exception e){
Toast.makeText(this, "DEU RUIM VACILĂO", Toast.LENGTH_SHORT).show();
}
}
You have to use MediaScannerConnection like below .Create a method refreshMedia() -
public void refreshMedia(){
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
MediaScannerConnection.scanFile(ApplicationContext.context, new String[] { imageFile.getPath() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
#Override
public void onScanCompleted(String path, Uri uri) {
//gallery refreshed.
Log.i(TAG, "Scanned " + path);
}
});
}
}, 1500); //this is to refresh media after 1.5 second delay
}
Here imageFile.getPath() is path for your image.
Use it as below-
save.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
store(bitmap, currentImage);
//after saving image call refreshmedia()
refreshMedia();
}