...

/

The MainActivity Class

The MainActivity Class

Learn to implement the MainActivity of an image classification Android app that utilizes a TF Lite model to classify images.

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:

Press + to interact
package com.example.horse_human_classify
import android.graphics.Bitmap
import android.graphics.ImageDecoder
import android.graphics.ImageDecoder.ImageInfo
import android.net.Uri
import android.os.Bundle
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import java.io.IOException
class MainActivity : AppCompatActivity() {
// Constants for image classifier
companion object {
private const val REQUEST_CODE_LOAD_IMAGE = 1
}
private lateinit var loadImageButton : Button
private lateinit var imageView : ImageView
private lateinit var selectedImage : Bitmap
private lateinit var classifier : ImageClassifier
private 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 ...