android smack MultiUserChat.getHostedRooms( NullPointerException)

用Smack开发andorid IM, 开发群组时想获取服务器上所有的聊天室,调用下面方法时出现NullPointerException:

Collection<HostedRoom> hostrooms = MultiUserChat.getHostedRooms(ClientConnectionServer.connection, ClientConnectionServer.connection.getServiceName());

而方法的2个参数都不为空,感觉很怪,就去国外论坛看了原因,查了几篇文章发现解决办法,下面是论坛里的一些信息:

The problem is that the static block of the ServiceDiscoveryManager class has to be evaluated beforeany connection is created. In smack this is done via an configuration file, but this approach does not work on Android and therefore on aSmack.

The workaround mentioned in the answer is somehow ugly, since you really don't want to use the Constructor to fetch the SDM object, instead the get() method should be used. But the get() method only works if there was actually a SDM created for the connection.

So in order to init the SDM correctly on Android you need to call the full forName notation to init the static blocks of the class before you create the first (XMPP)Connection object.。

上面方法是针对 aSmack 问题给出的解决方法,同样也适用 纯smack 的:

所以在初始化 XMPPConnection 前先初始化ServiceDiscoveryManager,代码为:

try
{
  // 其中ClientConnectionServer.class.getClassLoader() 用来获取当前类的类加载器,如果用ClassLoader.getSystemClassLoader(),我测试的没起作用
  Class.forName(
"org.jivesoftware.smackx.ServiceDiscoveryManager", true, ClientConnectionServer.class.getClassLoader()); } catch (ClassNotFoundException e1) { e1.printStackTrace(); } // 下面是进行XMPPConnection的初始化
  ........

 

转载于:https://www.cnblogs.com/windy-love/p/3199294.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值