Android - 为什么会返回第一个活动

时间:2016-10-28 16:03:25

标签: android firebase firebase-realtime-database

我正在使用Firebase作为数据库开发聊天应用。 在应用程序中我有3个活动:LoginActivity,MainActivity和chatActivity。 在MainActivity中,我可以打开聊天室,然后进入聊天室。 然后它打开chatActivity。 在聊天活动中,用户可以相互发送消息。在这里我的问题是。当用户键入消息并按发送时。出于某种原因,当用户按下SEND按钮时,它会跳转到mainActivity inst并发送消息。我不知道最新情况,我需要你的帮助。

主要活动代码

    package com.world.bolandian.firebase;


 public class MainActivity extends AppCompatActivity {

private Button createChat;
private EditText chatRoomName;
private ListView listView;
private ArrayAdapter<String> arrayAdapter;
private ArrayList<String> listOfChats = new ArrayList<>();
private String name;
private DatabaseReference root  = FirebaseDatabase.getInstance().getReference().getRoot();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
       ifUserIsLoggedIn();

    createChat = (Button)findViewById(R.id.createChatBtn);
    chatRoomName = (EditText)findViewById(R.id.chatRoomEt);
    listView = (ListView)findViewById(R.id.listView);

    arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line, listOfChats);

    listView.setAdapter(arrayAdapter);

    enterUserName();

    createChat.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Map<String, Object> map = new HashMap<String, Object>();
            map.put(chatRoomName.getText().toString(), "");
            root.updateChildren(map);
        }
    });

    root.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            Set<String> set = new HashSet<String>();
            Iterator i = dataSnapshot.getChildren().iterator();

            while (i.hasNext()) {
                set.add(((DataSnapshot) i.next()).getKey());
            }
            listOfChats.clear();
            listOfChats.addAll(set);
            arrayAdapter.notifyDataSetChanged();
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            Intent intent = new Intent(getApplicationContext(),ChatRoom.class);
            intent.putExtra("roomName",((TextView)view).getText().toString());
            intent.putExtra("userName",name);
            startActivity(intent);
        }
    });


      }


private void ifUserIsLoggedIn(){

    FirebaseAuth auth = FirebaseAuth.getInstance();
    FirebaseUser user = auth.getCurrentUser();
    if(user != null){

    }
    else
        startActivity(new Intent(this,LoginActivity.class));
}


    private void enterUserName(){

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Please enter A nick name:");

       final EditText input = new EditText(this);

        builder.setView(input);
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                name = input.getText().toString();
            }
        });

        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
                enterUserName();
            }
        });
        builder.show();
     }

   }

这是ChatActivity

  public class ChatRoom extends AppCompatActivity {

private Button sendMessageBtn;
private EditText inputMsg;
private TextView showMessage;
private DatabaseReference root;
private String userName,chatName,tempKey;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_chat_room);


    sendMessageBtn = (Button)findViewById(R.id.sendmessagebtn);
    inputMsg = (EditText)findViewById(R.id.messageEt);
    showMessage = (TextView)findViewById(R.id.showMessage);

    userName = getIntent().getExtras().get("userName").toString();
    chatName = getIntent().getExtras().get("roomName").toString();
    Log.v("username",userName);
    Log.v("chatname",chatName);

    setTitle(" Room " + chatName);

    root = FirebaseDatabase.getInstance().getReference().child(chatName);

    sendMessageBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Map<String,Object> map = new HashMap<String, Object>();
            tempKey = root.push().getKey();
            root.updateChildren(map);

            DatabaseReference messageRoot = root.child(tempKey);
            Map<String,Object> map2 = new HashMap<String, Object>();
            map2.put("name",userName);
            map2.put("message",inputMsg);

            messageRoot.updateChildren(map2);
        }
    });


    root.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {

            chatConversation(dataSnapshot);
        }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {

            chatConversation(dataSnapshot);
        }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {

        }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

}

private String chatMsg,chatUserName;

private void chatConversation(DataSnapshot dataSnapshot){

    Iterator i = dataSnapshot.getChildren().iterator();
        while(i.hasNext()){
            chatMsg = (String)((DataSnapshot)i.next()).getValue();
            chatUserName = (String)((DataSnapshot)i.next()).getValue();

            showMessage.append(chatUserName + " : " + chatMsg +"\n" );
        }
    }
 }

那是代码人员

1 个答案:

答案 0 :(得分:0)

最后我发现了我的错误。

        DatabaseReference messageRoot = root.child(tempKey);
        Map<String,Object> map2 = new HashMap<String, Object>();
        map2.put("name",userName);
        map2.put("message",inputMsg); -- thats the line that crash the app

       **map2.put("message",inputMsg.getText().toString());** should be like that

        messageRoot.updateChildren(map2);