This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I was trying to make the camera intent work on higher APIs but its crashing when i try to. I think there is something wrong with some paths but i cant figure out what. Its running fine with API 23.
FATAL EXCEPTION: main
Process: ur.mi.android.wgplus05, PID: 22088
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.XmlResourceParser android.content.pm.PackageItemInfo.loadXmlMetaData(android.content.pm.PackageManager, java.lang.String)' on a null object reference
at android.support.v4.content.FileProvider.parsePathStrategy(FileProvider.java:583)
at android.support.v4.content.FileProvider.getPathStrategy(FileProvider.java:557)
at android.support.v4.content.FileProvider.getUriForFile(FileProvider.java:399)
at ur.mi.android.wgplus05.Camera.takePicture(Camera.java:50)
at ur.mi.android.wgplus05.PictureActivity.takePicture(PictureActivity.java:148)
at ur.mi.android.wgplus05.PictureActivity.checkPermission(PictureActivity.java:140)
at ur.mi.android.wgplus05.PictureActivity.onOptionsItemSelected(PictureActivity.java:101)
at android.app.Activity.onMenuItemSelected(Activity.java:3204)
at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:408)
at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:195)
at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:113)
at android.support.v7.app.AppCompatDelegateImplV9.onMenuItemSelected(AppCompatDelegateImplV9.java:679)
at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:822)
at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:156)
at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:969)
at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:959)
at android.support.v7.widget.ActionMenuView.invokeItem(ActionMenuView.java:623)
at android.support.v7.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:154)
at android.view.View.performClick(View.java:5610)
at android.view.View$PerformClick.run(View.java:22260)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Line 50:
Uri photoURI = FileProvider.getUriForFile(activityContext,
BuildConfig.APPLICATION_ID + ".genericfileprovider",
photoFile);
public class Camera {
PictureActivity activityContext;
private String currentPhotoPath;
public Camera(PictureActivity activityContext) {
this.activityContext = activityContext;
}
public void takePicture(int requestCode) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(activityContext.getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
return;
}
// Continue only if the File was successfully created
if (photoFile != null) {
if(Build.VERSION.SDK_INT < 24){
Uri photoURI = Uri.fromFile(photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
activityContext.startActivityForResult(takePictureIntent, requestCode);
}
else {
Uri photoURI = FileProvider.getUriForFile(activityContext,
BuildConfig.APPLICATION_ID + ".genericfileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
activityContext.startActivityForResult(takePictureIntent, requestCode);
}
}
}
}
public String getCurrentPhotoPath() {
return currentPhotoPath;
}
public Bitmap getScaledBitmap(String path, Point targetSize) {
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
int scaleFactor = Math.min(photoW / targetSize.x, photoH / targetSize.y);
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(path, bmOptions);
return bitmap;
}
private File createImageFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.ENGLISH).format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(imageFileName, ".jpg", storageDir);
currentPhotoPath = image.getAbsolutePath();
return image;
}
}
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<uses-feature android:name="android.hardware.camera"
android:required="true"/>
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_icon_hdx"
android:label="#string/app_name"
android:roundIcon="#drawable/ic_icon_hdx"
android:supportsRtl="true"
android:theme="#style/Theme.AppCompat.Light.DarkActionBar">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Finanzen" />
<activity android:name=".Einkaufsliste" />
<activity android:name=".Einkaufsliste2" />
<activity android:name=".toDoList" />
<activity android:name=".Settings" />
<activity android:name=".PictureActivity" />
<activity
android:name=".Putzplan"
android:windowSoftInputMode="adjustResize" />
<activity android:name=".Kalender" />
<provider
android:name=".GenericFileProvider"
android:authorities="${applicationId}.ur.mi.android.wgplus05.genericfileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths"/>
</provider>
</application>
</manifest>
thats path
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
android:authorities="${applicationId}.ur.mi.android.wgplus05.genericfileprovider"
BuildConfig.APPLICATION_ID + ".genericfileprovider"
These do not match. They need to match. Otherwise, FileProvider cannot find the ContentProvider, because you provided an invalid authority name to getUriForFile().
So, for example, you could change the first line to:
android:authorities="${applicationId}.genericfileprovider"
Then, the two values would match (application ID plus .genericfileprovider).
The second argument in getUriForFile should match the authorities attribute from the xml.
BuildConfig.APPLICATION_ID + ".ur.mi.android.wgplus05.genericfileprovider"
Related
failed to try to share file via fileprovider, I don't know what I'm doing wrong. mistake (java.lang.IllegalArgumentException: Failed to find configured root that contains /storage/emulated/0/Download/Teste2.txt).
I tried to use the code according to the link: https: //developer.android.com/reference/androidx/core/content/FileProvider and I was not successful
in the previous versions without the fileprovider it worked perfectly using Intent.EXTRA_STREAM now in the android version 11 I was unable to make it work anymore
my code down
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:dist="http://schemas.android.com/apk/distribution"
package="com.login.projetobase">
<dist:module dist:instant="true" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme"
android:restoreNeedsApplication="true">
<!-- android.support.v4.content.FileProvider / androidx.core.content.FileProvider -->
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.login.projetobase.FileProvider"
android:exported="false"
android:grantUriPermissions="true" >
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths" />
</provider>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<!-- GRUPO STORAGE -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_MEDIA_LOCATION" />
</manifest>
provider_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path
name="Download"
path="/" />
</paths>
MainActivity.java
public class MainActivity extends Activity {
String P_ACTIVITY = "MainActivity";
util utl = new util();
String ativa_log = "S";
File sdcard_sdk29;
private static java.io.File sdcard;
Button btn ;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.btn01);
btn.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.Q)
public void onClick(View v) {
utl.PRINT_LOG(1, P_ACTIVITY+"btn.setOnClickListener-> **** INICIOU ****", ativa_log);
COMPARTILHA();
}
});
}
public void COMPARTILHA() {
try {
utl.PRINT_LOG(2, P_ACTIVITY + " COMPARTILHA() ...... INICIADO", ativa_log);
String NOME_ARQ = "Teste2.txt";
String texto = "Teste de compartilhamento";
File arq;
byte[] dados;
String RAIZ3 = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString();
// CRIA O ARQUIVO NA PASTA DOWNLOAD
arq = new File(RAIZ3 , NOME_ARQ);
utl.PRINT_LOG(2, P_ACTIVITY + " COMPARTILHA()-> DIRETORIO = ["+RAIZ3.toString()+"]", ativa_log);
FileOutputStream fos;
dados = texto.getBytes();
fos = new FileOutputStream(arq);
fos.write(dados);
fos.flush();
fos.close();
//INICIANDO O PROCESSO DE COMPARTILHAR AQUIVO
//Uri arquivo = Uri.fromFile(arq);
//Uri arquivo2 = Uri.parse(arq.toString());
Context context = getApplicationContext();
Uri contentUri = FileProvider.getUriForFile(context, "com.login.projetobase.FileProvider", arq);
utl.PRINT_LOG(2, P_ACTIVITY + " COMPARTILHA2()-> CAMINHO URI = ["+contentUri.toString()+"]", ativa_log);
utl.PRINT_LOG(2, P_ACTIVITY + " COMPARTILHA2()-> processando.....", ativa_log);
final Intent _intent = new Intent();
_intent.setAction(Intent.ACTION_SEND);
_intent.setType("application/pdf");
_intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION|Intent.FLAG_GRANT_READ_URI_PERMISSION);
_intent.putExtra(Intent.EXTRA_TEXT, "Compartilhamento com anexo");
_intent.putExtra(Intent.EXTRA_TITLE, "Teste de Compartilhamento");
_intent.putExtra(Intent.EXTRA_STREAM, contentUri);
startActivity(Intent.createChooser(_intent, "Compartilhar"));
} catch (Exception e) {
utl.PRINT_LOG(3, P_ACTIVITY + " ERRO->"+e, ativa_log);
Toast.makeText(getApplication(), "ERRO="+e, Toast.LENGTH_LONG).show();
}
}
}
There are many questions and answers about this topic on the internet but unfortunately it didnt solve my problem.
I get a error every time I try to intent a Camera for a picture of video recording within my Fragment.
The path where I want to save those files are in /data/data/com.example.testing/files/*
The error that I always get is: Failed to find configured root that "contains/data/data/com.example.testing/files/test.jpg" and "Failed to find configured root that contains/data/data/com.example.testing/files/test.mp4"
The complete error log:
2020-12-16 00:14:32.093 6473-6473/com.example.testing E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.testing, PID: 6473
java.lang.IllegalArgumentException: Failed to find configured root that contains /data/data/com.example.testing/files/test.jpg
at androidx.core.content.FileProvider$SimplePathStrategy.getUriForFile(FileProvider.java:744)
at androidx.core.content.FileProvider.getUriForFile(FileProvider.java:418)
at com.example.testing.fragments.InvitesCheck.capturePhoto(InvitesCheck.kt:141)
at com.example.testing.fragments.InvitesCheck.access$capturePhoto(InvitesCheck.kt:32)
at com.example.testing.fragments.InvitesCheck$onViewCreated$1.onClick(InvitesCheck.kt:53)
at android.view.View.performClick(View.java:7192)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:992)
at android.view.View.performClickInternal(View.java:7166)
at android.view.View.access$3500(View.java:824)
at android.view.View$PerformClick.run(View.java:27592)
at android.os.Handler.handleCallback(Handler.java:888)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:8178)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1101)
I tried different setups but unfortunately no luck.
This is my Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.testing">
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-feature android:name="android.hardware.camera" />
<application
android:allowBackup="false"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.Testing">
<activity
android:name=".MainActivity"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths" />
</provider>
</application>
</manifest>
I am using the following functions to call the camera:
private fun capturePhoto() {
val file = File(requireContext().filesDir.path, "test.jpg")
val uri = FileProvider.getUriForFile(requireActivity(), BuildConfig.APPLICATION_ID.toString() + ".provider", file)
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri)
startActivityForResult(intent, REQUEST_CODE)
}
private fun captureVideo() {
val file = File(requireContext().filesDir.path, "test.mp4")
val uri = FileProvider.getUriForFile(requireActivity(), BuildConfig.APPLICATION_ID.toString() + ".provider", file)
val intent = Intent(MediaStore.ACTION_VIDEO_CAPTURE)
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 10);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri)
startActivityForResult(intent, REQUEST_VIDEO)
}
xml/provider_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path name="external_files" path="."/>
</paths>
What am I doing wrong?
Thank you in advance.
Reading up on this question, it seems that you should be using Context.getExternalFilesDir() instead of Context.getFilesDir()` whenever you're creating the File to which to write to.
This would end up looking something like this:
private fun capturePhoto() {
val file = File(requireContext().getExternalFilesDir(null).path, "test.jpg")
val uri = FileProvider.getUriForFile(requireActivity(), BuildConfig.APPLICATION_ID.toString() + ".provider", file)
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri)
startActivityForResult(intent, REQUEST_CODE)
}
BONUS: I would recommend you take a look at the MediaStore class if you're planning on making a media-oriented app. Here's an official intro for it.
I want to open camera, click and upload the full image to a server. For that, I'm trying to save the image to a location and then upload it from another method. I have been receiving this error in getting the fileprovider to work, and have tried various stack overflow solutions but none seem to work for me.
java.lang.IllegalArgumentException: Failed to find configured root that contains /storage/emulated/0/Android/data/com.learning.speeeddy.imagereader.app/files/Pictures/IMG_20180627_132113_1596259289.jpg
at android.support.v4.content.FileProvider$SimplePathStrategy.getUriForFile(FileProvider.java:738)
at android.support.v4.content.FileProvider.getUriForFile(FileProvider.java:417)
at com.learning.speeeddy.imagereader.feature.MainActivity.dispatchTakePictureIntent(MainActivity.java:67)
at com.learning.speeeddy.imagereader.feature.MainActivity.access$200(MainActivity.java:40)
at com.learning.speeeddy.imagereader.feature.MainActivity$2.onClick(MainActivity.java:323)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22433)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6186)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
In MainActivity.java
private void dispatchTakePictureIntent() {
Intent pictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if(pictureIntent.resolveActivity(getPackageManager()) != null){
//Create a file to store the image
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
ex.printStackTrace();
}
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,"com.learning.speeeddy.imagereader.fileprovider", photoFile);
pictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(pictureIntent, CAPTURE_IMAGE_FULLSIZE_ACTIVITY_REQUEST_CODE);
}
}
}
private File createImageFile() throws IOException {
String timeStamp =
new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
String imageFileName = "IMG_" + timeStamp + "_";
File storageDir =
getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
return image;
}
In AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.learning.speeeddy.imagereader">
<uses-feature android:name="android.hardware.camera"
android:required="false" />
<uses-permission android:name="android.permission.INTERNET" android:required="true"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" android:required="true"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<meta-data
android:name="aia-compat-api-min-version"
android:value="1" />
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.learning.speeeddy.imagereader.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths"></meta-data>
</provider>
</application>
</manifest>
In file_paths.xml (/res/xml)
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="my_images" path="Android/data/com.learning.speeeddy.imagereader.app/files/Pictures" />
</paths>
I'm having issues with File Provider. I'm trying to get the Uri of an image I take with my phone camera. But whenever I try taking a photo, it's giving me the following error:
FATAL EXCEPTION: main Process: com.example.android.inventory, PID: 30523
java.lang.IllegalArgumentException: Failed to find configured root that contains /data/data/com.example.android.inventory/cache/IMG_20170718_213454_2102974580.jpg
at android.support.v4.content.FileProvider$SimplePathStrategy.getUriForFile(FileProvider.java:679)
at android.support.v4.content.FileProvider.getUriForFile(FileProvider.java:378)
at com.example.android.inventory.EditorActivity$5.onClick(EditorActivity.java:239)
onClickListener
//press button to take a photo
final Button addImage = (Button) findViewById(R.id.click);
addImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
try {
File f = createImageFile();
Log.d(LOG_TAG, "File: " + f.getAbsolutePath());
mImageUri = FileProvider.getUriForFile(
EditorActivity.this, FILE_PROVIDER_AUTHORITY, f);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
AndroidManifest
<?xml version="1.0" encoding="utf-8"?>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name="com.example.android.inventory.CatalogActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity
android:name="com.example.android.inventory.EditorActivity"
android:theme="#style/EditorTheme"
android:parentActivityName="com.example.android.inventory.CatalogActivity" >
<!-- Parent activity meta-data to support 4.0 and lower -->
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.android.inventory.CatalogActivity" />
</activity>
<provider
android:name="com.example.android.inventory.data.InventoryProvider"
android:authorities="com.example.android.inventory"
android:exported="false" />
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.example.android.myfileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_provider_paths" />
</provider>
</application>
<uses-feature android:name="android.hardware.camera"
android:required="true" />
File provider Path
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="share" path="/" />
</paths>
Any help would be appreciated. Thank you.
You can do it alternatively using Bitmap.
//The method below is opened when button is clicked you can handle in your own way
private void OpenImageChooser() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
//on Activity result will give you the data when you can convert it into bitmap to show in the image view
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
imgAttendance.setImageBitmap(imageBitmap);
}
}
}
In AndroidMenifest.xml
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths" />
</provider>
provider_paths.xml
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
In OnclickListener after file create
if (Build.VERSION.SDK_INT >= 24)
mImageCaptureUri = FileProvider.getUriForFile(EditorActivity.this, BuildConfig.APPLICATION_ID + ".provider", f);
else
mImageCaptureUri = Uri.fromFile(f);
Here is code snippet to get Uri from file provider.
File imageFile = createImageFile();
picUri = FileProvider.getUriForFile(RegisterActivity.this , this.getApplicationContext().getPackageName() + ".provider", imageFile);
Below is file provider path
provider_paths.xml
file.
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="my_images" path="."/>
</paths>
Here <external-path> define that image save in external storage
And below shows how to define file provide in Manifest file.
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths" />
</provider>
i am using this code to run a camera intent to take a photo. All being taken from HERE step by step (full sized camera option)
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(getActivity(), "com.example.android.fileprovider", photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(imageFileName, ".jpg",storageDir);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
Toast.makeText(getActivity(), mCurrentPhotoPath, Toast.LENGTH_SHORT).show();
return image;
}
This is my Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.terrormachine.swipeapp">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.example.android.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths">
</meta-data>
</provider>
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
and my paths xml:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="my_images" path="Android/data/com.example.package.name/files/Pictures" />
</paths>
and i am getting this error:
java.lang.IllegalArgumentException: Failed to find configured root that contains /storage/emulated/0/Android/data/com.example.terrormachine.swipeapp/files/Pictures/JPEG_20161015_211933_-593154643.jpg
A little surprising since the file "shell" is there(at this location).
I fount THIS thread but i cant understand a thing...can you explain it humanlike? Any solution is welcome! Its an important project and i need to finish as much as possible and this is a huge stop.
In your files_path.xml, you need to replace com.example.package.name with your apps package name, as explained on developers site.
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="my_images" path="Android/data/com.example.terrormachine.swipeapp/files/Pictures" />
</paths>
Also add camera permission in your AndroidManifest.xml file.
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera"
android:required="true" />
I think you are missing "uses-feature android:name="android.hardware.camera" android:required="true"" in your manifest.