Downloaded file not visible from the file browser - java

I download a file from firebase using file like. If I run this code on android emulator then I can see the downloaded file from file browser but in the real phone, it does not display the file.
private void DownloadFromStorage(String fileName) {
// CREATE FOLDER IF NOT EXIST
File dir = new File(DownloadActivity.this.getExternalFilesDir(null), "notes");
if (!dir.exists()) {
boolean b = dir.mkdir();
}
// CREATE FILE
File file = new File(DownloadActivity.this.getExternalFilesDir(null), fileName);
StorageReference storageReference = FirebaseStorage.getInstance().getReference()
.child("note")
.child(fileName);
Log.d("downloadFile: " ,""+ storageReference.getPath());
storageReference.getFile(file).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
if (getBaseContext() != null) {
txtStatus.setVisibility(View.GONE);
mProgressBar.setVisibility(View.GONE);
myToast("Download Complete.");
Log.d("downloadFile: " ,"DOWNLOAD COMPLETE");
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
if (getBaseContext() != null) {
txtStatus.setVisibility(View.GONE);
mProgressBar.setVisibility(View.GONE);
myToast("Download Fail");
Log.d("downloadFile: " ,"DOWNLOAD FAIL");
}
}
}).addOnProgressListener(new OnProgressListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull FileDownloadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
#SuppressLint("DefaultLocale") String uc = String.format("Downloading... %.2f ", progress);
if (getBaseContext() != null) txtStatus.setText(uc);
}
});
}
How can I see this file from the file browser?

Related

I want to add condition if user already save the image than show toast image already saved

The current code works to save the photo but I want to implement the toast code below when the user saves the image already it show image save already. Any ideas how I would do this.
Below is the source code to take the photo:
holder.save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkFolder();
final String path = imagesList.get(position).getPath();
final File file=new File(path);
String destPath = Environment.getExternalStorageDirectory().getAbsolutePath()+Common.APP_DIR;
final File destFile =new File(destPath);
try {
FileUtils.copyFileToDirectory(file, destFile);
} catch (IOException e) {
e.printStackTrace();
}
MediaScannerConnection.scanFile(context, new String[]{destPath + status.getTitle()},
new String[]{"*/*"}, new MediaScannerConnection.MediaScannerConnectionClient() {
#Override
public void onMediaScannerConnected() {
}
#Override
public void onScanCompleted(String path, Uri uri) {
}
});
Toast.makeText(context, "Image Saved Successfully!", Toast.LENGTH_SHORT).show();
}
});

Android Error: FFMPEG No such file or directory error

I went through the solution here.
Android FFMpeg No such file or directory error but it doesn't work for me.
The file is present in the location and I am still getting this error.
Here is the code snippet
private void spliceSong(AudioObject audioObject) {
File folder = new File("/sdcard/roboscreen/TempAudio");
if (!folder.exists()) {
folder.mkdir();
}
String fileName = new File(audioObject.path).getName();
File dest = new File(folder, fileName);
Log.d(TAG, "Destination Filename is " + fileName);
if (!dest.exists()){
try {
dest.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
String path = new File(audioObject.path).getPath();
Log.d(TAG, "File created " + dest.getAbsolutePath() + " " + audioObject.endDate + " " + audioObject.startDate);
String[] command = {"-ss", "2", "-i", "root/"+path, dest.toString()};
Log.d(TAG, "spliceSong: " + (this.context==null));
FFmpeg ffmpeg = FFmpeg.getInstance(this.context);
// // to execute "ffmpeg -version" command you just need to pass "-version"
try {
ffmpeg.loadBinary(new LoadBinaryResponseHandler(){
#Override
public void onSuccess() {
super.onSuccess();
Log.d(TAG, "onSuccess: bruhhhhh");
}
});
} catch (FFmpegNotSupportedException e) {
// Log.d(TAG, "Kaam Tamaam");
e.printStackTrace();
}
try {
ffmpeg.execute(command, new ExecuteBinaryResponseHandler() {
#Override
public void onStart() {
Log.d(TAG, "Work Started done");
}
#Override
public void onProgress(String message) {
Log.d(TAG, "Doing some work");
}
#Override
public void onFailure(String message) {
Log.d(TAG, "Conversion failure " + message);
}
#Override
public void onSuccess(String message) {
Log.d(TAG, "Conversion Successful");
}
#Override
public void onFinish() {
Log.d(TAG, "Work Dome");
}
});
} catch (FFmpegCommandAlreadyRunningException e) {
Log.d(TAG, e.toString());
e.printStackTrace();
}
// Log.d(TAG, "spliced");
// return File
}
and the context is coming through a different class
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public ScreenRecorder(RoboTutor activity, Context context) throws Exception {
if (isInstantiated){
// raise Error and quit
throw new Exception("One instance already instantiated");
}
this.activity = activity;
this.context = context;
this.isInstantiated = true;
this.videoTimeStamp = new Date();
}
A solution would be really appreciated.
Thanks in advance.
Figured it out. There were no issues with the library. I was referring to the wrong paths.

Save file on google drive

Hey I'm trying do application where i check my current location and save this location in ".txt" files. My application save this location in every "user set time" seconds. And it's work. Also I want add save files to Google drive. But I don't know how. Is there any method by which I can create a folder and save ".txt" files same as i did with local folder?
public class Save extends AppCompatActivity {
boolean sms = false;
int n_seconds, n_minutes, n_sum;
private String path = Environment.getExternalStorageDirectory().toString() + "/Loc/Save";
private Button buttonStartThread;
private Handler mainHandler = new Handler();
private volatile boolean stopThread = false;
NumberPicker edit_text_input_back, edit_text_input_back_2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_background);
buttonStartThread = findViewById(R.id.button_start_thread);
edit_phone_number = findViewById(R.id.edit_phone_number);
edit_mail = findViewById(R.id.edit_email);
edit_text_input_back = (NumberPicker) findViewById(R.id.edit_text_input_back);
edit_text_input_back.setMaxValue(60);
edit_text_input_back.setMinValue(0);
edit_text_input_back.setValue(0);
edit_text_input_back_2 = (NumberPicker) findViewById(R.id.edit_text_input_back_2);
edit_text_input_back_2.setMaxValue(60);
edit_text_input_back_2.setMinValue(0);
edit_text_input_back_2.setValue(0);
edit_text_input_back.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker numberPicker, int i, int i1) {
n_seconds = i1;
}
});
edit_text_input_back_2.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker numberPicker, int i, int i1) {
n_minutes = 60 * i1;
}
});
}
public void startThread(View view) {
stopThread = false;
n_sum = n_seconds + n_minutes;
ExampleRunnable runnable = new ExampleRunnable(n_sum);
new Thread(runnable).start();
buttonStartThread.setEnabled(false);
}
public void stopThread(View view) {
stopThread = true;
buttonStartThread.setEnabled(true);
}
class ExampleRunnable implements Runnable {
int seconds;
ExampleRunnable(int seconds) {
this.seconds = seconds;
}
#Override
public void run() {
for (; ; ) {
for (int i = 0; i < seconds; i++) {
if (stopThread)
return;
if (i == n_sum-1) {
runOnUiThread(new Runnable() {
#Override
public void run() {
createDir();
createFile();
}
});
}
Log.d(TAG, "startThread: " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
private void createDir() {
File folder = new File(path);
if(!folder.exists()){
try {
folder.mkdirs();
}catch (Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
}
private void createFile() {
File file = new File(path+"/"+System.currentTimeMillis()+".txt");
FileOutputStream fileOutputStream;
OutputStreamWriter outputStreamWriter;
try {
Intent intent = getIntent();
Double lat = intent.getDoubleExtra("adres", 0);
Double lon = intent.getDoubleExtra("adres2", 0);
String adr = intent.getStringExtra("adres3");
fileOutputStream = new FileOutputStream(file);
outputStreamWriter = new OutputStreamWriter(fileOutputStream);
outputStreamWriter.append("Your adress: " + adr + ". " + "Your latitude: " + lat + ", " + "longtitude: " + lon+".");
outputStreamWriter.close();
fileOutputStream.close();
}catch (Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
Thank you in advance
There are ample sources you can check for creating a folder, and uploading a file to Google Drive
Creating Folder
File fileMetadata = new File();
fileMetadata.setName("Invoices");
fileMetadata.setMimeType("application/vnd.google-apps.folder");
File file = driveService.files().create(fileMetadata)
.setFields("id")
.execute();
System.out.println("Folder ID: " + file.getId());
Uploading File
File fileMetadata = new File();
fileMetadata.setName("photo.jpg");
java.io.File filePath = new java.io.File("files/photo.jpg");
FileContent mediaContent = new FileContent("image/jpeg", filePath);
File file = driveService.files().create(fileMetadata, mediaContent)
.setFields("id")
.execute();
System.out.println("File ID: " + file.getId());
For the specific mime type of a txt file, you might need to refer this StackOverflow post (text/plain). For specific Google applications mime types, please see documentation.

Gallery doesn't refresh using MediaScan

I have the following Java code which downloads an image from an URL.
I can see the image downloaded in the folder, but the image does not appear in gallery. Only if I restart phone, Samsung S7 with android 7, I can see images in gallery. What can I do to have the images in gallery in real time after I downloaded them?
public class DetailsImgActivity extends AppCompatActivity {
private static final String TAG = "DetailsImgActivity";
private ImageView imageViewPoze;
private Button buttonDownload;
private static final int PERMISSION_REQUEST_CODE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details_img);
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
}
// image url stored in imageID
final String imageId = getIntent().getStringExtra("ImageId");
imageViewPoze = findViewById(R.id.imageViewPozeC);
Picasso.get().load(imageId).into(imageViewPoze);
buttonDownload = findViewById(R.id.btn_Download_Img);
buttonDownload.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
downloadFile(imageId);
}
});
}
private void downloadFile(String url) {
Retrofit.Builder builder = new Retrofit.Builder().baseUrl("https://firebasestorage.blabla.com/");
Retrofit retrofit = builder.build();
FileDownloadClient fileDownloadClient = retrofit.create(FileDownloadClient.class);
Call<ResponseBody> call = fileDownloadClient.downloadFile(url);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) {
// if (response.isSuccess()) {
Log.d(TAG, "server contacted and has file");
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... voids) {
boolean writtenToDisk = writeResponseBodyToDisk(response.body());
return null;
}
}.execute();
//after the image has been downloaded -refresh gallery
**Toast.makeText(getApplicationContext(), "File downloaded with success!", Toast.LENGTH_LONG).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
{
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File("file://"+ Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES));
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
sendBroadcast(mediaScanIntent);
}
else
{
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
}**
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e(TAG, "error");
}
});
}
private boolean writeResponseBodyToDisk(ResponseBody body) {
try {
String folder_main = Constants.dirName;
File f = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), folder_main);
if (!f.exists()) {
f.mkdirs();
}
// todo change the file location/name according to your needs
File futureStudioIconFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM+"/"+ Constants.dirName)
+ File.separator + UUID.randomUUID()+".jpg");
InputStream inputStream = null;
OutputStream outputStream = null;
try {
byte[] fileReader = new byte[4096];
long fileSize = body.contentLength();
long fileSizeDownloaded = 0;
inputStream = body.byteStream();
outputStream = new FileOutputStream(futureStudioIconFile);
while (true) {
int read = inputStream.read(fileReader);
if (read == -1) {
break;
}
outputStream.write(fileReader, 0, read);
fileSizeDownloaded += read;
Log.d(TAG, "file download: " + fileSizeDownloaded + " of " + fileSize);
}
outputStream.flush();
return true;
} catch (IOException e) {
return false;
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
} catch (IOException e) {
return false;
}
}
}
I used the follwing code, but If I don't reboot phone, I can't see the picture in gallery.
**Toast.makeText(getApplicationContext(), "File downloaded with success!", Toast.LENGTH_LONG).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
{
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File("file://"+ Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES));
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
sendBroadcast(mediaScanIntent);
}
else
{
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
}**

upload file(image) into quickblox custom object

How do I upload file (image) that I have his Uri, into custom object?
I've tried this:
public void onClick(View v) {
HashMap<String, Object> fields = new HashMap<String, Object>();
File newImage = new File(imageUri.toString());
fields.put("image", newImage);
fields.put("bla", "bla");
QBCustomObject qbCustomObject = new QBCustomObject();
qbCustomObject.setClassName("imageClass"); // your Class name
qbCustomObject.setFields(fields);
QBCustomObjects.createObject(qbCustomObject, new QBCallbackImpl() {
#Override
public void onComplete(Result result) {
if (result.isSuccess()) {
QBCustomObjectResult qbCustomObjectResult = (QBCustomObjectResult) result;
QBCustomObject qbCustomObject = qbCustomObjectResult.getCustomObject();
// Log.d("New record: ",newCustomObject.toString());
} else {
Log.e("Errors",result.getErrors().toString());
}
}
});
And I get just the string ("bla") and the image get - null
Thank you
Currently this feature is in development brunch. Will be in master in a couple of days
But you can use it already - Download SDK from development brunch
https://github.com/QuickBlox/quickblox-android-sdk/tree/development
Here are lots of snippets, especially for Custom Objects module
https://github.com/QuickBlox/quickblox-android-sdk/blob/development/snippets/src/com/quickblox/snippets/modules/SnippetsCustomObjects.java
Upload file
QBCustomObject qbCustomObject = new QBCustomObject(CLASS_NAME, NOTE1_ID);
QBCustomObjectsFiles.uploadFile(file1, qbCustomObject, AVATAR_FIELD, new QBCallbackImpl() {
#Override
public void onComplete(Result result) {
if (result.isSuccess()) {
QBCustomObjectFileField customObjectFileField = ((QBCOFileUploadResult) result).getCustomObjectFileField();
Log.i(TAG, ">>>upload response:" + customObjectFileField.getFileName() + " " + customObjectFileField.getFileId() + " " +
customObjectFileField.getContentType());
} else {
handleErrors(result);
}
}
});
Download file
QBCustomObject qbCustomObject = new QBCustomObject(CLASS_NAME, NOTE1_ID);
QBCustomObjectsFiles.downloadFile(qbCustomObject, AVATAR_FIELD, new QBCallbackImpl() {
#Override
public void onComplete(Result result) {
QBFileDownloadResult downloadResult = (QBFileDownloadResult) result;
if (result.isSuccess()) {
byte[] content = downloadResult.getContent(); // that's downloaded file content
InputStream is = downloadResult.getContentStream(); // that's downloaded file content
Log.i(TAG, ">>> file downloaded successfully" + getContentFromFile(is));
if(is!=null){
try{
is.close();
}catch(IOException e){
e.printStackTrace();
}
}
} else {
handleErrors(result);
}
}
});
Delete file
QBCustomObject qbCustomObject = new QBCustomObject(CLASS_NAME, NOTE1_ID);
QBCustomObjectsFiles.deleteFile(qbCustomObject, AVATAR_FIELD, new QBCallbackImpl() {
#Override
public void onComplete(Result result) {
if (result.isSuccess()) {
Log.i(TAG, ">>> file deleted successfully");
} else {
handleErrors(result);
}
}
});

Categories