Нужно переписать activity result api котлин код в джаву

Нашел рабочую имплементацию activity result api для доставания изображения через камеру и файловую систему. Код написан на котлине, а мне нужна джава. Пытался конвертировать в джаву через инструменты среды разработки, но код на выводе плохой. Пожалуйста, помогите.

import android.net.Uri
import android.os.Bundle
import android.widget.ImageView
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.FileProvider
import androidx.lifecycle.lifecycleScope
import com.google.android.material.button.MaterialButton
import java.io.File

class MainActivity : AppCompatActivity(R.layout.activity_main) {

    private val takeImageResult = registerForActivityResult(ActivityResultContracts.TakePicture()) { isSuccess ->
        if (isSuccess) {
            latestTmpUri?.let { uri ->
                previewImage.setImageURI(uri)
            }
        }
    }

    private val selectImageFromGalleryResult = registerForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? ->
        uri?.let { previewImage.setImageURI(uri) }
    }

    private var latestTmpUri: Uri? = null

    private val previewImage by lazy { findViewById<ImageView>(R.id.image_preview) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setClickListeners()
    }

    private fun setClickListeners() {
        findViewById<MaterialButton>(R.id.take_image_button).setOnClickListener { takeImage() }
        findViewById<MaterialButton>(R.id.select_image_button).setOnClickListener { selectImageFromGallery() }
    }

    private fun takeImage() {
        lifecycleScope.launchWhenStarted {
            getTmpFileUri().let { uri ->
                latestTmpUri = uri
                takeImageResult.launch(uri)
            }
        }
    }

    private fun selectImageFromGallery() = selectImageFromGalleryResult.launch("image/*")

    private fun getTmpFileUri(): Uri {
        val tmpFile = File.createTempFile("tmp_image_file", ".png", cacheDir).apply {
            createNewFile()
            deleteOnExit()
        }

        return FileProvider.getUriForFile(applicationContext, "${BuildConfig.APPLICATION_ID}.provider", tmpFile)
    }
} 

Фрагмент кода Manifest

<application ..>
    <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths" />
        </provider>
</application>

Код provider_paths.xml

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <cache-path
        name="cached_files"
        path="." />
    <files-path
        name="images"
        path="." />
</paths>

Для вашего удобства разметка

<?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">

    <com.google.android.material.card.MaterialCardView
        android:id="@+id/image_preview_card"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_margin="16dp"
        app:cardElevation="8dp"
        app:layout_constraintBottom_toTopOf="@id/button_barrier"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintDimensionRatio="16:9"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <ImageView
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:layout_gravity="center"
            android:alpha="0.25"
            app:tint="@color/black" />

        <ImageView
            android:id="@+id/image_preview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:scaleType="centerCrop"
            />
    </com.google.android.material.card.MaterialCardView>

    <com.google.android.material.button.MaterialButton
        android:id="@+id/take_image_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginEnd="4dp"
        android:layout_marginBottom="16dp"
        android:text="Take image"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/select_image_button"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent" />

    <com.google.android.material.button.MaterialButton
        android:id="@+id/select_image_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="4dp"
        android:layout_marginEnd="16dp"
        android:layout_marginBottom="16dp"
        android:text="Select gallery-image"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toEndOf="@+id/take_image_button" />

    <androidx.constraintlayout.widget.Barrier
        android:id="@+id/button_barrier"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:barrierDirection="top"
        app:barrierMargin="16dp"
        app:constraint_referenced_ids="take_image_button,select_image_button" />

</androidx.constraintlayout.widget.ConstraintLayout>

Ответы (1 шт):

Автор решения: Vadik

Переписать один в один на Java невозможно, так как в методе takeImage у вас запускается корутина.

Но если вызов корутины там не обязателен, то ваш код можно переписать на Java следующим образом:

public class MainActivity extends AppCompatActivity {

    private Uri latestTmpUri = null;
    private ImageView previewImage = null;
    
    private final ActivityResultLauncher<Uri> takeImageResult =
            registerForActivityResult(new TakePicture(), isSuccess -> {
                if (isSuccess) {
                    if (latestTmpUri != null) {
                        previewImage.setImageURI(latestTmpUri);
                    }
                }
            });
    
    private final ActivityResultLauncher<String> selectImageFromGalleryResult =
            registerForActivityResult(new GetContent(), uri -> {
                if (uri != null) {
                    previewImage.setImageURI(uri);
                }
            });

    public MainActivity() {
        super(R.layout.activity_main);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        previewImage = findViewById(R.id.image_preview);
        setClickListeners();
    }

    private void setClickListeners() {
        findViewById(R.id.take_image_button).setOnClickListener(v -> takeImage());
        findViewById(R.id.select_image_button).setOnClickListener(v -> selectImageFromGallery());
    }

    private void takeImage() {
        final Uri uri;
        try {
            uri = getTmpFileUri();
        } catch (IOException exception) {
            throw new RuntimeException("Cannot create temp file", exception);
        }
        latestTmpUri = uri;
        takeImageResult.launch(uri);
    }

    private void selectImageFromGallery() {
        selectImageFromGalleryResult.launch("image/*");
    }

    private Uri getTmpFileUri() throws IOException {
        final File tmpFile = File.createTempFile("tmp_image_file", ".png", getCacheDir());
        //noinspection ResultOfMethodCallIgnored
        tmpFile.createNewFile();
        tmpFile.deleteOnExit();
        final String authority = String.format("%s.provider", BuildConfig.APPLICATION_ID);
        return FileProvider.getUriForFile(getApplicationContext(), authority, tmpFile);
    }

}
→ Ссылка