Android登录时出现空指针异常

Android Null Pointer Excpetion in Login

这是我的代码(activity)。我在 conn.login 方法返回空指针异常时遇到问题。我似乎不明白问题出在哪里。

Button loginButton = (Button) findViewById(R.id.loginbutton);
        loginButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                EditText userN = (EditText)findViewById(R.id.username);
                String inputUsername = userN.getText().toString(); // get the username input and store it in inputUsername

                EditText userP = (EditText)findViewById(R.id.password);
                String inputPassword = userP.getText().toString(); // get the password input and store it in inputPassword

                XMPP conn = new XMPP("192.168.1.90", inputUsername, inputPassword);
                //XMPPTCPConnection connection;

                conn.connect(); // connect to server



                try {

                        conn.login(conn.connection, inputUsername, inputPassword); // login problem here, code line 117.

                    }


                } catch (Exception e) {
                    e.printStackTrace();
                }

                Intent myIntent = new Intent(v.getContext(), MyActivity.class);
                startActivity(myIntent);

            }
        });

这是我的 xmpp class 文件。

public class XMPP{
private String serverAddress = "192.168.1.90";
private int portNumber = 5222;
public XMPPTCPConnection connection;
private String loginUser;
private String passwordUser;
public String userStatus;


//-------------Constructor----------------
public XMPP(String serverAddress, String loginUser, String passwordUser){
    this.serverAddress = serverAddress;
    this.loginUser = loginUser;
    this.passwordUser = passwordUser;
}

public void connect(){
    AsyncTask<Void, Void, Boolean> connectionThread = new AsyncTask<Void, Void, Boolean>(){
        @Override
        protected Boolean doInBackground(Void... arg0){
            boolean isConnected = false;
            ConnectionConfiguration config = new ConnectionConfiguration( serverAddress, portNumber);
            config.setReconnectionAllowed(true);
            connection = new XMPPTCPConnection(config);
            XMPPConnectionListener  connectionListener = new XMPPConnectionListener();
            connection.addConnectionListener(connectionListener);

            config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);

            try{
                connection.connect();
                isConnected = true;
            } catch (IOException e){
                e.printStackTrace();
            } catch (SmackException e){
                e.printStackTrace();
            } catch (XMPPException e){
                e.printStackTrace();
            }
            return isConnected;
        }
    };
    connectionThread.execute();
}

public void login(XMPPConnection connection, String loginUser, String passwordUser){

    this.loginUser = loginUser;
    this.passwordUser = passwordUser;

    try{

        connection.login(loginUser, passwordUser); //logcat takes me here line 93.


    } catch (SmackException.NotConnectedException e)
    {
        new Timer().schedule(new TimerTask()
        {
            @Override
            public void run()
            {
                connect();
            }
        }, 5 * 1000);
    } catch (SaslException e){
        e.printStackTrace();
    } catch (XMPPException e){
        e.printStackTrace();
    } catch (SmackException e){
        e.printStackTrace();
    } catch (IOException e){
        e.printStackTrace();
    }

}


public class XMPPConnectionListener implements ConnectionListener{
    @Override
    public void connected(final XMPPConnection connection){
        if(!connection.isAuthenticated())
            login(connection, loginUser, passwordUser); 
    }
    @Override
    public void authenticated(XMPPConnection arg0){}
    @Override
    public void connectionClosed(){}
    @Override
    public void connectionClosedOnError(Exception arg0){}
    @Override
    public void reconnectingIn(int arg0){}
    @Override
    public void reconnectionFailed(Exception arg0){}
    @Override
    public void reconnectionSuccessful(){}
    }
}

这是我的 logcat...

Reconstruct Branch:
02-13 00:00:01.995  17160-17160/com.example.haz.project1 D/OpenGLRenderer﹕ Enabling debug mode 0
02-13 00:00:03.977  17160-17160/com.example.haz.project1 W/ApplicationPackageManager﹕ getCSCPackageItemText()
02-13 00:00:03.977  17160-17160/com.example.haz.project1 I/PersonaManager﹕ getPersonaService() name persona_policy
02-13 00:00:04.087  17160-17160/com.example.haz.project1 E/ViewRootImpl﹕ sendUserActionEvent() mView == null
02-13 00:00:09.112  17160-17160/com.example.haz.project1 W/IInputConnectionWrapper﹕ getTextBeforeCursor on inactive InputConnection
02-13 00:00:09.122  17160-17160/com.example.haz.project1 W/IInputConnectionWrapper﹕ getTextAfterCursor on inactive InputConnection
02-13 00:00:12.696  17160-17160/com.example.haz.project1 W/System.err﹕ java.lang.NullPointerException
02-13 00:00:12.696  17160-17160/com.example.haz.project1 W/System.err﹕ at com.example.haz.project1.XMPP.login(XMPP.java:93)
02-13 00:00:12.706  17160-17160/com.example.haz.project1 W/System.err﹕ at com.example.haz.project1.Login.onClick(Login.java:117)
02-13 00:00:12.706  17160-17160/com.example.haz.project1 W/System.err﹕ at android.view.View.performClick(View.java:4633)
02-13 00:00:12.706  17160-17160/com.example.haz.project1 W/System.err﹕ at android.view.View$PerformClick.run(View.java:19330)
02-13 00:00:12.706  17160-17160/com.example.haz.project1 W/System.err﹕ at android.os.Handler.handleCallback(Handler.java:733)
02-13 00:00:12.706  17160-17160/com.example.haz.project1 W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:95)
02-13 00:00:12.706  17160-17160/com.example.haz.project1 W/System.err﹕ at android.os.Looper.loop(Looper.java:157)
02-13 00:00:12.706  17160-17160/com.example.haz.project1 W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:5356)
02-13 00:00:12.706  17160-17160/com.example.haz.project1 W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
02-13 00:00:12.706  17160-17160/com.example.haz.project1 W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:515)
02-13 00:00:12.706  17160-17160/com.example.haz.project1 W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
02-13 00:00:12.706  17160-17160/com.example.haz.project1 W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
02-13 00:00:12.706  17160-17160/com.example.haz.project1 W/System.err﹕ at dalvik.system.NativeStart.main(Native Method)
02-13 00:00:12.776  17160-17160/com.example.haz.project1 W/ApplicationPackageManager﹕ getCSCPackageItemText()
02-13 00:00:12.776  17160-17160/com.example.haz.project1 I/PersonaManager﹕ getPersonaService() name persona_policy
02-13 00:00:12.846  17160-17160/com.example.haz.project1 D/AbsListView﹕ Get MotionRecognitionManager
02-13 00:00:12.866  17160-17160/com.example.haz.project1 D/AbsListView﹕ onVisibilityChanged() is called, visibility : 4
02-13 00:00:12.866  17160-17160/com.example.haz.project1 D/AbsListView﹕ unregisterIRListener() is called
02-13 00:00:12.866  17160-17160/com.example.haz.project1 D/AbsListView﹕ onVisibilityChanged() is called, visibility : 0
02-13 00:00:12.866  17160-17160/com.example.haz.project1 D/AbsListView﹕ unregisterIRListener() is called
02-13 00:00:12.876  17160-17160/com.example.haz.project1 D/AbsListView﹕ unregisterIRListener() is called
02-13 00:00:12.916  17160-17160/com.example.haz.project1 D/AbsListView﹕ unregisterIRListener() is called
02-13 00:00:12.916  17160-17160/com.example.haz.project1 D/AbsListView﹕ onVisibilityChanged() is called, visibility : 4
02-13 00:00:12.916  17160-17160/com.example.haz.project1 D/AbsListView﹕ unregisterIRListener() is called
02-13 00:00:12.956  17160-17160/com.example.haz.project1 D/AbsListView﹕ unregisterIRListener() is called
02-13 00:00:12.966  17160-17160/com.example.haz.project1 D/AbsListView﹕ unregisterIRListener() is called
02-13 00:01:18.820  17160-17160/com.example.haz.project1 D/AbsListView﹕ unregisterIRListener() is called

您正在 xmpp 实例上调用 conn.connect();。 在此方法中,您将创建一个异步任务,该任务将直接执行。

主线程尝试在启动线程后直接使用conn.login(...);。 您正在尝试通过调用 its 登录函数(不幸的是此处重复命名)来访问登录函数内的连接对象。 该变量仍然为空,因为您的 AsyncTask 尚未完成(并设置它)。 (它甚至可能还没有开始。)

如果可能的话,想登录就尝试连接,不要之前。 然后在 AsyncTask 中执行 all 网络操作,以免阻塞主线程UI-线程。

  1. 用户点击按钮
  2. 将启动新的 AsyncTask
    1. 尝试连接(如果无法连接请重试)
    2. 登录
    3. 在 AsyncTak 的 onPostExecute
    4. 中向 UI 汇报

这不会阻塞 UI 线程。

注:

为什么不在 XMPP class private 中建立连接? 您仅在登录功能中使用它,它是 XMPP class 的一部分。然后你只需要调用 conn.login(username,password)