androidkotlinandroid-fragmentsfragmentappcompatactivity

how to change AppCompatActivity to Fragment?


I am a newbie at develop android app.

I want to use "Droid Speech" but I can't use it, because "Droid Speech" is made of AppCompatActivity.

I want to how to change AppCompatActivity into Fragment.

this is my code

class DroidSpeechActivity : AppCompatActivity(), View.OnClickListener,
    OnDSListener,
    OnDSPermissionsListener {
    val TAG = "Activity_DroidSpeech"
    private var droidSpeech: DroidSpeech? = null
    private var finalSpeechResult: TextView? = null

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

        setContentView(R.layout.activity_droid_speech)

        droidSpeech =
            DroidSpeech(this, fragmentManager)
        droidSpeech!!.setOnDroidSpeechListener(this)
        droidSpeech!!.setShowRecognitionProgressView(false)
        droidSpeech!!.setOneStepResultVerify(true)
        droidSpeech!!.setRecognitionProgressMsgColor(Color.WHITE)
        droidSpeech!!.setOneStepVerifyConfirmTextColor(Color.WHITE)
        droidSpeech!!.setOneStepVerifyRetryTextColor(Color.WHITE)
        droidSpeech!!.setPreferredLanguage("ko-KR")
        finalSpeechResult = findViewById(R.id.finalSpeechResult)
        start.setOnClickListener(this)
        stop.setOnClickListener(this)
    }

    override fun onPause() {
        super.onPause()
        if (stop!!.visibility == View.VISIBLE) {
            stop!!.performClick()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (stop!!.visibility == View.VISIBLE) {
            stop!!.performClick()
        }
    }

    override fun onClick(view: View) {
        when (view.id) {
            R.id.start -> {

                // Starting droid speech
                droidSpeech!!.startDroidSpeechRecognition()

                // Setting the view visibilities when droid speech is running
                start!!.visibility = View.GONE
                stop!!.visibility = View.VISIBLE
            }
            R.id.stop -> {

                // Closing droid speech
                droidSpeech!!.closeDroidSpeechOperations()
                stop!!.visibility = View.GONE
                start!!.visibility = View.VISIBLE
            }
        }
    }

    // MARK: DroidSpeechListener Methods
    override fun onDroidSpeechSupportedLanguages(currentSpeechLanguage: String, supportedSpeechLanguages: List<String>) {
        Log.i(TAG, "Current speech language = $currentSpeechLanguage")
        Log.i(TAG, "Supported speech languages = $supportedSpeechLanguages")
        if (supportedSpeechLanguages.contains("ko-KR")) {
            // Setting the droid speech preferred language as tamil if found
            droidSpeech!!.setPreferredLanguage("ko-KR")

            // Setting the confirm and retry text in tamil
            droidSpeech!!.setOneStepVerifyConfirmText("check")
            droidSpeech!!.setOneStepVerifyRetryText("no")
        }
    }

    override fun onDroidSpeechRmsChanged(rmsChangedValue: Float) {
    }

    override fun onDroidSpeechLiveResult(liveSpeechResult: String) {
        Log.i(TAG, "Live speech result = $liveSpeechResult")
    }

    override fun onDroidSpeechFinalResult(finalSpeechResult: String) {
        this.finalSpeechResult!!.text = finalSpeechResult
        println("test$finalSpeechResult")
        if (droidSpeech!!.continuousSpeechRecognition) {
            val colorPallets1 = intArrayOf(Color.RED, Color.GREEN, Color.BLUE, Color.CYAN, Color.MAGENTA)
            val colorPallets2 = intArrayOf(Color.YELLOW, Color.RED, Color.CYAN, Color.BLUE, Color.GREEN)

            // Setting random color pallets to the recognition progress view
            droidSpeech!!.setRecognitionProgressViewColors(if (Random().nextInt(2) == 0) colorPallets1 else colorPallets2)
        } else {
            stop!!.visibility = View.GONE
            start!!.visibility = View.VISIBLE
        }
    }

    override fun onDroidSpeechClosedByUser() {
        stop!!.visibility = View.GONE
        start!!.visibility = View.VISIBLE
    }

    override fun onDroidSpeechError(errorMsg: String) {
        Toast.makeText(this, errorMsg, Toast.LENGTH_LONG).show()
        stop!!.post {
            stop!!.performClick()
        }
    }

    // MARK: DroidSpeechPermissionsListener Method
    override fun onDroidSpeechAudioPermissionStatus(audioPermissionGiven: Boolean, errorMsgIfAny: String) {
        if (audioPermissionGiven) {
            start!!.post {
                start!!.performClick()
            }
        } else {
            if (errorMsgIfAny != null) {
                Toast.makeText(this, errorMsgIfAny, Toast.LENGTH_LONG).show()
            }
            stop!!.post {
                stop!!.performClick()
            }
        }
    }
}

this is try to change code...but err

class DroidSpeechActivity : Fragment(), View.OnClickListener,
    OnDSListener,
    OnDSPermissionsListener {
    val TAG = "Activity_DroidSpeech"
    private var droidSpeech: DroidSpeech? = null
    private var finalSpeechResult: TextView? = null

    // MARK: Activity Methods
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // Setting the layout;[.

        // Initializing the droid speech and setting the listener

        droidSpeech =
            DroidSpeech(activity?.applicationContext, activity?.getFragmentManager())
        droidSpeech!!.setOnDroidSpeechListener(this)
        droidSpeech!!.setShowRecognitionProgressView(false)
        droidSpeech!!.setOneStepResultVerify(true)
        droidSpeech!!.setRecognitionProgressMsgColor(Color.WHITE)
        droidSpeech!!.setOneStepVerifyConfirmTextColor(Color.WHITE)
        droidSpeech!!.setOneStepVerifyRetryTextColor(Color.WHITE)
        droidSpeech!!.setPreferredLanguage("ko-KR")
        start.setOnClickListener(this)
        stop.setOnClickListener(this)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.activity_droid_speech, container, false)
    }

    override fun onPause() {
        super.onPause()
        if (stop!!.visibility == View.VISIBLE) {
            stop!!.performClick()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (stop!!.visibility == View.VISIBLE) {
            stop!!.performClick()
        }
    }

    // MARK: OnClickListener Method
    override fun onClick(view: View) {
        when (view.id) {
            R.id.start -> {

                // Starting droid speech
                droidSpeech!!.startDroidSpeechRecognition()

                // Setting the view visibilities when droid speech is running
                start!!.visibility = View.GONE
                stop!!.visibility = View.VISIBLE
            }
            R.id.stop -> {

                // Closing droid speech
                droidSpeech!!.closeDroidSpeechOperations()
                stop!!.visibility = View.GONE
                start!!.visibility = View.VISIBLE
            }
        }
    }

    // MARK: DroidSpeechListener Methods
    override fun onDroidSpeechSupportedLanguages(currentSpeechLanguage: String, supportedSpeechLanguages: List<String>) {
        Log.i(TAG, "Current speech language = $currentSpeechLanguage")
        Log.i(TAG, "Supported speech languages = $supportedSpeechLanguages")
        if (supportedSpeechLanguages.contains("ko-KR")) {
            // Setting the droid speech preferred language as tamil if found
            droidSpeech!!.setPreferredLanguage("ko-KR")

            // Setting the confirm and retry text in tamil
            droidSpeech!!.setOneStepVerifyConfirmText("check")
            droidSpeech!!.setOneStepVerifyRetryText("no")
        }
    }

    override fun onDroidSpeechRmsChanged(rmsChangedValue: Float) {
        // Log.i(TAG, "Rms change value = " + rmsChangedValue);
    }

    override fun onDroidSpeechLiveResult(liveSpeechResult: String) {
        Log.i(TAG, "Live speech result = $liveSpeechResult")
    }

    override fun onDroidSpeechFinalResult(finalSpeechResult: String) {
        // Setting the final speech result
        this.finalSpeechResult!!.text = finalSpeechResult
        println("test$finalSpeechResult")
        if (droidSpeech!!.continuousSpeechRecognition) {
            val colorPallets1 = intArrayOf(Color.RED, Color.GREEN, Color.BLUE, Color.CYAN, Color.MAGENTA)
            val colorPallets2 = intArrayOf(Color.YELLOW, Color.RED, Color.CYAN, Color.BLUE, Color.GREEN)

            // Setting random color pallets to the recognition progress view
            droidSpeech!!.setRecognitionProgressViewColors(if (Random().nextInt(2) == 0) colorPallets1 else colorPallets2)
        } else {
            stop!!.visibility = View.GONE
            start!!.visibility = View.VISIBLE
        }
    }

    override fun onDroidSpeechClosedByUser() {
        stop!!.visibility = View.GONE
        start!!.visibility = View.VISIBLE
    }

    override fun onDroidSpeechError(errorMsg: String) {
        // Speech error
        stop!!.post { // Stop listening
            stop!!.performClick()
        }
    }

    // MARK: DroidSpeechPermissionsListener Method
    override fun onDroidSpeechAudioPermissionStatus(audioPermissionGiven: Boolean, errorMsgIfAny: String) {
        if (audioPermissionGiven) {
            start!!.post { // Start listening
                start!!.performClick()
            }
        } else {
            if (errorMsgIfAny != null) {
                // Permissions error
            }
            stop!!.post { // Stop listening
                stop!!.performClick()
            }
        }
    }
}

this is err message


java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
        at com.example.Jachi3kki.DroidSpeechActivity.onCreateView(DroidSpeechActivity.kt:49)

DroidSpeechActivity.kt:49 line is this

start.setOnClickListener(this)

how to convert my AppCompatActivity to fragment?


Solution

  • Your code has some problems:

    1. It's usually better to use the optional ? operator and don't force the cast with !! to avoid a crash by NullPointerException
    2. You need to initialize your views in the onCreateView method by referring to the view instance.
      Unlike activities, fragments don't call the setContentView method, so you can't refer directly to the layout items.

    In my code I used the inline method setOnClickListener and I assumed that start and stop are Buttons, if it's not the case you just need to change the type of the two views in their declaration.

    Try to change your fragment's code like this:

    class DroidSpeechActivity : Fragment(), 
        OnDSListener,
        OnDSPermissionsListener {
    
        val TAG = "Activity_DroidSpeech"
    
        private var droidSpeech: DroidSpeech? = null
        private var finalSpeechResult: TextView? = null
        private var start: Button? = null
        private var stop: Button? = null
    
        // MARK: Activity Methods
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
    
            // Initializing the droid speech and setting the listener
            droidSpeech = DroidSpeech(requireActivity().applicationContext, requireActivity().getFragmentManager()).apply {
                setOnDroidSpeechListener(this)
                setShowRecognitionProgressView(false)
                setOneStepResultVerify(true)
                setRecognitionProgressMsgColor(Color.WHITE)
                setOneStepVerifyConfirmTextColor(Color.WHITE)
                setOneStepVerifyRetryTextColor(Color.WHITE)
                setPreferredLanguage("ko-KR")
            }
        }
    
        override fun onCreateView(
            inflater: LayoutInflater,
            container: ViewGroup?,
            savedInstanceState: Bundle?
        ): View? {
            val view = inflater.inflate(R.layout.activity_droid_speech, container, false)
    
            finalSpeechResult = view.findViewById<TextView>(R.id.finalSpeechResult)
    
            start = view.findViewById<Button>(R.id.start).apply {
                setOnClickListener { startClicked() }
            }
            stop = view.findViewById<Button>(R.id.start).apply {
                setOnClickListener { stopClicked() }
            }
    
            return view
        }
    
        override fun onPause() {
            super.onPause()
            
            if (stop?.visibility == View.VISIBLE) {
                stop?.performClick()
            }
        }
    
        override fun onDestroy() {
            super.onDestroy()
            
            if (stop?.visibility == View.VISIBLE) {
                stop?.performClick()
            }
        }
    
        private fun startClicked() {
            droidSpeech?.startDroidSpeechRecognition()
    
            // Setting the view visibilities when droid speech is running
            start?.visibility = View.GONE
            stop?.visibility = View.VISIBLE
        }
    
        private fun stopClicked() {
            droidSpeech?.closeDroidSpeechOperations()
    
            stop?.visibility = View.GONE
            start?.visibility = View.VISIBLE
        }
    
        // MARK: DroidSpeechListener Methods
        override fun onDroidSpeechSupportedLanguages(currentSpeechLanguage: String, supportedSpeechLanguages: List<String>) {
            Log.i(TAG, "Current speech language = $currentSpeechLanguage")
            Log.i(TAG, "Supported speech languages = $supportedSpeechLanguages")
            if (supportedSpeechLanguages.contains("ko-KR")) {
                // Setting the droid speech preferred language as tamil if found
                droidSpeech?.setPreferredLanguage("ko-KR")
    
                // Setting the confirm and retry text in tamil
                droidSpeech?.setOneStepVerifyConfirmText("check")
                droidSpeech?.setOneStepVerifyRetryText("no")
            }
        }
    
        override fun onDroidSpeechRmsChanged(rmsChangedValue: Float) {
            // Log.i(TAG, "Rms change value = " + rmsChangedValue);
        }
    
        override fun onDroidSpeechLiveResult(liveSpeechResult: String) {
            Log.i(TAG, "Live speech result = $liveSpeechResult")
        }
    
        override fun onDroidSpeechFinalResult(finalSpeechResult: String) {
            // Setting the final speech result
            finalSpeechResult?.text = finalSpeechResult
            println("test$finalSpeechResult")
            if (droidSpeech?.continuousSpeechRecognition == true) {
                val colorPallets1 = intArrayOf(Color.RED, Color.GREEN, Color.BLUE, Color.CYAN, Color.MAGENTA)
                val colorPallets2 = intArrayOf(Color.YELLOW, Color.RED, Color.CYAN, Color.BLUE, Color.GREEN)
    
                // Setting random color pallets to the recognition progress view
                droidSpeech?.setRecognitionProgressViewColors(if (Random().nextInt(2) == 0) colorPallets1 else colorPallets2)
            } else {
                stop?.visibility = View.GONE
                start?.visibility = View.VISIBLE
            }
        }
    
        override fun onDroidSpeechClosedByUser() {
            stop?.visibility = View.GONE
            start?.visibility = View.VISIBLE
        }
    
        override fun onDroidSpeechError(errorMsg: String) {
            // Speech error
            stop?.post { // Stop listening
                stop?.performClick()
            }
        }
    
        // MARK: DroidSpeechPermissionsListener Method
        override fun onDroidSpeechAudioPermissionStatus(audioPermissionGiven: Boolean, errorMsgIfAny: String) {
            if (audioPermissionGiven) {
                start?.post { // Start listening
                    start?.performClick()
                }
            } else {
                if (errorMsgIfAny != null) {
                    // Permissions error
                }
                stop?.post { // Stop listening
                    stop?.performClick()
                }
            }
        }
    }