How to get a static logger from a fragment in android?

77 Views Asked by At

Here is what I want to do:

I have an app with basically no GUI whatsoever, just a lot of stuff going on in the background (app is basically just a LAN remote control for the camera, so I have camera classes, network classes and so on running in the background. However, I want to have a simple TextView on my GUI, that will display some sort of log. All of my classes should have access to this log and add/write stuff. Since my GUI consists only of a single textview, I don't want to bother with MVVM, which would be my go-to GUI pattern.

What I have so far:

For the TextView, I created a Fragment:

class GUIFragment : Fragment(R.layout.gui_fragment) {


    // other class members
    private lateinit var logger : Logger

    private var _binding: GuiFragmentBinding? = null
    private val guiBinding get() = _binding!!

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        retainInstance = true
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        //set up bindings
        _binding = GuiFragmentBinding.inflate(inflater, container, false)
        guiBinding.logviewer.movementMethod = ScrollingMovementMethod()
        logger = Logger(guiBinding.logviewer)
        return guiBinding.root


    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    // other logic 

    companion object {
        fun getLogger() : Logger?{
            return null // or my logger instance
        }
    }
}

The idea here is to have a static method, which returns either the fragments logger instance or null (since the GUI doesn't change at all, it should in reality always return the logger instance. The logger itself is a member of the fragment and gets the bound TextView passed to it's constructor. However, I suppose companion objects have no access to class members (which makes sense, since those are none-static)? Should my logger member be static too, but then how should I pass the TextView to it?

For completeness sake here is the Logger class too:

class Logger (_tv : TextView) {

    private val maxLogLines = 100
    private val tv = _tv

    suspend fun log(msg: String?) = withContext(Dispatchers.Main){
        var logtext = tv.text.toString()
        logtext = logtext.plus("${msg}\n")
        var split = logtext.split("\n")


        if (split.count() >= maxLogLines) {
            logtext = split.slice(1 until (maxLogLines - 1)).joinToString("\n")
        }
        tv.text = logtext
    }
}
0

There are 0 best solutions below