The camera application is functioning smoothly on Marshmallow API 23, however, it crashes when trying to use the camera on API versions higher than 23

After creating a simple app for capturing photos and storing them in the SURVEYASSIST folder on the SD card, everything was running smoothly on my Redmi 3s prime (Android version Marshmallow 6.0.1). However, upon opening the app on the Redmi Note 5 pro (Oreo 8.1.0) and clicking on the camera button, the app crashes with an error code displayed as shown in the image.

https://i.sstatic.net/fZCjH.jpg

public class MainActivity extends AppCompatActivity {

    public static final int CAPTURE_IMAGE_FULLSIZE_ACTIVITY_REQUEST_CODE = 1777;
    private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public static final String Demo_ImagePath ="/storage/emulated/0/SURVEYASSIST/";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button button = (Button) findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                String imgcurTime = dateFormat.format(new Date());
                String _path = Demo_ImagePath + File.separator + imgcurTime + ".jpg";
                File file = new File(_path);

                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                startActivityForResult(intent, CAPTURE_IMAGE_FULLSIZE_ACTIVITY_REQUEST_CODE);
            }
        });
    }
}

Answer №1

An issue known as the FileUriExposedException is being thrown in this scenario. According to the provided documentation:

This exception occurs when an application exposes a file:// Uri to another app.

You can find a helpful article on addressing this problem here. In case the link becomes inaccessible, here is a summary:

  1. Include the following in your manifest:

    <manifest ...>
      <application ...>
          <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>
      </application>
    

  2. Create an XML file named res/xml/provider_paths.xml

    <?xml version="1.0" encoding="utf-8"?>
    <paths xmlns:android="http://schemas.android.com/apk/res/android">
        <external-path name="external_files" path="."/>
    </paths>
    
  3. Modify your code: From:

    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
    

    To:

    Uri apkURI = FileProvider.getUriForFile(
                         this, 
                         this.getApplicationContext()
                         .getPackageName() + ".provider", file);
    intent.setDataAndType(apkURI, "image/*");
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieving a specific value from a JSON object using the find method in JavaScript

Having difficulty extracting the value of jersey_num from the JSON data below. const json = [{ $: { Type: "first_name" }, _: "Evan" }, { $: { Type: "last_name" }, _: "Ferguson" ...

Removing a selected row from a data table using an HTTP request in Angular 2

I am working with a table that has data retrieved from the server. I need to delete a row by selecting the checkboxes and then clicking the delete button to remove it. Here is the code snippet: ...

Disable hover effects in CSS with JavaScript

I am looking for a way to deactivate CSS hover functionality using JavaScript. Within a form, there is a button that sends data to the database server. By utilizing OnClientClick() of an ASP.NET Button control, my goal is to modify the text of the element ...

Incorporate a personalized style into the wysihtml5 text editor

Is there a way for me to insert a button that applies a custom class of my choice? I haven't been able to find this feature in the documentation, even though it's a commonly requested one. Here's an example of what I'm looking for: If ...

Is there a reason why Firebase.auth.getUsers does not have filter support?

Can someone please check out my code below and help me with this issue? When I use FireBase.Auth.getUses(), I am only able to set data like getUses([userId:'dddd']). However, I want to getUsers("userId" containing "@hayan.com"). getAuth() .get ...

Changing the CSS property of a single table cell's innerHTML

I have a question that may seem silly, but I'm going to ask it anyway. Currently, I am iterating through a list of strings that follow the format "1H 20MIN" and adding them to table cells using the innerHTML property like so: for (i = 0; i < list ...

Display map upon clicking on Google Map marker trigger an AJAX request

Hello, I'm facing an issue with creating a new map when clicking on a marker. Here is the process I want to achieve: Show the default google map with included markers - this part works fine When I click on a marker, I want to create a new map where ...

Choosing a radio button based on the stored value within a variable

When transferring a variable (active) from my route to EJS, I initially found it easy to simply display its value: <!-- Active Text Input--> <div class="form-outline mb-4"> <label for="active" class="form-label">Active</label> ...

typescript error caused by NaN

Apologies for the repetitive question, but I am really struggling to find a solution. I am facing an issue with this calculation. The parameters a to g represent the values of my input from the HTML. I need to use these values to calculate a sum. When I tr ...

Having trouble sending AJAX select options with Choices.js

I'm currently utilizing Choices.js (https://github.com/jshjohnson/Choices) along with Ajax to dynamically populate data into my select field from a database. However, I've encountered an issue when using the following code: const choices = new C ...

"Using AJAX to send a POST request to asp.net and receiving a response with a

Hey there! I'm currently working on my computer science project for school, using asp.net and c#. I've run into a bit of an issue where my AJAX POST request is being received as a GET request. I've tried to troubleshoot it myself but no luck ...

I would appreciate your assistance in understanding how to utilize the Array concat() method in my code, and I am

I need help understanding how to use the Array concat() method and how to write pure JavaScript code according to the ECMA-262 standard. Assume O is the object we are working with. Let A be the new array created based on O with a length of 0. Set the ini ...

Embarking on a new Android project ahead!

Starting a new project on Android focused on car sales. Firstly, which libraries should be used for the interface? The main functionalities needed are: 1) Displaying images in grid blocks covering the entire screen. 2) Implementing image zooming feature. ...

I'm struggling with developing react applications due to problems with canvas elements

I am currently using an M1 MacBook Pro, with Node version 15.4.1 and npm version 7.0.15. When I ran the command npx create-react-app my-app, it gave me this output: https://i.sstatic.net/OKKnA.jpg I have attempted various solutions but keep encountering ...

Mastering intricate data structures using React.js

I am working on creating a table for orders using React+Redux. The data I need is stored in props and it has a structured format similar to this: [{ //stored in props(redux state) "id": 37, //order 1 "content": { "items": { " ...

Steps to enable editing in an array

I'm struggling to implement an editing functionality for the lists inside the ul element in my simple to-do list project. Currently, I have the delete functionality working but need guidance on how to add an edit function. The list items are added by ...

Is there a way to determine the remaining time between the present moment and a specific time in JavaScript?

Here's a snapshot of the snippetI have this great idea for a prayer app that can calculate the time remaining between the current time and the scheduled prayer times. My initial approach was to directly find the difference using the following code: ...

Adding a button label value to a FormGroup in Angular

I've been working on a contact form that includes inputs and a dropdown selection. To handle the dropdown, I decided to use the ng-Bootstrap library which involves a button, dropdown menu, and dropdown items. However, I'm facing difficulties inte ...

Discover multiple keys within a new Map object

Our usual approach involves creating a new Map like this: const hash = new Map() hash.set(key,value) To retrieve the information, we simply use: hash.get(specificKey) An advantage of using Map is that we have flexibility in choosing keys and values. Cur ...

Preventing AngularJS from Binding in Rows: A Solution

Currently, I am utilizing AngularJS version 1.5.3 and I am facing an issue with my services. I have two services - one that retrieves Area names and the other that fetches details for each Area. In my code, I first call the service to get the Area names an ...