How to use ConnectionListener interface?

I am new to Xmpp and am confused right now.When I add a new Toast to the ConnectionListener interface methods the Toast does not show up in the application.

My code:

conn2.addConnectionListener(new ConnectionListener()

`````` {``

`` @Override
public void connected(XMPPConnection xmppConnection)
{
Toast.makeText(getApplicationContext(), “connected”, Toast.LENGTH_LONG).show();
}

@Override
public void authenticated(XMPPConnection xmppConnection, boolean b)
{
Toast.makeText(getApplicationContext(), “authenticated”, Toast.LENGTH_LONG).show();
}

@Override
public void connectionClosed()
{
Toast.makeText(getApplicationContext(), “conclose”, Toast.LENGTH_LONG).show();
}

@Override
public void connectionClosedOnError(Exception e)
{
Toast.makeText(getApplicationContext(), “conclose”, Toast.LENGTH_LONG).show();
}

@Override
public void reconnectionSuccessful()
{
Toast.makeText(getApplicationContext(), “reconnect”, Toast.LENGTH_LONG).show();
}

@Override
public void reconnectingIn(int i)
{
Toast.makeText(getApplicationContext(), “reconnect”, Toast.LENGTH_LONG).show();
}

@Override
public void reconnectionFailed(Exception e)
{

}
});``

This is what I expect the code to do:Whenever a connection is established there should be a new Toast that appears on the screen saying “Connected”.What am I doing wrong.Is it the wrong way to do this?

May be you can update UI in main thread!

Thanks for the reply

I changed my code like this

conn2.addConnectionListener(new ConnectionListener()

{

@Override
public void connected(XMPPConnection xmppConnection)

{

Toast.makeText(MainActivity.this, “connected (in connectionlistener”, Toast.LENGTH_LONG).show();

}

but still it is not showing Toast when connection is eastablished.Correct me if I am wrong.I am newbie in android development.

You’re still doing wrong. Try this:

@Override
public void connected(XMPPConnection xmppConnection) {

new Handler(Looper.getMainLooper()).post(new Runnable() {

@Override
public void run() {

//here write your code to update UI.
}

});
}


But this is still not a recommended way to update UI. You should new a Handler instance to handle ui updating, or use BroadcastReceiver.