You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ML Kit文本识别遇MlKitContext未初始化及空指针异常求助

Fixes for ML Kit Text Recognition Initialization Errors

Here are targeted solutions to resolve your issues:

1. Remove Manual ML Kit Initialization

Recent versions of ML Kit (17.0.0+) automatically initialize when you first use its APIs. Calling MlKit.initialize(this) explicitly can lead to conflicts. Delete that line from your TranslateApplication.onCreate() method:

class TranslateApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        FavoriteRepository.initialize(this)
        // Remove MlKit.initialize(this)
    }
}

2. Ensure Custom Application Class is Registered

Make sure your TranslateApplication is properly declared in AndroidManifest.xml—otherwise its onCreate() won't execute:

<application
    android:name=".TranslateApplication"
    <!-- other attributes -->
    >
    <!-- activities, etc. -->
</application>

3. Lazy Initialize Text Recognition Client

Class-level properties are initialized early, which can cause context-related null issues. Use Kotlin's lazy delegate to create the client only when needed:

private val textRecognition by lazy {
    TextRecognition.getClient(TextRecognizerOptions.DEFAULT_OPTIONS)
}

private fun recognizeText(imageUri: Uri) {
    try {
        val inputImage = InputImage.fromFilePath(requireContext(), imageUri)
        lifecycleScope.launch {
            textRecognition.process(inputImage)
                .addOnSuccessListener { result ->
                    viewBinding.wordEt.text = result.text
                }
                .addOnFailureListener { e ->
                    e.printStackTrace()
                }
        }
    } catch (e: IOException) {
        e.printStackTrace()
    }
}

4. Verify Dependency Setup

Ensure you have the correct ML Kit Text Recognition dependency in your app-level build.gradle (or build.gradle.kts):

dependencies {
    // For bundled model (downloaded with app)
    implementation "com.google.mlkit:text-recognition:16.0.0"
    // OR for unbundled model (downloaded on first use)
    // implementation "com.google.mlkit:text-recognition:16.0.0-beta1"
}

If using the unbundled version, add the Google Play Services dependency for model downloading:

implementation "com.google.android.gms:play-services-tasks:18.1.0"

These steps should resolve both the IllegalStateException and NullPointerException by ensuring proper context initialization and correct API usage.

内容的提问来源于stack exchange,提问作者HaBuiDuc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 19:52:09