I upload the file correctly, now I want to download, there are no errors but logcat says the download was done but I can not find the file in the phone memory
And other version this code generate an error
CODE:
public void download(){
try{
//DatabaseReference databaseReference= FirebaseDatabase.getInstance().getReference();
FirebaseStorage storage = FirebaseStorage.getInstance();
//StorageReference storageRef = storage.getReferenceFromUrl(url);
final StorageReference storageRef = storage
.getReferenceFromUrl("gs://the-piraty-book-alpha1.appspot.com/arquivos/")
.child(nome);
File storagePath = new File( Environment.getExternalStorageDirectory(),"TPB");
if(!storagePath.exists()) {
storagePath.mkdirs();
}
File localFile = null;
localFile = File.createTempFile("arquivo","pdf");
final File finalLocalFile = localFile;
FileDownloadTask task = storageRef.getFile(localFile);
task.addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
Log.e("firebase ",";local tem file created created " + finalLocalFile.toString());
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Log.e("firebase ",";local tem file not created created " +exception.toString());
}
});
}catch (IOException e){
}
}
10-01 13:35:51.118 31218-31218/ktm.com.menu E/firebase: ;local tem file created created /data/user/0/ktm.com.menu/cache/arquivo572065630pdf
not founding in my phone
,my manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.STORAGE" />
Related
I want to save my captured images to a specific directory (/sdcard/DCIM/FokusStacker) with the following method. I have tried different Locations, but none of them worked.
private void capturePicture(){
File dir = new File("/sdcard/DCIM/FokusStacker");
String fileName = "IMG_"+ System.currentTimeMillis();
File file = new File(dir,fileName);
Log.d(TAG, "capturePicture: DIRECTORY: "+dir.getAbsolutePath());
ImageCapture.OutputFileOptions outputFileOptions =
new ImageCapture.OutputFileOptions.Builder(file).build();
imageCapture.takePicture(outputFileOptions, ContextCompat.getMainExecutor(this), new ImageCapture.OnImageSavedCallback() {
#Override
public void onImageSaved(#NonNull ImageCapture.OutputFileResults outputFileResults) {
Log.d(TAG, "onImageSaved: SAVED");
return;
}
#Override
public void onError(#NonNull ImageCaptureException exception) {
Log.d(TAG, "onError: FAILED");
return;
}
});
}
These are the Permission i've included:
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
And i also tried saving it to the internal storage.
Code Snippet for to get the local directoryof the App for the file:
File dir = getApplicationContext().getFilesDir();
Can anyone please guide me how to do this?
I am a little new to android so please, I would appreciate if I can have a detailed procedure.
How to save bitmap to image file? (png/jpg any types don't care...)
I'm running device(hisilicon) & android app.
Android and device are communicating over sockets.
Device send Image (h.264) and show it on Android on TextureView.
I can get Bitmap from TextureView, using textureView.getBitmap().
I made a button button to save the picture, textureView.getBitmap().
<Button
android:id="#+id/btnSavePng"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onBtnSavePng"
android:text="savePicture" />
and, onclick function is like under.
public String getCurrentTimeString() {
int yyyy = Calendar.getInstance().get(Calendar.YEAR);
int MM = Calendar.getInstance().get(Calendar.MONTH) + 1;
int dd = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
int hh = Calendar.getInstance().get(Calendar.HOUR);
int mm = Calendar.getInstance().get(Calendar.MINUTE);
int ss = Calendar.getInstance().get(Calendar.SECOND);
String result = yyyy+"-"+MM+"-"+dd+" "+hh+":"+mm+":"+ss;
return result;
}
public void onBtnSavePng(View view) {
try {
File storage = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
String fname = getCurrentTimeString() + ".jpg";
File tp = new File(storage, fname);
Bitmap bm = textureView.getBitmap();
tp.createNewFile(); // Result of File.createNewFile() ignored
FileOutputStream ot = new FileOutputStream(tp);
bm.compress(Bitmap.CompressFormat.JPEG, 100, ot);
ot.close();
} catch(Exception e) {
Log.d("onBtnSavePng", e.toString()); // java.io.IOException: Operation not permitted
}
}
I allow uses-permissions AndroidManifest.xml like under, and android:requestLegacyExternalStorage="true" is on application.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.GET_TASKS" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
Is there any problem with my codes?
If so, how to save bitmap to png or jpg file?
I guess, my app don't access to directory.
Thank you for read my question.
Self Solved.
public void onBtnSavePng(View view) {
try {
String root = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES).toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
String fname = getCurrentTimeString() + ".jpg";
File file = new File(myDir, fname);
FileOutputStream out = new FileOutputStream(file);
Bitmap bm = textureView.getBitmap();
bm.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch( Exception e) {
Log.d("onBtnSavePng", e.toString());
}
I don't understand why my code is worked not yet.
Anyway, Thank you for all who helps me.
I'll try all of reply codes.
Thank you.
1.Check it if you don't request the runtime permission yet: https://developer.android.com/training/permissions/requesting
2.Or if your android is higher than 10:
https://developer.android.com/about/versions/11/privacy/storage#scoped-storage
After you update your app to target Android 11, the system ignores the requestLegacyExternalStorage flag.
Then you have to use SAF or MediaStore API to store the bitmap in the "public directory".
SAF:
https://developer.android.com/guide/topics/providers/document-provider
MediaStore API:
https://developer.android.com/reference/android/provider/MediaStore
public void onBtnSavePng(View view) {
try {
String fileName = getCurrentTimeString() + ".jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DISPLAY_NAME, fileName);
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpg");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
values.put(MediaStore.MediaColumns.RELATIVE_PATH, "DCIM/");
values.put(MediaStore.MediaColumns.IS_PENDING, 1);
} else {
File directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
File file = new File(directory, fileName);
values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
}
Uri uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
try (OutputStream output = getContentResolver().openOutputStream(uri)) {
Bitmap bm = textureView.getBitmap();
bm.compress(Bitmap.CompressFormat.JPEG, 100, output);
}
} catch (Exception e) {
Log.d("onBtnSavePng", e.toString()); // java.io.IOException: Operation not permitted
}
}
In kotlin
This is working for me->
fun saveMediaToStorage(bitmap: Bitmap, context: Context, onUriCreated: (Uri) -> Unit) {
var fos: OutputStream? = null
//Generating a file name
val filename = "${System.currentTimeMillis()}.jpg"
try {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.Q) {
val resolver = context.contentResolver
val contentValues = ContentValues()
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, "$filename.jpg")
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpg")
val imageUri =
resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)
fos = Objects.requireNonNull(imageUri)?.let {
resolver.openOutputStream(it)
}
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos)
Objects.requireNonNull(fos)
imageUri?.let { onUriCreated(it) }
} else {
//These for devices running on android < Q
val imagesDir =
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
val image = File(imagesDir, filename)
fos = FileOutputStream(image)
fos.use {
//Finally writing the bitmap to the output stream that we opened
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, it)
}
onUriCreated(Uri.fromFile(image))
}
} catch (e: Exception) {
Log.d("error", e.toString())
}
}
String myDir =new File (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)+pdfDirectoryImage);
fileName = filename + ".png";
androidElevenPath = saveImages(mContext,finalBitmap,filename);
private static Uri saveImages(Context mContext, Bitmap bitmap, #NonNull String name) throws IOException {
boolean saved;
OutputStream fos;
File image = null;
Uri imageUri = null;
String imagesDir = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ContentResolver resolver = mContext.getContentResolver();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, name);
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/png");
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, "DCIM" + pdfDirectoryImage);
imageUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
fos = resolver.openOutputStream(imageUri);
} else {
imagesDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM).toString() + File.separator + pdfDirectoryImage;
File file = new File(imagesDir);
if (!file.exists()) {
file.mkdir();
}
image = new File(imagesDir, name + ".png");
fos = new FileOutputStream(image);
}
saved = bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
return imageUri;
}
In case you are on Android11+ and you have the storage manager permission granted and are working directly with files (and not the MediaStore API) the cause could be a ":" char (usually from a timestamp) in the name of the created file. Android 11 (unlike older Android versions) does not allow that.
What am I doing wrong?
I have tried googlign the problem, but people mostly say it is an issue with android Q, but I don't think my problem is that.
AndroidManifest.xml:
<manifest ...>
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest>
Java:
void takePhoto(){
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.CAMERA},2);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null)
{
File photoFile = createPhotoFile();
if(photoFile != null){
pathToFile = photoFile.getAbsolutePath();
Uri photoURI = getUriForFile(this, this.getPackageName() + ".fileprovider", photoFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(intent, REQUEST_CAMERA);
}
}
}
private File createPhotoFile() {
String name = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File storageDir = getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File image = null;
try{
image = File.createTempFile(name, ".jpg", storageDir);
} catch(IOException e){
Log.d("myLog", "Except: " + e.toString());
}
return image;
}
I should generate a .pdf file inside the android data folder to use the Java code below, with the permissions enabled in the XML manifest file. But when I run the code I have the following exception. The application has different permissions within the manifest, It should all be configured correctly, I state that the application I'm testing on an old Android 4. How can I solve this? and what is it due to?
Exception: error: java. I. FileNotFoundException: /data/my.pdf:
open failed: EACCES (Permission denied)
Code:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE " />
public static Boolean GeneratePDF(String base64) {
Boolean ret = true;
try {
String direttorio=""+Environment.getDataDirectory().getAbsolutePath();
final File dwldsPath = new File(direttorio + "/" + "my.pdf");
byte[] pdfAsBytes = Base64.decode(base64, 0);
FileOutputStream os;
os = new FileOutputStream(dwldsPath, false);
os.write(pdfAsBytes);
os.flush();
os.close();
} catch (Exception ex) {
System.out.println("\n Errore Generazione File: "+ex);
ret = false;
}
return ret;
}
you have to give Write permission at run time.
It can be achieved something as following...
public class MainActivity extends AppCompatActivity implements ActivityCompat.OnRequestPermissionsResultCallback{
private static final int REQUEST_WRITE_PERMISSION = 111;
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == REQUEST_WRITE_PERMISSION && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
GeneratePDF("your String name");
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
requestPermission();
}
private void requestPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_PERMISSION);
} else {
GeneratePDF("your String name");
}
}
}
Replace this line
String direttorio=""+Environment.getDataDirectory().getAbsolutePath();
To:
String direttorio= Environment.getExternalStorageDirectory().getAbsolutePath();
final File dwldsPath = new File(direttorio + "/" + my.pdf");
if you're using Android 6.0 and above,
there could be 2 ways:
1 if you're making only for demo purpose you can manually give permission to app
by going in settings->apps->permissions. Then allow all permission which are
required.
2 you've to implement runtime permissions so that user can allow it runtime.
I want to use the file explorer in Android system to show the file I saved before.
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
startActivityForResult(intent, 1);
So, I think saving the data into SD card is the only way to achieve this. I've found many materials, but I always get the error that I don't have the permission to save the data into SD card. The error message is as follow.
01-17 23:35:44.184 6337-6337/? W/System.err: java.io.FileNotFoundException: /storage/emulated/0/rtd: open failed: EACCES (Permission denied)
01-17 23:35:44.184 6337-6337/? W/System.err: at libcore.io.IoBridge.open(IoBridge.java:452)
01-17 23:35:44.185 6337-6337/? W/System.err: at java.io.FileOutputStream.<init>(FileOutputStream.java:87)
01-17 23:35:44.185 6337-6337/? W/System.err: at java.io.FileOutputStream.<init>(FileOutputStream.java:72)
In fact I do add the permission lines in the AndroidManifest
</activity>
</application>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
</manifest>
So, can anyone help me figure out what I should do to fix this error?
Here is the code of my saving button
class ButtonClickListener2 implements View.OnClickListener{
#Override
public void onClick(View v){
// Intent intent = getIntent();
Name = getIntent().getStringExtra("Name");
Age = getIntent().getStringExtra("Age");
Movie = getIntent().getStringExtra("Movie");
File2 = getIntent().getStringExtra("File");
TextView txt = (TextView)findViewById(R.id.textView3);
txt.setText(Name+" "+ Age+ " "+Movie+" "+ File2);
String filename = File2.toString();
String Age_Content = Age.toString();
String Movie_Content = Movie.toString();
String Name_Content = Name.toString();
FileService service = new FileService(getApplicationContext());
try {
if(Environment.getExternalStorageState().equals(Environment.getExternalStorageState())){
service.save(filename, Age_Content, Movie_Content,Name_Content);
Toast.makeText(getApplicationContext(),R.string.SDCard_available,Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(),R.string.SDCard_protected,Toast.LENGTH_SHORT).show();
}
Toast.makeText(getApplicationContext(),R.string.success,Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),R.string.fail,Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}
class FileService {
private Context context;
public FileService (Context context) {
this.context = context;
}
public void save(String filename, String Age_content, String Movie_content, String Name_content) throws Exception{
//save the data into SD card
/* FileOutputStream outputStream = context.openFileOutput(filename,Context.MODE_APPEND);
outputStream.write(Age_content.getBytes());
outputStream.write(Movie_content.getBytes());
outputStream.write(Name_content.getBytes());
outputStream.close();*/
File file = new File(Environment.getExternalStorageDirectory(),filename);
FileOutputStream outputStream = new FileOutputStream(file);
outputStream.write(Age_content.getBytes());
outputStream.write(Movie_content.getBytes());
outputStream.write(Name_content.getBytes());
outputStream.close();
}
}
If you're using Android M, try this:
private final String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
requestPermissions(permissions, 2909);
Also, override the onRequestPermissionsResult method as follows:
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
Your activity must extend AppCompatActivity in order for this to work.
Android has introduced runtime permissions with version 6.0. You might want to look into it.
In your manifests file put the below code
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Check whether you used PERMISSIONS in AndroidManifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />