I have to place image from sd card to imageview in android
I tried using getExternalStorageDirectory(). It is showing deprecated method. It is not working.
MainActivity
public class MainActivity extends Activity {
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView)findViewById(R.id.imageView1);
try {
Bitmap picture = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory().getPath()+"/DCIM/mm.png");
imageView.setImageBitmap(picture);
} catch (Exception e) {
Log.e("Error reading file", e.toString());
}
// File imgFile = new File("/sdcard/DCIM/mm.png");
//
// if(imgFile.exists()) {
//
// Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
//
// imageView.setImageBitmap(myBitmap);
// }
}
}
xml file
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity"
android:orientation = "vertical">
<ImageView
android:id = "#+id/imageView1"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
/>
</LinearLayout>
I tried many ways. But it is not working. Kindly suggest me to do this.
Manifest Add this permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
declare this on your Activity:
String[] PERMISSIONS = {android.Manifest.permission.WRITE_EXTERNAL_STORAGE,android.Manifest.permission.READ_EXTERNAL_STORAGE};
private Context mContext=MainActivity.this;
private static final int REQUEST = 112;
static ImageView muyimage;
in Oncreate();
muyimage=(ImageView)findViewById(R.id.myimge);
if (Build.VERSION.SDK_INT >= 23) {
String[] PERMISSIONS = {android.Manifest.permission.WRITE_EXTERNAL_STORAGE};
if (!hasPermissions(mContext, PERMISSIONS)) {
ActivityCompat.requestPermissions((Activity) mContext, PERMISSIONS, REQUEST );
} else {
try {
//here i have mentioned my image path ,you have to set your image path
Bitmap picture = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory().getPath()+"/Pictures/Screenshots/mine.png");
muyimage.setImageBitmap(picture);
} catch (Exception e) {
Log.e("Error reading file", e.toString());
}
}
} else {
try {
//here i have mentioned my image path ,you have to set your image path
Bitmap picture = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory().getPath()+"/Pictures/Screenshots/mine.png");
muyimage.setImageBitmap(picture);
} catch (Exception e) {
Log.e("Error reading file", e.toString());
}
}
And this
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//do here
} else {
Toast.makeText(mContext, "The app was not allowed to write in your storage", Toast.LENGTH_LONG).show();
}
}
}
}
private static boolean hasPermissions(Context context, String... permissions) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
try {
//here i have mentioned my image path ,you have to set your image path
Bitmap picture = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory().getPath()+"/Pictures/Screenshots/mine.png");
muyimage.setImageBitmap(picture);
} catch (Exception e) {
Log.e("Error reading file", e.toString());
}
return false;
}
}
}
return true;
}
Environment.getExternalStorageDirectory() returns the primary storage directory of the phone (/storage/emulated/0/) not SD card. The path of SD card storage varies from phone to phone and it depends on manufactures how to implement it. Sometimes SD card mounts to a folder with different names in /storage directory and sometimes in /mnt directory. Starting from Android KitKat (API 19) you have access to getExternalFilesDirs method to get storages directory but there isn't any official solution to work in all phones and android versions. Most of the time SD card mounts to /storage directory so I wrote a solution that works in the android emulator and most of the Android phones but it doesn't guarantee all possibilities. You could change your code like so:
public class MainActivity extends AppCompatActivity {
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView)findViewById(R.id.imageView1);
File storageDir = new File("/storage/");
if(storageDir.exists()){
String[] dirList = storageDir.list();
for (String dir: dirList){
if(!(dir.equals("emulated") || dir.equals("self"))){
File file = new File( "/storage/" + dir + "/DCIM/" + "mm.png");
if(file.exists()) {
Bitmap picture = BitmapFactory.decodeFile(file.getAbsolutePath());
imageView.setImageBitmap(picture);
break;
}
}
}
}
}
}
Related
In one of my activities, I save an image in my App's directory subfolder and in the next activity I read the .png file and include it in a pdf file with some other data and save it in my App's directory, Everything worked fine until I updated my phone from Android 10 to 11. Now I get this error:
E/main: error java.io.FileNotFoundException: /storage/emulated/0/IranianMasonryBuildings/sjdnnd -- Fri Feb 12 11:49:36 GMT+03:30 2021.pdf: open failed: EPERM (Operation not permitted)
I tried many fixes online but none of them seem to work.
My manifest includes theses permissions and also the requestLegacyExternalStorage = true
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
android:requestLegacyExternalStorage="true"
compileSdkVersion and targetSdkVersion are set to 29, I tried to change the API level to 28 as mentioned in some answers to other questions but did not work.
This is how I try to create the pdf file:
private boolean isExternalStorageWritable(){
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
Log.i("State", "Yes, it is writable");
return true;
}else{
return false;
}
}
public boolean checkPermission(String permission){
int check = ContextCompat.checkSelfPermission(this, permission);
return (check == PackageManager.PERMISSION_GRANTED);
}
public void checkPermission(String permission, int requestCode)
{
if (ContextCompat.checkSelfPermission(Results.this, permission)
== PackageManager.PERMISSION_DENIED) {
// Requesting the permission
ActivityCompat.requestPermissions(Results.this,
new String[] { permission },
requestCode);
}
else {
/*Toast.makeText(Results.this,
"Permission already granted",
Toast.LENGTH_SHORT)
.show();*/
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == STORAGE_PERMISSION_CODE){
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
/*Toast.makeText(Results.this,
"Storage Permission Granted",
Toast.LENGTH_SHORT)
.show();*/
}
else {
Toast.makeText(Results.this,
"Please grant access",
Toast.LENGTH_SHORT)
.show();
}
}
}
// Storage Permissions
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
public static void verifyStoragePermissions(Activity activity) {
// Check if we have write permission
int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(
activity,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE
);
}
}
public void writeExternalStorage (){
String state;
state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) &&
checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
try {
//File storageDir2 = new File(Environment.getExternalStorageDirectory().toString(),
"/IranianMasonryBuildings/BluePrints");
File storageDir2 = new File(Environment.getExternalStorageDirectory().toString(),
"/IranianMasonryBuildings");
File f = new File(storageDir2, "BluePrint213.png");
Bitmap blueprint2 = BitmapFactory.decodeStream(new FileInputStream(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
PdfDocument myPdfDocument = new PdfDocument();
Paint myPaint = new Paint();
// Create a page description
PdfDocument.PageInfo myPageInfo1 = new PdfDocument.PageInfo.Builder(PageWidth,
PageHeight, PageNumber).create();
// start a page
PdfDocument.Page myPage1 = myPdfDocument.startPage(myPageInfo1);
Canvas canvas = myPage1.getCanvas();
myPaint = new Paint();
myPaint.setStyle(Paint.Style.STROKE);
myPaint.setStrokeWidth(3);
canvas.drawRect(200, 250, 1900, 2600, myPaint);
myPdfDocument.finishPage(myPage1);
File storageDir = new File(Environment.getExternalStorageDirectory().toString(),
"/IranianMasonryBuildings");
storageDir.mkdirs(); // make sure you call mkdirs() and not mkdir()
boolean wasSuccessful = storageDir.mkdirs();
if (!wasSuccessful) {
//Toast.makeText(getApplicationContext(), "mkdirs was not Successful ",
Toast.LENGTH_LONG).show();
}
File file2 = new File(storageDir, ProjectName + " -- " + Today + ".pdf");
try {
myPdfDocument.writeTo(new FileOutputStream(file2));
Toast.makeText(this, "The results are saved in" + "IranianMasonryBuildings",
Toast.LENGTH_LONG).show();
} catch (IOException e) {
Log.e("main", "error " + e.toString());
Toast.makeText(this, "Error!" + e.toString(), Toast.LENGTH_LONG).show();
}
// close the document
myPdfDocument.close();
Any ideas what is causing the problem and how to fix?
Android 11 (API level 30) further enhances the platform, giving better protection to app and user data on external storage. This release introduces several enhancements, such as opt-in raw file path access for media, batch edit operations for media, and an updated UI for the Storage Access Framework.
Follow this link
https://developer.android.com/about/versions/11/privacy/storage
I am developing and android application with emulator of Android Studio 3.6. I am using a virtual device of Nexus 7 with andoird 10.
I have given permission on the manifest file and I have asked for the user to give permission for read write to the external storage.
Although permissions are ok I can not create a folder on the external storage. I attempt to write form a background proccess.
This is the excerpt og manifest file
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
This is the excerpt of my Main Activity where I ask the the user to give permission and call the background proccess: UnitDataUpdater
public class MainActivity extends AppCompatActivity {
public static final String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
public static final int MY_PERMISSIONS_REQUEST_EXTERNAL_STORAGE = 1;
// public static String SERVER_API_URL = "http://local.xxxx.xxxxx.eu/index.php?option=com_alumincocc&view=examlist&Itemid=122&format=json&unitCode=";
// public static LinearLayout examList;
public JSONArray uiData;
ListView examsList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
checkPermissions();
setContentView(R.layout.activity_main);
String url = "http://xxxxx.xxxxx.eu/index.php?option=com_alumincocc&view=examlist&Itemid=122&format=json&unitCode=478050";
String result = "";
examsList = (ListView) findViewById(R.id.examsList);
UnitDataUpdater process = new UnitDataUpdater(this);
try {
result = process.execute(url).get();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
........
public void checkPermissions() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED
||
ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_EXTERNAL_STORAGE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
#NonNull String[] permissions,
#NonNull int[] grantResults) {
super
.onRequestPermissionsResult(requestCode,
permissions,
grantResults);
if (requestCode == MY_PERMISSIONS_REQUEST_EXTERNAL_STORAGE) {
// Checking whether user granted the permission or not.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Showing the toast message
Toast.makeText(MainActivity.this,
"Write Permission Granted",
Toast.LENGTH_SHORT)
.show();
} else {
Toast.makeText(MainActivity.this,
"Write Permission Denied",
Toast.LENGTH_SHORT)
.show();
}
}
}
}
And this is the background process where I try to write to the external storage. The method getAppDi is where I am trying to create a new folder. This folder is never created so the rest of the class throws errors.
A strange thing is that at the emulator I don't see the Document folder. I have try the same thing on Downloads folder but still the same.
public class UnitDataUpdater extends AsyncTask<String, Void, String> {
// private static String REMOTE_URL = "http://local.xxxxxx.xxxxx.eu/index.php?option=com_alumincocc&view=examlist&Itemid=122&format=json&unitCode=";
private String data = "";
public static final String REQUEST_METHOD = "GET";
public static final int READ_TIMEOUT = 15000;
public static final int CONNECTION_TIMEOUT = 15000;
private String filePrefix = "i";
private MainActivity mainActivity;
public UnitDataUpdater(Activity mainActivity) {
this.mainActivity = (MainActivity) mainActivity;
}
........
private String getAppDir() {
String externalStoragePublicDirectory = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
.getAbsolutePath();
String appDirPath = externalStoragePublicDirectory + "/XXXXUnitData";
File appDir = new File(appDirPath);
if (!appDir.exists()) {
if (!appDir.mkdir()) {
try {
throw new Exception("Storage Error");
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
return appDir.getAbsolutePath();
}
}
Any help is appreciated
On Android Q external storage is not readable and writable. Use getExternalFilesDir(null) instead. You do not need any read write permission then in manifest or at runtime.
I tried to delete the image file from the gallery, but it won't. Image files are output normally, and sharing functions are done. It can't write and delete in my App. Files are deleted from the default app.
I tried to delete it use File class and ContentResolver. but file has not been deleted.
Android targetSdkVersion is 26 and compileSdkVersion is 28.
Manifest
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
I get SDcard path from getSDcardPath()
public String getSDcardPath(Context context) {
File[] storage = ContextCompat.getExternalFileDirs(context, null);
if(storage.length > 1 && storage[0] != null && storage[1] != null)
return storage[1].toString();
else
return "";
}
File Class code Used
public void useFileClass() {
File mFile = new File("file Parent + file NAME");
if (mFile.exists()) {
mFile.delete();
}
}
ContentResolver code Used
public void useContentResolver(Context context, File mFile) {
ContentResolver contentResolver = context.getContentResolver();
Uri mUri = getUri(context, mFile);
contentResolver.delete(mUri, null, null);
}
public Uri getUri(Context context, File mFile) {
Uri mUri;
mUri = FileProvider.getUriForFile(context, "MyApplication", mFile);
return mUri;
}
share code
public void shareImage() {
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setType("image/*");
shareIntent.putExtra(Intent.EXTRA_STREAM, getUri(this, mFile));
startActivity(Intent.createChooser(shareIntent, "Share image too..."));
}
You need request Permission before access into storage. Try this:
private static final int MY_WRITE_STORAGE_PERMISSION_CODE = 200;
private void checkPermission() {
if (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_WRITE_STORAGE_PERMISSION_CODE);
} else {
// Todo (Add, Delete, Edit, ...)
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == MY_WRITE_STORAGE_PERMISSION_CODE)
{
if (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
// Todo (Add, Delete, Edit, ...)
} else {
// Permission Deny
}
}
}
Hope this help you.
This code works correctly under 6.0.1 android version but if i run this application on 6.0.1 android devices , it will not save images to sd card.
What i need to update for 6.0.1 devices ?
public void SaveImages(int a ,String b)
{
Bitmap bitmap = null;
OutputStream output;
if(a==0)
{
bitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.image_0);
}
File filepath = Environment.getExternalStorageDirectory();
// Create a new folder in SD Card
File dir = new File(filepath.getAbsolutePath()
+ "/Wallpapers/");
dir.mkdirs();
// Create a name for the saved image
File file = new File(dir,b);
// Show a toast message on successful save
Toast.makeText(FullImageActivity.this, "Loading...",
Toast.LENGTH_SHORT).show();
Toast.makeText(FullImageActivity.this, "Image Saved to SD Card",
Toast.LENGTH_SHORT).show();
try {
output = new FileOutputStream(file);
// Compress into png format image from 0% - 100%
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, output);
output.flush();
output.close();
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
On Android 6.0+, you need to request runtime permission to write to external storage.
In order to request runtime permission to write to external storage:
public class MarshmallowPermission {
public static final int EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE = 2;
public MarshmallowPermission() {
}
public boolean checkPermissionForExternalStorage(Activity activity) {
if(Build.VERSION.SDK_INT >= 23) {
int result = ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if(result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
} else {
return true;
}
}
public void requestPermissionForExternalStorage(Activity activity) {
if(ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Toast.makeText(activity,
"External Storage permission needed. Please allow in App Settings for additional functionality.",
Toast.LENGTH_LONG).show();
// user has previously denied runtime permission to external storage
} else {
ActivityCompat.requestPermissions(activity,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE);
}
}
}
Then you can do
if(!marshmallowPermission.checkPermissionForExternalStorage(this)) {
marshmallowPermission.requestPermissionForExternalStorage(this);
} else {
// can write to external
}
And
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == MarshmallowPermission.EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE) {
if(marshmallowPermission.checkPermissionForExternalStorage(this)) {
// can write to external
} else {
// runtime permission denied, user must enable permission manually
}
}
}
Refer the following link,
How to save the image to SD card on button Click android. and
Saving image from image view to sd card : Android.
For detailed tutorial,
http://www.android-examples.com/save-store-image-to-external-storage-android-example-tutorial/
I use this simple code for capturing Image from camera. I have found this issue a lot and try many methods but cannot solve this issue.
My Image is mostly PDF when i capture it It become unreadable due to worse pixels
private static final int CAMERA_REQUEST = 1888;
private ImageView imageView;
private static final int MY_CAMERA_PERMISSION_CODE = 100;
ImageView Image;
private static final int REQUEST_CAPTURE_IMAGE = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera_test);
Image = (ImageView) findViewById(R.id.Image);
Button camera = (Button) findViewById(R.id.camera);
camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)
{
requestPermissions(new String[]{Manifest.permission.CAMERA}, MY_CAMERA_PERMISSION_CODE);
}
else
{
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
}
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults)
{
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == MY_CAMERA_PERMISSION_CODE)
{
if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(this, "camera permission granted", Toast.LENGTH_LONG).show();
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
else
{
Toast.makeText(this, "camera permission denied", Toast.LENGTH_LONG).show();
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK)
{
Bitmap photo = (Bitmap) data.getExtras().get("data");
Image.setImageBitmap(photo);
}
}
I use this simple code for capturing Image from camera. I have found this issue a lot and try many methods but cannot solve this issue.
My Image is mostly PDF when i capture it It become unreadable due to worse pixels
If you need your image in best quality, you need to save it to a file, otherwise you can just access the thumbnail (low res image). I will share how I did it.
Inside your manifest, you need to define a file provider inside application tag, permissions also.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<application...>
...
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="{your package name}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_path" />
</provider>
</application>
You will also need to make a FileProvider in your res/xml folder. Mine looks like this:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="/storage/emulated/0/Pictures/" path="Pictures/"/>
</paths>
Please do more research, where do you want to save your photos, in my example you can save them only to SD card, but there are more options.
Now, taking photo and saving it.
private var currentPhotoUri = Uri.EMPTY
private var currentPhotoPath
private val requestCode = 123
private fun dispatchTakePictureIntent() {
Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePictureIntent ->
// Ensure that there's a camera activity to handle the intent
takePictureIntent.resolveActivity(activity?.packageManager!!)?.also {
createFile()
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, currentFileUri)
startActivityForResult(takePictureIntent, requestCode)
}
}
}
private fun createFile(): File? {
val photoFile: File? = try {
createImageFile()
} catch (ex: IOException) {
Log.i("mylog error", "Error creating file: " + ex.toString())
ex.printStackTrace()
null
}
// Continue only if the File was successfully created
photoFile?.also {
val photoURI: Uri = context?.let { context ->
FileProvider.getUriForFile(
context,
"{your package name}.fileprovider",
it
)
} as Uri
currentPhotoUri = photoURI
}
return photoFile
}
private fun createImageFile(): File {
val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
val storageDir: File? = context!!.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
Log.i("mylog", "storage dir = " + storageDir?.absolutePath)
return File.createTempFile(
"JPEG_${timeStamp}_", /* prefix */
".jpg", /* suffix */
storageDir /* directory */
).apply {
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = absolutePath
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent)
{
if (requestCode == requestCode && resultCode == RESULT_OK) {
val bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(),currentPhotoUri)
val imageView = findViewById(R.id.Image)
imageView.setImageBitmap(bitmap)
}
}
That should work. Dont forget to check permissions. You can learn more here.
The object which you have in intent data is a thumbnail of this image. When you capture the photo you should specify path to file . You can also use CameraX API.