import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.util.Log
import android.widget.ImageView
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.camera.core.*
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.lifecycle.LifecycleOwner
import kotlinx.android.synthetic.main.activity_main.*
import java.io.File
import java.nio.ByteBuffer
import java.text.SimpleDateFormat
import java.util.Locale
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
class MainActivity : AppCompatActivity() {
private lateinit var imageCapture: ImageCapture
private lateinit var cameraExecutor: ExecutorService
private var imageCaptureFile: File? = null
private val requestPermissionLauncher: ActivityResultLauncher<String> = registerForActivityResult(
ActivityResultContracts.RequestPermission()
) { isGranted: Boolean ->
if (isGranted) {
startCamera()
} else {
Toast.makeText(this, "Camera permission is required to capture images.", Toast.LENGTH_SHORT).show()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
requestPermissionLauncher.launch(Manifest.permission.CAMERA)
} else {
startCamera()
}
captureButton.setOnClickListener { takePhoto() }
cameraExecutor = Executors.newSingleThreadExecutor()
}
private fun startCamera() {
val cameraProviderFuture = ProcessCameraProvider.getInstance(this)
cameraProviderFuture.addListener(Runnable {
val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()
val preview = Preview.Builder().build().also {
it.setSurfaceProvider(viewFinder.surfaceProvider)
}
imageCapture = ImageCapture.Builder()
.setCaptureMode(ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY)
.setTargetRotation(windowManager.defaultDisplay.rotation)
.build()
val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA
try {
cameraProvider.unbindAll()
cameraProvider.bindToLifecycle(this as LifecycleOwner, cameraSelector, preview, imageCapture)
} catch (exc: Exception) {
Log.e("CameraX", "Use case binding failed", exc)
}
}, ContextCompat.getMainExecutor(this))
}
private fun takePhoto() {
val imageCapture = imageCapture ?: return
val photoFile = createImageFile()
val outputOptions = ImageCapture.OutputFileOptions.Builder(photoFile).build()
imageCapture.takePicture(
outputOptions, cameraExecutor, object : ImageCapture.OnImageSavedCallback {
override fun onError(imageCaptureError: ImageCaptureException) {
Log.e("CameraX", "Photo capture failed: ${imageCaptureError.message}", imageCaptureError)
}
override fun onImageSaved(output: ImageCapture.OutputFileResults) {
val savedUri = output.savedUri ?: photoFile.toUri()
imageCaptureFile = photoFile
val msg = "Photo captured at ${savedUri.path}"
runOnUiThread {
Toast.makeText(this@MainActivity, msg, Toast.LENGTH_SHORT).show()
displayCapturedImage()
}
}
})
}
private fun createImageFile(): File {
val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(System.currentTimeMillis())
val storageDir = getExternalFilesDir("images")
return File.createTempFile("JPEG_${timeStamp}_", ".jpg", storageDir).apply {
imageCaptureFile = this
}
}
private fun displayCapturedImage() {
imageCaptureFile?.let { file ->
val bitmap = BitmapFactory.decodeFile(file.absolutePath)
capturedImage.setImageBitmap(bitmap)
}
}
override fun onDestroy() {
super.onDestroy()
cameraExecutor.shutdown()
}
}
Write, Run & Share Kotlin code online using OneCompiler’s Kotlin online compiler for free. It’s a modern and fast online playground for Kotlin, supporting the latest version and ideal for learning, experimenting, and sharing code instantly.
Kotlin is a statically typed, modern programming language developed by JetBrains. It runs on the JVM and is fully interoperable with Java. Kotlin is concise, expressive, and safe, and it’s officially supported by Google for Android app development.
The following is a simple Kotlin program that prints a greeting:
fun main() {
println("Hello, OneCompiler!")
}
OneCompiler’s Kotlin editor supports stdin. You can provide input using the I/O tab. Here's a sample program that reads a line of input and prints a greeting:
fun main() {
print("Enter your name: ")
val name = readLine()
println("Hello, $name")
}
val name: String = "OneCompiler" // Immutable
var age: Int = 25 // Mutable
Kotlin supports type inference, so explicit types are optional:
val city = "Hyderabad"
var count = 10
val score = 85
if (score >= 50) {
println("Pass")
} else {
println("Fail")
}
for (i in 1..5) {
println(i)
}
var i = 1
while (i <= 5) {
println(i)
i++
}
var j = 1
do {
println(j)
j++
} while (j <= 5)
fun add(a: Int, b: Int): Int {
return a + b
}
fun greet(name: String) = "Hello, $name"
val items = listOf("apple", "banana", "cherry")
for (item in items) {
println(item)
}
This guide provides a quick reference to Kotlin programming syntax and features. Start coding in Kotlin using OneCompiler’s Kotlin online compiler today!