The MainActivity Class
Learn to implement the MainActivity of an image classification Android app that utilizes a TF Lite model to classify images.
We'll cover the following...
The MainActivity
class is the main activity of our app that extends the AppCompatActivity
class. It overrides the onCreate()
method to set up the UI, initializes the UI components, and handles user interactions.
Fields of the MainActivity
The fields of the MainActivity
include:
A constant field to define the request code for loading an image.
A field (
Button
) to load images from the storage.A field (
ImageView
) to view the image on the UI.A field (
Bitmap
) to represent the selected image.A field (of the type
ImageClassifier
) to perform image classification using a TF Lite model.A field (
TextView
) to display the classification result.A field (an instance of
ActivityResultLauncher)
handling the result of picking an image.
The following code defines these fields:
package com.example.horse_human_classifyimport android.graphics.Bitmapimport android.graphics.ImageDecoderimport android.graphics.ImageDecoder.ImageInfoimport android.net.Uriimport android.os.Bundleimport android.widget.Buttonimport android.widget.ImageViewimport android.widget.TextViewimport androidx.activity.result.contract.ActivityResultContractsimport androidx.appcompat.app.AppCompatActivityimport java.io.IOExceptionclass MainActivity : AppCompatActivity() {// Constants for image classifiercompanion object {private const val REQUEST_CODE_LOAD_IMAGE = 1}private lateinit var loadImageButton : Buttonprivate lateinit var imageView : ImageViewprivate lateinit var selectedImage : Bitmapprivate lateinit var classifier : ImageClassifierprivate lateinit var resultTextView : TextView// Implement the logic below to pick an image from the device's storage//private val pickImage// Override onCreate() method here}
Lines 18–20: These define a companion object (
REQUEST_CODE_LOAD_IMAGE
) with a constant property to represent the request code for loading an image.Line 22: This ...