用Smack开发andorid IM, 开发群组时想获取服务器上所有的聊天室,调用下面方法时出现NullPointerException:
Collectionhostrooms = MultiUserChat.getHostedRooms(ClientConnectionServer.connection, ClientConnectionServer.connection.getServiceName());
而方法的2个参数都不为空,感觉很怪,就去国外论坛看了原因,查了几篇文章发现解决办法,下面是论坛里的一些信息:
The problem is that the 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 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的初始化........