dir.by  
Поиск >>

Компьютер, программы
→
Android, Google Play phone, tablet (writing an app, a game)
→
Android Kotlin (XML markup app) | Android Studio
 Android Kotlin choose photo from gallery and draws in the application | Android Studio | Kotlin ... 
посмотрели 8179 раз
обновлено: 11 April 2024
I've written an app that has a  Load photo from Gallery  button, and when clicked, I call the standard functionality to select a photo from the Gallery:


 


I click on the  Load photo from Gallery  button:






 

The Android system shows a folder with photos
I choose a photo:





 

My app gets the path to the photo
and displays the selected photo:




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 android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import android.content.Intent
import android.content.Intent.ACTION_OPEN_DOCUMENT
import android.net.Uri
import android.widget.Button
import android.widget.ImageView


class MainActivity : AppCompatActivity() {

     val MY_REQUEST_CODE1 = 100

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

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

          myButton.setOnClickListener {
               val intent = Intent(ACTION_OPEN_DOCUMENT)
               intent.addCategory(Intent.CATEGORY_OPENABLE)
               intent.type = "*/*"
               intent.putExtra(Intent.EXTRA_MIME_TYPES, arrayOf("image/*", "video/*"))
               startActivityForResult(intent, MY_REQUEST_CODE1);
          }

     }

     // I override system function
     override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
          super.onActivityResult(requestCode, resultCode, data)

          if (resultCode == RESULT_OK && requestCode == MY_REQUEST_CODE1) {

               val uriFilePath_to_gallery = data?.data
               show_URI_in_ImageView(uriFilePath_to_gallery)

          }
     }


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

}
Step 2. 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
This is to display the picture
The color          indicates that a new code has been added.
  Xml     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="#A0A000"
               android:textColor="#000000"
               android:text="Load photo from Gallery" />

          <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>
Explanation
I wonder what path we will see when we select the photo from the gallery
 
When we select a photo from the gallery, we will see uri:
content://com.android.providers.media.documents/document/image%3A16
 
Question: How do I get the path to the file from this uri?
Answer: This uri was generated by the system Provider. I wouldn't recommend converting uri to a file path, because there's no guarantee that it will always work. Because only temporary permissions can be allocated to a file by the system.

Problem! Working with uri from the gallery is not very convenient for me. When I save uri to the database in a project at work, then this uri does not always work (after a few days) - the picture for this uri is not displayed.
Decision:
  Step 1. I'm creating an empty file inside my app folder (there's a getExternalFilesDir function in Kotlin).
  Step 2. I read the contents (content) from the uri gallery and save it to my empty file.
  Step 3. I get uri at the location of my file
Download an example:
Changes 1
  Created a new file MyFileUtils.kt
package com.example.androidkotlinapp1

import android.content.ContentResolver
import android.content.Context
import android.net.Uri
import android.webkit.MimeTypeMap
import androidx.core.content.FileProvider
import java.io.File
import java.io.InputStream

class MyFileUtils {

     fun copyUriContentToFileInsideApp(context: Context, uri: Uri, filenameWithoutExtension: String): Uri?
     {
          val fileExtension = getFileExtensionFromUri(context, uri);
          val folderApplication = context.getExternalFilesDir(android.os.Environment.DIRECTORY_PICTURES)
          val fileDest = File(folderApplication, filenameWithoutExtension + '.' + fileExtension)

          val uriDest = FileProvider.getUriForFile(
               context, "${BuildConfig.APPLICATION_ID}.fileprovider", fileDest
          )

          // get stream by uri
          val streamSource = context.contentResolver.openInputStream(uri)

          // store source stream to fileDest
          if (fileDest!=null && streamSource!=null)
          {
               streamSource.use { input ->
                    fileDest.outputStream().use { output ->
                         input.copyTo(output)
                         return uriDest
                    }
               }
          }
          return null
     }

     private fun getFileExtensionFromUri(context: Context, uri:Uri): String? {
          return if (uri.scheme == ContentResolver.SCHEME_CONTENT) {
               val mime = MimeTypeMap.getSingleton()
               mime.getExtensionFromMimeType(context.contentResolver.getType(uri))
          } else {
               MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(File(uri.path)).toString())
          }
     }
}
Changes 2
Created a new 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>
Changes 3
  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>
Changes 4
  File MainActivity.kt
package com.example.androidkotlinapp1

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.content.Intent
import android.content.Intent.ACTION_OPEN_DOCUMENT
import android.net.Uri
import android.widget.Button
import android.widget.ImageView
import androidx.core.content.ContentProviderCompat.requireContext

class MainActivity : AppCompatActivity() {
     val MY_REQUEST_CODE1 = 100

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

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

          myButton.setOnClickListener {
               val intent = Intent(ACTION_OPEN_DOCUMENT)
               intent.addCategory(Intent.CATEGORY_OPENABLE)
               intent.type = "*/*"
               intent.putExtra(Intent.EXTRA_MIME_TYPES, arrayOf("image/*", "video/*"))
               startActivityForResult(intent, MY_REQUEST_CODE1);
          }
     }

     // I override system function
     override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
          super.onActivityResult(requestCode, resultCode, data)

          if (resultCode == RESULT_OK && requestCode == MY_REQUEST_CODE1) {

               val uriContent_selected_from_gallery = data?.data

               val filenameWithoutExtension = "my_picture1"
               val newUri = MyFileUtils().copyUriContentToFileInsideApp(baseContext!!, uriContent_selected_from_gallery!!, filenameWithoutExtension);

               show_URI_in_ImageView(newUri)


          }
     }

     // my function for image view
     fun show_URI_in_ImageView(uriContent: Uri?)
     {
          val myImageView = findViewById(R.id.imageView1) as ImageView
          myImageView.setImageURI(uriContent)
     }
}
Let's run the program
Let's see a new uri for the picture:
content://com.example.androidkotlinapp1.fileprovider/pictures/my_picture1.jpg
 
← Previous topic
Android Kotlin application takes photo using camera and draws in the application | Android Studio | Kotlin
 
Next topic →
getExternalFilesDir - function that returns the full path to an external directory where our application can place persistent files | Android Studio, Kotlin
 
Your feedback ... Comments ...
   
Your Name
Your comment (www links can only be added by a logged-in user)

Новость "Черная пятница" Dreame в Беларуси – две недели скидок до 3400 рублей
 
• What is the Android operating system? What version numbers were in Android
• What are ARM processors? | Android
• What is AndroidX?
• Android doesn't use the JVM at all. Instead, Android apps run in ART (Android Runtime) or Dalvik virtual machines
• On Android, by running the APK file, the PackageInstaller system application is executed and the package is registered with the PackageManager Service
Android Java (XML markup application) | 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
• Example "Setting text in TextView" via Java code | Android, Java application
• Example "I send an http (web api) request to the site and display the response in TextView" | Android, Java application
• 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
• Error "Waiting For Debugger ... Application Android Java ... is waiting for the debugger to attach." when starting a project in 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
Android Kotlin (XML markup app) | 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
Android Kotlin (app with Jetpack Compose) | Android Studio
• What is Jetpack for Android? How is Jetpack Compose different from a project with XML markup?
• What is @Composable in Jetpack Compose (Kotlin, Android)?
• What is @Preview in Jetpack Compose (Kotlin, Android)?
• Create a new project "Jetpack Compose" on Kotlin in Android Studio (write a program for Android phones, tablets) in Windows 10
• Component state. Using MutableState. If you change the value in MutableState, the automatically matching @Composable functions(components) will be redrawn. | Jetpack Compose (Android, Kotlin)
• Database Room (SQLite) in Jetpack Compose | Created Kotlin, Android app "Notes" (add,delete text and save to database)
• Compilation error "Dependency "androidx.core:core-ktx:1.17.0" requires Android Gradle plugin 8.9.1 or higher" | Jetpack | Kotlin | Android Studio
• Google Gemini Artificial Intelligence Creates Android Kotlin Jetpack Code (Login Page)
• Job Interview (Jetpack App Questions & Assignments) | Android, Kotlin
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.
• Android C++ NDK Beginner"s Guide (Book)
• 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 "The project's Gradle version 8.12 is incompatible with the Gradle JVM version 25 currently selected to run Gradle build." | Compiling Android Native C++ an application to Android Studio on a machine (Windows)
• 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
• Is it possible to develop a paid application in Belarus and upload it to Google Play? | Monetization in Google Play Console
• Topics about Google Play Billing & in-app purchase | 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
Interview Android, Kotlin, Java
• Interview Android, Kotlin, Java (General Theory)

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