java - 如何让用户在 firebase 中拥有自己的聊天室和 map 标记?

标签 java android google-maps firebase

<分区>

我制作了一个应用程序,可以让用户登录并在谷歌地图上设置标记,标记连接到属于设置它的用户的聊天室。

现在的问题是无论我如何尝试,我都无法在 Chatactivity 和 MapFragment 中获取 uid,我不知道是什么问题 这是三个 Activity :

谁能帮帮我~~

登录 Activity :

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    auth = FirebaseAuth.getInstance();

    if (auth.getCurrentUser() != null) {
        startActivity(new Intent(LoginActivity.this, MainActivity.class));
        finish();
    }
    //authenticate user
    auth.signInWithEmailAndPassword(email, password)
            .addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    // If sign in fails, display a message to the user. If sign in succeeds
                    // the auth state listener will be notified and logic to handle the
                    // signed in user can be handled in the listener.
                    if (!task.isSuccessful()) {
                        // there was an error
                        if (password.length() < 6) {
                            edUserid.setError("密碼太短,請輸入超過6個字元!");
                        } else {
                            Toast.makeText(LoginActivity.this, "登入失敗", Toast.LENGTH_LONG).show();
                        }
                    } else {
                        Toast.makeText(getApplicationContext(),"登入成功",Toast.LENGTH_LONG).show();
                        startActivity(new Intent(LoginActivity.this, MainActivity.class));
                        finish();
                    }
                }
            });




}

聊天 Activity :

    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            EditText input = (EditText)findViewById(R.id.input);

            // Read the input field and push a new instance
            // of ChatMessage to the Firebase database
            FirebaseDatabase.getInstance()
                    .getReference(CHAT_PATH)
                    .push()
                    .setValue(new ChatMessage(input.getText().toString(),
                            FirebaseAuth.getInstance()
                                    .getCurrentUser()
                                    .getDisplayName())
                    );

            // Clear the input
            input.setText("");
        }
    });
    ListView listOfMessages = (ListView)findViewById(R.id.list_of_messages);

    adapter = new FirebaseListAdapter<ChatMessage>(this, ChatMessage.class,
            R.layout.message, FirebaseDatabase.getInstance().getReference(CHAT_PATH)) {
        @Override
        protected void populateView(View v, ChatMessage model, int position) {
            // Get references to the views of message.xml
            TextView messageText = (TextView)v.findViewById(R.id.message_text);
            TextView messageUser = (TextView)v.findViewById(R.id.message_user);
            TextView messageTime = (TextView)v.findViewById(R.id.message_time);

            // Set their text
            messageText.setText(model.getMessageText());
            messageUser.setText(model.getMessageUser());

            // Format the date before showing it
            messageTime.setText(DateFormat.format("dd-MM-yyyy (HH:mm:ss)",
                    model.getMessageTime()));
        }
    };

    listOfMessages.setAdapter(adapter);

}

MapFragment(部分):

        mFirebaseDatabase = FirebaseDatabase.getInstance();


        mFirebaseRef = mFirebaseDatabase.getReference("Map/"+userUID);
        mFirebaseRef.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {

                LatLng myLatLon = dataSnapshot.getValue(FirebaseMarker.class).toLatLng();

                // stash the key in the title, for recall later

                Marker myMarker = mgoogleMap.addMarker(new MarkerOptions()
                        .position(myLatLon).draggable(true).icon(BitmapDescriptorFactory.fromResource(R.drawable.seedloc2)).title(dataSnapshot.getKey()));

                // cache the marker locally
                markers.put(dataSnapshot.getKey(), myMarker);
            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {
                LatLng myLatLon = dataSnapshot.getValue(FirebaseMarker.class).toLatLng();

                // Move markers on the map if changed on Firebase
                Marker changedMarker = markers.get(dataSnapshot.getKey());
                changedMarker.setPosition(myLatLon);

            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {
                Marker deadMarker = markers.get(dataSnapshot.getKey());
                deadMarker.remove();
                markers.remove(dataSnapshot.getKey());
                Log.v(TAG, "moved !" + dataSnapshot.getValue());


            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                Log.v(TAG, "canceled!" + databaseError.getMessage());

            }
        });

    }
}

@Override
public void onMapReady(final GoogleMap googleMap) {
    MapsInitializer.initialize(getContext());

    mgoogleMap = googleMap;
    googleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener(){

        @Override
        public void onInfoWindowClick(Marker marker) {
            Intent intent = new Intent(getActivity(),ChatActivity.class);
            startActivity(intent);

        }
    });

最佳答案

你的数据库结构应该是这样的:

  • 联系人

    • [用户名]
      • 电子邮件
      • 密码
  • 标记

    • [用户名]
      • 纬度
      • 经度
      • uid

聊天

  • [用户名]
    • [来自推送的keyMessage]
      • 消息文本
      • 消息时间
      • 消息用户

通过这种结构,您可以从标记中获取聊天室 ID,并且您也可以使用 userId 从标记中显示用户信息。

与其使用来自推送的 userId,不如使用来自 firebase auth 的 uid。

auth.createUserWithEmailAndPassword(email, password)
        .addOnCompleteListener(CreateActivity.this, new 
          OnCompleteListener<AuthResult>() {

            public void onComplete( Task<AuthResult> task) {
                Toast.makeText(CreateActivity.this, "創建成功,請重新登 入", Toast.LENGTH_SHORT).show();

                // If sign in fails, display a message to the user. If sign in succeeds
                // the auth state listener will be notified and logic to handle the
                // signed in user can be handled in the listener.
                if (!task.isSuccessful()) {
                    Toast.makeText(CreateActivity.this, "認證失敗或帳號已 存在" , Toast.LENGTH_SHORT).show();
                } else {
                // insert user to database
                    FirebaseDatabase database = FirebaseDatabase.getInstance();
                    String currentUid = auth.getCurrentUser().getUid();
                    DatabaseReference myRef = database.getReference("Contacts/" + currentUid);
                    ContactInfo contact1 = new ContactInfo(email,id,password);
                    myRef.setValue(contact1);//將會員資料寫入FIREBASE
                    startActivity(new Intent(CreateActivity.this, MainActivity.class));
                    finish();
                }
            }
        });


}

关于java - 如何让用户在 firebase 中拥有自己的聊天室和 map 标记?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45262856/

相关文章:

java - 使用java代理时出错

java - 在 .properties 文件中添加注释

javascript - 为什么标记位置对象更改纬度和经度属性名称

java - OOP 的可重用性和可维护性

java - Java 中的透明度重叠

android - 扩展 SupportMapFragment 在加载 fragment 时显示全黑屏

尝试 listview.getChildAt() 时出现 java.lang.NullPointerException

android - android-support-v7-appcompat 和 android-support-v4 之间的区别

ios - 如何在 MapView IOS 中创建折线

javascript - 重新利用 map 标记进行加权热图