Android 无法在恢复时启动活动组件信息

Android 无法在恢复时启动活动组件信息,android,xmpp,Android,Xmpp,我的应用程序工作正常,但当应用程序转到后台时,它会在应该恢复时崩溃。 正如您在源代码中看到的,我记录了onStart、onStop等事件 在我的日志中,我可以在启动应用程序时看到onStart、onResume。当我按back键时,我看到:onStop、STOP、onPause和onDestroy 当我尝试重新启动应用程序时,它会立即崩溃,日志中没有其他消息,除了“无法启动Activity ComponentInfo java lang.NullPointerException” 我怎样才能防止

我的应用程序工作正常,但当应用程序转到后台时,它会在应该恢复时崩溃。 正如您在源代码中看到的,我记录了onStart、onStop等事件

在我的日志中,我可以在启动应用程序时看到onStart、onResume。当我按back键时,我看到:onStop、STOP、onPause和onDestroy

当我尝试重新启动应用程序时,它会立即崩溃,日志中没有其他消息,除了“无法启动Activity ComponentInfo java lang.NullPointerException”

我怎样才能防止这种情况

public class Start extends Activity {

private Handler handler = new Handler();
private ArrayList<String> discussionThread;
private EditText textMessage;

private ListView listview;

private ConnectionConfiguration config;
private Presence presence;
private MultiUserChat muc;
private DiscussionHistory history;
private PacketFilter filter;
private MyCustomAdapter discussionThreadAdapter;
private XMPPConnection connection;


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    try {
        initConnection();
    } catch (XMPPException e) {
        e.printStackTrace();
    }

    final EditText textMessage = (EditText) this.findViewById(R.id.message);        
    listview = (ListView) this.findViewById(R.id.list);

    discussionThread = new ArrayList<String>();
    discussionThreadAdapter = new MyCustomAdapter();
    listview.setAdapter(discussionThreadAdapter);

    Button send = (Button) this.findViewById(R.id.send);
    send.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            String text = textMessage.getText().toString();

            Message msg = new Message(ROOM, Message.Type.groupchat);
            msg.setBody(text);
            connection.sendPacket(msg);
            discussionThreadAdapter.notifyDataSetChanged();
            textMessage.setText("");
        }
    });


    textMessage.setOnKeyListener(new OnKeyListener()
    {
        public boolean onKey(View v, int keyCode, KeyEvent event)
        {
            if (event.getAction() == KeyEvent.ACTION_DOWN)
            {
                switch (keyCode)
                {
                    case KeyEvent.KEYCODE_DPAD_CENTER:
                    case KeyEvent.KEYCODE_ENTER:
                        SendText();
                        return true;
                    default:
                        break;
                }
            }
            return false;
        }
    });
}


private void initConnection() throws XMPPException {
    config = new ConnectionConfiguration(SERVER_HOST, SERVER_PORT, SERVICE_NAME);
    connection = new XMPPConnection(config);
    connection.connect();
    connection.login(LOGIN, PASSWORD);
    presence = new Presence(Presence.Type.available);

    connection.sendPacket(presence);

    muc = new MultiUserChat(connection, ROOM);
    history = new DiscussionHistory();

    history.setMaxStanzas(25);

    muc.join(LOGIN, PASSWORD, history, SmackConfiguration.getPacketReplyTimeout());

    filter = new MessageTypeFilter(Message.Type.groupchat);

    connection.addPacketListener(new PacketListener() {

        public void processPacket(Packet packet) {
            Message message = (Message) packet;
            if (message.getBody() != null) {
                String fromName = message.getFrom().substring(48);
                String nieuweRegel = fromName + ": " + message.getBody();

                fromName = fromName.toUpperCase();

                if (fromName.equals(LOGIN.toUpperCase())) {
                    discussionThreadAdapter.addVanMijItem(nieuweRegel);
                } else {
                    discussionThreadAdapter.addVanAnderItem(nieuweRegel);
                }

            }
        }
    }, filter);

}

private void Notify() {
    discussionThreadAdapter.notifyDataSetChanged();
    listview.setSelection(discussionThreadAdapter.getCount());
}

private class MyCustomAdapter extends BaseAdapter {

    private static final int BERICHT_VAN_ANDER = 0;
    private static final int BERICHT_VAN_MIJ = 1;
    private static final int TYPE_MAX_COUNT = BERICHT_VAN_MIJ + 1;

    private LayoutInflater mInflater;

    private TreeSet<Integer> mySet = new TreeSet<Integer>();

    public MyCustomAdapter() {
        mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public void addVanAnderItem(final String item) {
        discussionThread.add(item);
        handler.post(new Runnable() {
            public void run() {
                Notify();
            }
        });

    }

    public void addVanMijItem(final String item) {
        discussionThread.add(item);
        mySet.add(discussionThread.size() - 1);
        handler.post(new Runnable() {
            public void run() {
                Notify();
            }
        });
    }

    @Override
    public int getItemViewType(int position) {
        return mySet.contains(position) ? BERICHT_VAN_MIJ : BERICHT_VAN_ANDER;
    }

    @Override
    public int getViewTypeCount() {
        return TYPE_MAX_COUNT;
    }

    @Override
    public int getCount() {
        return discussionThread.size();
    }

    @Override
    public String getItem(int position) {
        return discussionThread.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        int type = getItemViewType(position);
        if (convertView == null) {
            holder = new ViewHolder();
            switch (type) {
                case BERICHT_VAN_ANDER:
                    convertView = mInflater.inflate(R.layout.bericht_van_ander_item, null);
                    holder.textView = (TextView)convertView.findViewById(R.id.textline);
                    break;
                case BERICHT_VAN_MIJ:
                    convertView = mInflater.inflate(R.layout.bericht_van_mij_item, null);
                    holder.textView = (TextView)convertView.findViewById(R.id.textline);
                    break;
            }
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder)convertView.getTag();
        }
        holder.textView.setText(discussionThread.get(position));
        return convertView;
    }

}

public static class ViewHolder {
    public TextView textView;
}

private void SendText() {

    InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(textMessage.getWindowToken(), 0);

    String text = textMessage.getText().toString();

    Message msg = new Message(ROOM, Message.Type.groupchat);
    msg.setBody(text);
    connection.sendPacket(msg);
    textMessage.setText("");
}

public void onStart() {
    super.onStart();
    Log.i("CONN", "onStart");
    startConnection();
}

public void onRestart() {
    super.onRestart();
    Log.i("CONN", "onReStart");
    startConnection();
}

public void onResume() {
    super.onResume();
    Log.i("CONN", "onResume");
    startConnection();
}

public void onPause() {
    super.onPause();
    Log.i("CONN", "onPause");
    stopConnection();

}

public void onStop() {
    super.onStop();
    Log.i("CONN", "onStop");
    stopConnection();
}

public void onDestroy() {
    super.onDestroy();
    Log.i("CONN", "onDestroy");
    stopConnection();
}

private void stopConnection() {

    if (connection != null) {

        Log.i("CONN", "STOP");

        connection.disconnect(presence);

        connection = null;
        filter = null;
        history = null;
        muc = null;
        presence = null;
        config = null;
        discussionThreadAdapter = null;


    }

}

private void startConnection() {

    if (connection.isConnected() ) {

    } else {

        Log.i("CONN", "START");

        try {
            initConnection();
        } catch (XMPPException e) {
            e.printStackTrace();
        }
    }
}
我启动应用程序,一切正常。日志:

05-12 08:40:21.743:D/AndroidRuntime(491):>>>>>>>>>>>>>>> AndroidRuntime开始>
AndroidRuntime START您在
stopConnection
方法
null
中设置为
connection
,因此当您尝试执行检查
if(connection.isConnected())
时,您会收到
null
,因为您设置了它。如果
connection
不是
null
的话,你应该签入
startConnection
方法,否则你必须调用
initConnection
方法。

你在
stopConnection
方法
null
中设置了
connection
所以当你试图做的时候,检查
if(connection.isConnected())
您将收到
null
,因为您设置了它。如果
connection
不是
null
的话,你应该签入
startConnection
方法,否则你必须调用
initConnection
方法。

而Marek的答案肯定是正确的(这可能就是你得到
null点异常的原因),我知道的一件事是,您不应该试图在UI线程上建立连接。如果建立连接需要几秒钟以上的时间,这将不可避免地导致应用程序崩溃。您应该创建一个
AsnycTask
,并在那里更改连接和状态。

虽然Marek的回答肯定没有错(这可能是您得到
NullPointerException
的原因),但我知道,您不应该尝试在UI线程上建立连接。如果建立连接需要几秒钟以上的时间,这将不可避免地导致应用程序崩溃。您应该创建一个
AsnycTask
,并在那里更改连接和状态。

您可以发布日志猫输出吗?转到“窗口-->显示视图-->其他视图”,然后查找并单击“日志猫”。然后运行程序,直到获得
NullPointerException
,然后在此处发布相关的logcat输出(告诉您发生
NullPointerException
的代码)。您还应该告诉我们发生了
NullPointerException
的哪一行(因为我们不知道确切的行号)。您可以发布日志猫输出吗?转到“窗口-->显示视图-->其他视图”,然后查找并单击“日志猫”。然后运行程序,直到获得
NullPointerException
,然后在此处发布相关的logcat输出(告诉您发生
NullPointerException
的代码)。您还应该告诉我们发生了
NullPointerException
的哪一行(因为我们不知道确切的行号)。您可能希望对内联代码使用勾号(shift+~),而不是粗体:)我在
if(connection==null)中更改了它{
但这没有任何区别。在我的日志中,我看不到类似onResume或onRestart的内容,因此应用程序永远不会到达该事件。您可能希望对内联代码使用勾号(shift+~)而不是粗体:)我在
if(connection==null)中更改了它{
但这没有任何区别。在我的日志中,我看不到任何类似于onResume或onRestart的内容,因此应用程序永远不会到达该事件OK。我会更改它。但我仍然不明白为什么永远不会到达onResume或onRestart事件。我只能在第一次启动应用程序时在日志中看到事件。我认为我可以解决这个问题通过将
System.exit(0)
放入stopConnection()可以。我会更改它。但我仍然不明白为什么从来没有到达onResume或onRestart事件。我只能在第一次启动应用程序时在日志中看到事件。我想我可以通过将
System.exit(0)
放入stopConnection()来解决问题
   private void startConnection() {

    if (connection != null ) {

        Log.i("CONN", "RUNNING");

    } else {

        Log.i("CONN", "START");

        try {
            initConnection();
        } catch (XMPPException e) {
            e.printStackTrace();
        }
    }
}