获取 XMPPConnection 的空指针异常

我在本地主机上运行 openfire 服务器,Smack 版本 4.2.4.GetAllContacts() 方法中的异常。下面是我的类 XmppConnection 的代码,它扩展了类 org.jivesoftware.smack.ConnectionListener。


  public class XmppConnection implements ConnectionListener{

  private  XMPPTCPConnection mConnection;


  public List<Contact> getAllContacts() throws SmackException.NotLoggedInException, InterruptedException, SmackException.NotConnectedException {


    Log.d(TAG,"getAllContats called()");

    List<Contact> contacts = new ArrayList<>();


    if(XmppConnectService.sConnectionState == ConnectionState.AUTHENTICATED){

        Roster roster = Roster.getInstanceFor(mConnection);  //exception here


            Collection<RosterEntry> entries = roster.getEntries();

            Presence presence;


            for (RosterEntry entry : entries) {

                Contact c = new Contact(entry.getJid().toString());

                presence = roster.getPresence(entry.getJid());


                contacts.add(c);

                       }



    return contacts;


}


public XmppConnection( Context context)

{


    mApplicationContext = context.getApplicationContext();

    String jid = PreferenceManager.getDefaultSharedPreferences(mApplicationContext)

            .getString("xmpp_jid",null);

    mPassword = PreferenceManager.getDefaultSharedPreferences(mApplicationContext)

            .getString("xmpp_password",null);


    if( jid != null)

    {

        mUsername = jid.split("@")[0];

        mServiceName = jid.split("@")[1];

    }else

    {

        mUsername ="";

        mServiceName="";

    }

}


上面的代码在 logcat 中显示了这个错误:java.lang.NullPointerException: XMPPConnection must not be null


我从另一个类调用 getAllContacts() 作为


XmppConnection xmpp = new XmppConnection(this);

contacts = xmpp.getAllContacts();

getAllContacts() 方法是从另一个活动调用的,并在 authenticated() 方法之后调用。因为它是在 authenticated() 方法之后调用的,所以 mConnection 应该已经初始化了。


慕容3067478
浏览 241回答 2
2回答

有只小跳蛙

为 XmppConnection 类创建一个新对象会将其变量初始化为 null。将 XMPPTCPConnection 声明为静态工作:private&nbsp;static&nbsp;XMPPTCPConnection&nbsp;mConnection;

扬帆大鱼

如您的代码所示,您在方法 connect() 内初始化 mConnection 变量。并且您的方法authenticated() 不会调用connect() 方法。您能否确保在调用方法 authenticated() 之前或在方法内调用 connect() 方法
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java