'How to pass XMPPAbstractConnection from Smack XMPP library to viewpager fragment in Android?

I'm building a chat app using the Smack XMPP library. The structure of my app is the following:

  • MainActivity which holds a login screen and sends me to my main fragment using Intent. This can be ignored as I don't do anything else with it once it calls MainScreen.
  • class MainScreen : AppCompatActivity() which has a nav_graph and loads another fragment called DataFragment with some data.
  • DataFragment that has a ViewPager inside with several other SubFragments.
    • ChatFragment loaded using the ViewPager which will present all the available users in the server to chat with.

I managed to successfully connect to my XMPP Server inside MainScreen using the following code:

    lateinit var connection: AbstractXMPPConnection
    lateinit var chatManager: ChatManager
    //Takes care of connecting to an XMPP Server.
    fun xmppConn(userName: String, userPass: String, xmppDomain: String): AbstractXMPPConnection? {
        try {
            val config = XMPPTCPConnectionConfiguration.builder()
                .setUsernameAndPassword(userName, userPass)
                .setSecurityMode(ConnectionConfiguration.SecurityMode.ifpossible)
                .setXmppDomain(xmppDomain)
                .setPort(8222)
                .build()

            connection = XMPPTCPConnection(config) as AbstractXMPPConnection
            connection?.connect()?.login()

            if(connection.isAuthenticated){
                //Tell the server that we're online.
                val presence: Presence = Presence(Presence.Type.available)
                connection.sendStanza(presence)
            }

now I want to keep that connection alive and send it to my ChatFragment so that it can call the send message methods. I noticed that if I abstract the connection in a class, then creating a new instance inside ChatFragment will restart my connection and replace it with a new one. I also tried Bundling the connection but it seems Bundles don't accept XMPPAbstractConnection data types and I don't call the ChatFragment directly since its loaded in my viewpager rather than loaded using an Intent.

I read a lot and it seems its possible to reference the same class using interfaces? I'm fairly new to Android programming so any suggestions will be welcome.

  • How can I call chat events such as send(message) from the ChatFragment when my connection is made in its parent MainScreen Activity? Do I send data from the Activity through the ViewPager and somehow make it reach ChatFragment or is there a better way?


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source