dir.by  
  Search  
Programming, development, testing
Android, Google Play phone, tablet (writing an app, a game)
Kotlin application (for Android phone) in Android Studio
Android Kotlin application takes photo using camera and draws in the application | Android Studio | Kotlin
  Looked at 3413 times    
 Android Kotlin application takes photo using camera and draws in the application | Android Studio | Kotlin 
last updated: 9 April 2024
Download an example:
Description
I've written an app that has a  I want make photo  button, and when clicked, I call the standard function to take a photo:


 

I click on the  I want make photo  button:




 

I click Allow Camera:




 

I press the standard phone
button to take a photo:




 

Agree:




 

My app uploads a new photo and displays:




Step 1. Creating a new project
Step 2. Let's change the code in the file MainActivity.kt
The color          indicates that a new code has been added.
  File MainActivity.kt
package com.example.androidkotlinapp1

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Environment.DIRECTORY_PICTURES
import android.provider.MediaStore.ACTION_IMAGE_CAPTURE
import android.provider.MediaStore.EXTRA_OUTPUT
import android.widget.Button
import android.widget.ImageView
import androidx.core.content.FileProvider
import android.content.Context
import android.content.Intent
import android.net.Uri
import java.io.File
import java.text.SimpleDateFormat
import java.util.*


class MainActivity : AppCompatActivity() {

     val MY_REQUEST_CODE1 = 100
     var UriFilePath_to_SaveImage:Uri? = null


     override fun onCreate(savedInstanceState: Bundle?) {
          super.onCreate(savedInstanceState)
          setContentView(R.layout.activity_main)

          val myButton = findViewById(R.id.button1) as Button

          myButton.setOnClickListener {
               UriFilePath_to_SaveImage = createURIpath(baseContext)
               val intent = Intent(ACTION_IMAGE_CAPTURE)
               intent.putExtra(EXTRA_OUTPUT, UriFilePath_to_SaveImage)
               startActivityForResult(intent, MY_REQUEST_CODE1);
          }

     }

     // I override system function
     override fun onActivityResult(requestCode: Int, resultCode: Int, intent: Intent?) {
          super.onActivityResult(requestCode, resultCode, intent)
          if (resultCode == RESULT_OK && requestCode == MY_REQUEST_CODE1) {
               show_URI_in_ImageView(UriFilePath_to_SaveImage)
          }
     }


     // my function for output path (where put new image)
     fun createURIpath(context: Context): Uri {
          val fileName = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.GERMAN).format(Date())
          val path = getExternalFilesDir(DIRECTORY_PICTURES)
          val file = File(path, "$fileName.jpg")
          return FileProvider.getUriForFile( context, "${BuildConfig.APPLICATION_ID}.fileprovider", file)
     }


     // my function for image view
     fun show_URI_in_ImageView(uri: Uri?)
     {
          val myImageView = findViewById(R.id.imageView1) as ImageView
          myImageView.setImageURI(uri)
     }

}
Explanation:
1) find my button by id
val myButton = findViewById(R.id.button1) as Button


Note!
Here's how I added id to res/layout/activity_main.xml:
@+id/ is a system Android expression
button1 is id of my button.
...
<Button
 
    android:id="@+id/button1"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:backgroundTint="#00FF00"
     android:textColor="#000000"
     android:text="I want make photo" />
...

 
2) By pressing my button, open the system camera to take a photo:
...
myButton.setOnClickListener {
     UriFilePath_to_SaveImage = createURIpath(baseContext)
     val intent = Intent(ACTION_IMAGE_CAPTURE)
     intent.putExtra(EXTRA_OUTPUT, UriFilePath_to_SaveImage)
     startActivityForResult(intent, MY_REQUEST_CODE1);
}
...


Note 1
This is the button press handler: myButton.setOnClickListener { ... }
When the button is clicked, the code inside the parentheses will be called.

Note 2
Create the Intent object.
Intent is a class to store parameters.
Intent is needed to pass these parameters to Activity
The startActivityForResult method shows Activity, performs some action in Activity, and returns with the result.
In Intent I specified:
ACTION_IMAGE_CAPTURE this means that I will take a photo with my phone's camera
EXTRA_OUTPUT is the uri path and the photos will be saved there
3) When you take a photo from your phone's camera, the system function will be called:
override fun onActivityResult
override fun onActivityResult(requestCode: Int, resultCode: Int, intent: Intent?) {
     super.onActivityResult(requestCode, resultCode, intent)
     if (resultCode == RESULT_OK && requestCode == MY_REQUEST_CODE1) {
          show_URI_in_ImageView(UriFilePath_to_SaveImage)
     }
}


Note 1
Be sure to call the basic method:
super.onActivityResult(requestCode, resultCode, intent)

Note 2
By requestCode I determine which Activity returned the result:
if (resultCode == RESULT_OK && requestCode == MY_REQUEST_CODE1)

MY_REQUEST_CODE1 I use at the very top of the file this can be any number:
val MY_REQUEST_CODE1 = 100

I also pass MY_REQUEST_CODE1 to the Activity run:
startActivityForResult(intent, MY_REQUEST_CODE1);


Note 3
Once the photo is taken, I call my show_URI_in_ImageView(UriFilePath_to_SaveImage) function to show the photo on the screen next to my button.

The interesting thing is that:
• The photo taken will be saved by my uri in my app folder
content://com.example.androidkotlinapp1.fileprovider/pictures/20240103_191203.jpg

• But if we were to choose a photo from the gallery, here's my Kotlin app:
   Android Kotlin choose photo from gallery and draws in the application | Android Studio | Kotlin ...
Then uri will come to us from data in the function:
override fun onActivityResult(requestCode: Int, resultCode: Int, intent: Intent?) {
     super.onActivityResult(requestCode, resultCode, intent)
     val uriFromGallery = intent?.data
}
4) My Function createURIpath
My function creates an empty file and returns the uri path
fun createURIpath(context: Context): Uri {
          val fileName = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.GERMAN).format(Date())
          val path = getExternalFilesDir(DIRECTORY_PICTURES)
          val file = File(path, "$fileName.jpg")
          return FileProvider.getUriForFile( context, "${BuildConfig.APPLICATION_ID}.fileprovider", file)
     }


Note 1
val fileName = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.GERMAN).format(Date())
The file name I do as the date and time, for example: 3 january 2024 19:38:37
val fileName = "20240103_193837.jpg"

Note 2
val path = getExternalFilesDir(DIRECTORY_PICTURES)
DIRECTORY_PICTURES This is the Android system constant, there is more: DIRECTORY_MUSIC, DIRECTORY_MOVIES, DIRECTORY_DOCUMENTS
getExternalFilesDir is a Android system function that returns the full path to the directory where our application can place persistent files
path in our case, this is the folder where the images will be saved, because we use DIRECTORY_PICTURES
path = "/storage/emulated/0/Android/data/com.example.androidkotlinapp1/files/Pictures"
Read more: What is getExternalFilesDir in Android Studio, Kotlin ...

Note 3
val file = File(path, "$fileName.jpg")
Create an empty jpg file in the path folder named fileName

On a note 4
return FileProvider.getUriForFile( context, "${BuildConfig.APPLICATION_ID}.fileprovider", file)
FileProvider.getUriForFile is a system function that uses a file and application id to return the uri path.
The uri path will return:
content://com.example.androidkotlinapp1.fileprovider/pictures/20240103_191203.jpg
5) My Function show_URI_in_ImageView
My function draws a picture in ImageView by uri
fun show_URI_in_ImageView(uri: Uri?)
{
     val myImageView = findViewById(R.id.imageView1) as ImageView
     myImageView.setImageURI(uri)
}


Note!
Here's how I added id to res/layout/activity_main.xml:
...
<ImageView
 
    android:id="@+id/imageView1"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     tools:srcCompat="@tools:sample/avatars" />
...
Step 3. Let's change the code in the file activity_main.xml
In the activity_main.xml file, add the following graphic elements:
LinearLayout
This is a layer where elements are displayed one after the other vertically or horizontally (I have it vertically because the android:orientation="vertical parameter is set)
Button
It's a button
ImageView
To display a picture
The color          indicates that a new code has been added.
  File activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:app="http://schemas.android.com/apk/res-auto"
     xmlns:tools="http://schemas.android.com/tools"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     tools:context=".MainActivity">

     <LinearLayout
 
         android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:orientation="vertical">

          <Button
 
              android:id="@+id/button1"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:backgroundTint="#00FF00"
               android:textColor="#000000"
               android:text="I want make photo" />

          <ImageView
 
              android:id="@+id/imageView1"
               android:layout_width="match_parent"
               android:layout_height="wrap_content"
               tools:srcCompat="@tools:sample/avatars" />
     </LinearLayout>


</androidx.constraintlayout.widget.ConstraintLayout>
Step 4. Let's change the code in the file AndroidManifest.xml
  File AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:tools="http://schemas.android.com/tools">

     <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
     <uses-permission android:name="android.permission.READ_MEDIA_IMAGES"/>
     <uses-permission android:name="android.permission.READ_MEDIA_VIDEO"/>
     <uses-permission android:name="android.permission.READ_MEDIA_AUDIO"/>


     <application
 
         android:allowBackup="true"
          android:dataExtractionRules="@xml/data_extraction_rules"
          android:fullBackupContent="@xml/backup_rules"
          android:icon="@mipmap/ic_launcher"
          android:label="@string/app_name"
          android:supportsRtl="true"
          android:theme="@style/Theme.AndroidKotlinApp1"
          tools:targetApi="31">
          <activity
 
              android:name=".MainActivity"
               android:exported="true">
               <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}.fileprovider"
               android:exported="false"
               android:grantUriPermissions="true">
               <meta-data
 
                   android:name="android.support.FILE_PROVIDER_PATHS"
                    android:resource="@xml/file_paths" />
          </provider>


     </application>

</manifest>
Why is ${applicationId} used in the manifest file?
Why is ${BuildConfig.APPLICATION_ID} used in the MainActivity.kt file?

Explanation:
This is the same value "com.example.androidkotlinapp1" and is taken from the build.gradle file.
Learn more:
File AndroidManifest.xml

What is ${applicationId}
File AndroidManifest.xml
...
<provider
 
    android:name="androidx.core.content.FileProvider"
     android:authorities="${applicationId}.fileprovider"
     android:exported="false"
     android:grantUriPermissions="true">
     <meta-data
 
         android:name="android.support.FILE_PROVIDER_PATHS"
          android:resource="@xml/file_paths" />
</provider>...


Note!
${applicationId} this means that the variable applicationId is taken from the file build.gradle:
android {
     namespace 'com.example.androidkotlinapp1'
     compileSdk 33

     defaultConfig {
          applicationId "com.example.androidkotlinapp1"
          minSdk 27
          targetSdk 33
          versionCode 1
          versionName "1.0"

          testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
     }
     ...
}
dependencies {
     ...
}

 
Read more: How to make a variable in the build.gradle file and pass it to the manifest file AndroidManifest.xml | Android ...
File MainActivity.kt

What is ${BuildConfig.APPLICATION_ID}
File MainActivity.kt
fun createURIpath(context: Context, dir: String, ext: String): Uri {
     ...
     return FileProvider.getUriForFile(context, "${BuildConfig.APPLICATION_ID}.fileprovider", file)
}
...


Note 1
FileProvider.getUriForFile is a system function that uses a file and application id to return the uri path.
 
Note 2
BuildConfig.APPLICATION_ID is a variable.
The BuildConfig class is created itself when the project is compiled and is located in the build folder:
public final class BuildConfig {
     public static final String APPLICATION_ID = "com.example.androidkotlinapp1";
     public static final int VERSION_CODE = 1;
     public static final String VERSION_NAME = "1.0";
...
}

The values are taken from the file build.gradle from the defaultConfig section.
File build.gradle:
android {
     namespace 'com.example.androidkotlinapp1'
     compileSdk 33

     defaultConfig {
          applicationId "com.example.androidkotlinapp1"
          minSdk 27
          targetSdk 33
          versionCode 1
          versionName "1.0"

          testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
     }
     ...
}
dependencies {
     ...
}



Read more: How to Make a Variable in a build.gradle File and Pass It to a Kotlin File | Android Studio | Kotlin ...
Step 5. Let's create a new file file_paths.xml
Let's create a file inside the folder:
D:\AndroidKotlinApp1
    app
       src
          main
             res
                xml
  File file_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths>
     <external-path
 
         name="pictures"
          path="Android/data/com.example.androidkotlinapp1/files/Pictures" />
     <external-path
 
         name="music"
          path="Android/data/com.example.androidkotlinapp1/files/Music" />
     <external-path
 
         name="docs"
          path="Android/data/com.example.androidkotlinapp1/files/Documents" />
     <external-path
 
         name="pdf"
          path="." />
</paths>
Just like that:
Explanation:
File AndroidManifest.xml

The <provider>...</provider>... section refers to the xml file file_paths
File AndroidManifest.xml
...
<provider
 
    android:name="androidx.core.content.FileProvider"
     android:authorities="${applicationId}.fileprovider"
     android:exported="false"
     android:grantUriPermissions="true">
     <meta-data
 
         android:name="android.support.FILE_PROVIDER_PATHS"
          android:resource="@xml/file_paths" />
</provider>...
File file_paths.xml make access to specific path by name
File file_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths>
     <external-path
 
         name="pictures"
          path="Android/data/com.example.androidkotlinapp1/files/Pictures" />
     <external-path
 
         name="music"
          path="Android/data/com.example.androidkotlinapp1/files/Music" />
     <external-path
 
         name="docs"
          path="Android/data/com.example.androidkotlinapp1/files/Documents" />
     <external-path
 
         name="pdf"
          path="." />
</paths>


Note!
In the MainActivity.kt file, I call the getExternalFilesDir system function
val path = getExternalFilesDir(DIRECTORY_PICTURES)
DIRECTORY_PICTURES This is the Android system constant, there is more: DIRECTORY_MUSIC, DIRECTORY_MOVIES, DIRECTORY_DOCUMENTS
getExternalFilesDir is a Android system function that returns the full path to the directory where our application can place persistent files
path in our case, this is the folder where the images will be saved, because we use DIRECTORY_PICTURES
path = "/storage/emulated/0/Android/data/com.example.androidkotlinapp1/files/Pictures"
Read more: What is getExternalFilesDir in Android Studio, Kotlin ...
It is very very important: com.example.androidkotlinapp1 in path must be the same as com.example.androidkotlinapp1 in applicationId in build.gradle file
Step 6. Let's launch the project and see where the picture will be saved
The file will be saved to your phone here:
file path:
/storage/emulated/0/Android/data/com.example.androidkotlinapp1/files/Pictures/20240103_193837.jpg
URI:
content://com.example.androidkotlinapp1.fileprovider/pictures/20240103_191203.jpg
 
← Previous topic
Show a window with 2 buttons: yes, no and you don't need to add any resource, layout | I call the AlertDialog function in Kotlin | Android Studio
 
Next topic →
Android Kotlin choose photo from gallery and draws in the application | Android Studio | Kotlin ...
 
Your feedback ... Comments ...
   
Your Name
Your comment (www links can only be added by a logged-in user)

  Объявления  
  Объявления  
 
What is the Android operating system? What version numbers were in Android
What are ARM processors? | Android
Что такое AndroidX?
Java application (for Android phone) in Android Studio
Why Android applications are written in Java?
Download and install Android Studio to write programs for Android phones in Java, Kotlin
Open Android Studio on the computer (Windows 10)
Create a new project on Java with one simple Activity in Android Studio (write a program for Android phones, tablets) in Windows 10
Compile and run the application in Android Studio on computer (Windows) in emulator mode Android Device
Running the application Android Studio in debugging on computer (Windows) in emulator mode Android Device
Error "error while waiting for device: the emulator process for ..... has terminated" when running an application in Android Studio on a computer (Windows) in emulator mode Android Device
Error "Error while waiting for device: Illegal char <*> at index 0: *.lock ..." when running the application in Android Studio
Error "AVD is already running ..." when running the application in Android Studio
Error "CMake "3.18.1" was not found in SDK, PATH, or by cmake.dir property" when compiling a project to Android Studio
Error "Execution failed for task ":app:compressDebugAssets" when compiling a project to Android Studio
All errors when starting the Android application
What is Android SDK (a copy of the Android operating system)? Installing Android SDK 8.1 in Android Studio ...
Create a Android virtual device in Android Studio
Install HAXM
Activity in Android
Kotlin application (for Android phone) in Android Studio
Download and install Android Studio to write programs for Android phones in Java, Kotlin
Create a new project "Empty Views Activity" on Kotlin in Android Studio (write a program for Android phones, tablets) in Windows 10
Compile and run Kotlin an application in Android Studio on a computer (Windows) in emulator mode Android Device
Run Kotlin an application in Android Studio in debugging on a computer (Windows) in emulator mode Android Device
Running and debugging Kotlin Android Studio app on my phone via USB
Long wait when running Kotlin Android application. I see the message: "I/zygote:Waiting for a blocking GC ProfileSaver"
Create Android project, add TextView and show the value on the phone | Android Telephone, Android Studio, Kotlin, Windows 10
Copy the data in the class and object. We use the attribute @Parcelize and the interface Parcelable. | Kotlin | Android Studio
Error "Class is not abstract and does not implement abstract member public abstract fun describeContents(): Int defined in android.os.Parcelable" | Kotlin | Android Studio | @Parcelize | Parcelable
Show a window with 2 buttons: yes, no and you don't need to add any resource, layout | I call the AlertDialog function in Kotlin | Android Studio
Android Kotlin application takes photo using camera and draws in the application | Android Studio | Kotlin
Android Kotlin choose photo from gallery and draws in the application | Android Studio | Kotlin ...
getExternalFilesDir - function that returns the full path to an external directory where our application can place persistent files | Android Studio, Kotlin
getFilesDir - function that returns the full path to directory where our application can place files | Android Studio, Kotlin
How do I work with files media in Android? What are content Uri and file path. The difference between getExternalFilesDir and getFilesDir ... | Android Studio, Kotlin
How to Make a Variable in the build.gradle File and Pass It to the Manifest File AndroidManifest.xml | Android Studio | Kotlin
How to Make a Variable in a build.gradle File and Pass It to a Kotlin File | Android Studio | Kotlin
Moshi (converting json text to a class object) | deserialization in Kotlin | Android Studio
Moshi (converting array json to list of object) | deserialization in Kotlin | Android Studio
Error "Failed to find the generated JsonAdapter class for class com.example.androidkotlinapp1.MyBook" | Exception | Kotlin | Moshi | Android Studio
Error "A problem occurred evaluating project ':app'. Caused by: CustomMessageMissingMethodException: Could not find method kapt() for arguments [com.squareup.moshi:moshi-kotlin-codegen:1.14.0]" | When compiling a Kotlin, Moshi project in Android Studio
Jetpack application (for Android phone) in Android Studio | Kotlin
What is Jetpack for Android?
Create a new project "Jetpack Compose" on Kotlin in Android Studio (write a program for Android phones, tablets) in Windows 10
Compilation error "Dependency 'androidx.core:core-ktx:1.17.0' requires Android Gradle plugin 8.9.1 or higher" | Jetpack | Kotlin | Android Studio
C++ game (for Android phone) in Android Studio | Android NDK, OpenGL ES
What is Android NDK for Android phone? This is the C++ library for the Android phone.
What is Android OpenGL ES for Android phone? This is the C++ graphics library for the Android phone.
Create a project "Android Native C++ Game" for the phone | Android Studio, Android NDK, OpenGL ES, C++
Drawing a lake by points for the 2D game
Drawing an enemy airplane as a vector graphic in Adobe Illustrator. I take the coordinates of the points from Adobe Illustrator and add them to my 2D game on C++ OpenGL
Compile and run "Android Native C++ Game" in Android Studio on a computer (Windows) in Android Device emulator mode
Error "[CXX1405] error when building with cmake using CMakeLists.txt: C build system [configure] failed while executing cmake.exe" when compiling Android Native C++ an application to Android Studio on computer (Windows)
Error "ninja: error: rebuilding 'build.ninja': subcommand failed" when compiling Android Native C++ an application to Android Studio on computer (Windows)
Draw a triangle with paint inside in "Android Native C++ Game" for phone | Android Studio, Android NDK, OpenGL ES v1, C++
Download bmp file from Assets and draw textures in "Android Native C++ Game" for your phone | Android Studio, Android NDK, OpenGL ES v2 (shader), C++
How to get bmp file located in Assets inside apk file ? | Android Studio, NDK, C++
How to use alpha transparency in displaying texture using OpenGL? | Android Studio, OpenGL ES, NDK, C++
Why does glTexImage2D return error code 1280? | Android Studio, OpenGL ES, NDK, C++
What are cpp and h files in C++? | Android Studio, NDK, C++
How to create new h file and add to project android NDK C++? | Android Studio, NDK, C++
How to create new cpp file and add to project android NDK C++? | Android Studio, NDK, C++, CMakeLists.txt
dynamic_cast in C++ (converting a pointer to a different type and checking validity in runtime) | Android Studio, NDK, C++
std::map<Key, Value> is a set of keys and values in C++. | Android Studio, NDK, C++
Pass a function as a parameter to a function (callback) | C++ | Android Studio, NDK, C++
How to find event when display rotated (changed orientation) in Android phone | Android Studio, NDK, C++
How to handle events in Android phone (create/terminate window event, set focus, lost focus, touch in phone) | Android Studio, NDK, C++
Create a signed apk file in Android Studio | Android NDK, OpenGL ES
Google Play Console (for developer)
Creating a Google Play account developer | Google Play Console
The developer in Google Play Console needs to verify the identity | Google Play Console
The developer in Google Play Console needs to confirm developer account | Google Play Console
Developer account is not in use | Developer account is at risk of being closed | Google Play Console
Compile app and send it for production in Google Play Console | My app in Google Play Console
Policy status "Invalid Privacy policy" | Provide link to a valid privacy policy page | My app in Google Play Console
Policy status "App must target Android 15 (API level 35) or higher" | Status "You won't be able to release app updates" | My app in Google Play Console
Policy status "App must target Android 14 (API level 34) or higher" | Status "You won't be able to release app updates" | My app in Google Play Console
Policy app content "Remove Photo and video permissions permission or submit declaration" | My app in Google Play Console
Create an application in Google Play Console (in the option I select that it will be a game) | My game in Google Play Console
Important parameters: package, applicationId, versionCode, versionName, android:label (in AndroidManifest.xml, build.gradle) to create a test version for Google Play Console | My game in Google Play Console
Create a signed .aab file in Android Studio | My game in Google Play Console
Compile the game and send it for internal testing in Google Play Console | My game in Google Play Console
Google automatically ran tests and made pictures, a report on how the game runs on different brands of phones | My game in Google Play Console
How do I ask Google Play Developer Console a support question?
Google Play Developer Console support feedback
Topics about Google Play Billing & in-app purchase | Google Play Console
Can I use (integrate) payments in my Google game if I am a developer from Belarus? | Monetization in Google Play Console
How can I change the Google Play Console language? | Google Chrome
How to change country in payments profile? | Google Play Console
How do I view (open) a payment page in Google Play? | Google Play Console

  Ваши вопросы присылайте по почте: info@dir.by  
Яндекс.Метрика