我创建了一个应用程序,可让用户登录并在谷歌地图上设置标记,标记连接到属于设置它的用户的聊天室。
我使用firebase邮件身份验证,问题是我无法获取uid并且它无效,我尝试了很多方法,但它仍然无法正常工作。
实际上我可以使用uid在createActivity中使用firebase中的帐户数据,但是当我切换到其他活动时,uid变为null,我之前会问这个,有人告诉我使用这段代码:
Intent intent = new Intent(CreateActivity.this, MainActivity.class);
intent.putExtra("uid", currentUid);
startActivity(intent);
但它没有用。
有人可以帮我找到问题所在,这是我的相关代码:
LoginActivity:
public void login(View v){
final EditText edUserid = (EditText) findViewById(R.id.eduser);
final EditText edPass = (EditText) findViewById(R.id.edpass);
final String email = edUserid.getText().toString();
final String password = edPass.getText().toString();
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "請輸入電子郵件!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "請輸入密碼", Toast.LENGTH_SHORT).show();
return;
}
//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();
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
auth = FirebaseAuth.getInstance();
FirebaseUser user = auth.getCurrentUser();
String currentUid = user.getUid();
intent.putExtra("uid", currentUid);
startActivity(intent);
finish();
}
}
});
}
CreateActivity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create);
auth = FirebaseAuth.getInstance();
FirebaseDatabase database = FirebaseDatabase.getInstance();
final DatabaseReference myRef = database.getReference();
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public void create(View v){
EditText Edcount = (EditText)findViewById(R.id.edcount);
EditText Edpass = (EditText)findViewById(R.id.edpass);
EditText Eduser = (EditText)findViewById(R.id.userid);
EditText Edpassag = (EditText)findViewById(R.id.edpassag);
final String email = Edcount.getText().toString().trim();
final String id = Eduser.getText().toString().trim();
final String password = Edpass.getText().toString().trim();
String password2 = Edpassag.getText().toString();
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "請輸入電子郵件!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(id)) {
Toast.makeText(getApplicationContext(), "請輸入用戶名!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "請輸入密碼!", Toast.LENGTH_SHORT).show();
return;
}
if (password.length() < 6) {
Toast.makeText(getApplicationContext(), "密碼太短,請輸入超過6個字元!", Toast.LENGTH_SHORT).show();
return;
}
if(!password.equals(password2)){
Toast.makeText(getApplicationContext(), "密碼前後不符!", Toast.LENGTH_SHORT).show();
return;
}
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(CreateActivity.this, new OnCompleteListener<AuthResult>() {
public void onComplete( Task<AuthResult> task) {
Toast.makeText(CreateActivity.this, "創建成功,歡迎使用SeeDate", 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 {
FirebaseDatabase database = FirebaseDatabase.getInstance();
FirebaseUser user = auth.getCurrentUser();
String currentUid = user.getUid();
DatabaseReference myRef = database.getReference("Contacts/" + currentUid);
ContactInfo contact1 = new ContactInfo(email,id,password);
myRef.setValue(contact1);//將會員資料寫入FIREBASE
Intent intent = new Intent(CreateActivity.this, MainActivity.class);
intent.putExtra("uid", currentUid);
startActivity(intent);
finish();
}
}
});
}
}
MainActivity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
auth = FirebaseAuth.getInstance();
//get current user
authListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
auth = FirebaseAuth.getInstance();
FirebaseUser user = auth.getCurrentUser();
if (user != null) {
// user auth state is changed - user is null
// launch login activity
userUID = getIntent().getStringExtra("uid");
}
else{
startActivity(new Intent(MainActivity.this, LoginActivity.class));
finish();
}
}
};
}
public void onStart() {
super.onStart();
auth.addAuthStateListener(authListener);
}
@Override
public void onStop() {
super.onStop();
if (authListener != null) {
auth.removeAuthStateListener(authListener);
}
}
}
MapFragment(存储标记部分):
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (FirebaseAuth.getInstance().getCurrentUser() == null) {
Intent intent = new Intent(getActivity(),LoginActivity.class);
startActivity(intent);
}
else{
MainActivity a ;
a = (MainActivity)getActivity();
a.userUID = userUID1;
Log.d("TAG", userUID1);
// userUID = (String) getActivity().getIntent().getExtras().get("uid");
}
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
mview = inflater.inflate(R.layout.fragment_map, container, false);
return mview;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mMapView = (MapView)mview.findViewById(R.id.mapView);
if(mMapView != null){
mMapView.onCreate(null);
mMapView.onResume();
mMapView.getMapAsync(this);
mFirebaseDatabase = FirebaseDatabase.getInstance();
mFirebaseRef = mFirebaseDatabase.getReference("Map/" + userUID1);
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.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
@Override
public boolean onMarkerClick(Marker marker) {
// Remove map markers from Firebase when tapped
FirebaseDatabase.getInstance().getReference();
// String user = ContactInfo.getAccount();
CustomInfoWindowAdapter adapter = new CustomInfoWindowAdapter(MapFragment.this);
googleMap.setInfoWindowAdapter(adapter);
marker.setTitle("的種子");
marker.setSnippet("點選聊天");
marker.showInfoWindow();
// Intent intent = new Intent(getActivity(),ChatActivity.class);
// startActivity(intent);
return true;
}
});
googleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
@Override
public void onMapClick(final LatLng latLng) {
// Taps create new markers in Firebase
// This works because jackson can figure out LatLng
mFirebaseRef.push().setValue(new FirebaseMarker(latLng));
}
});
mgoogleMap.setOnMarkerDragListener(new GoogleMap.OnMarkerDragListener() {
@Override
public void onMarkerDragStart(Marker marker) {
// not implemented
}
@Override
public void onMarkerDrag(Marker marker) {
// not implemented
}
@Override
public void onMarkerDragEnd(Marker marker) {
mFirebaseRef.child(marker.getTitle()).setValue(new FirebaseMarker(marker.getPosition()));
}
});
}
}
如果您需要更多信息,我会对其进行更新。
答案 0 :(得分:0)
您需要更改此行:
userUID = getIntent().getStringExtra("uid");
这一行:
String userUID = user.getUid();
Log.d("TAG", userUID);
希望它有所帮助。
答案 1 :(得分:0)
如果我不理解,MapFragment
是您MainActivity
的一部分。你的问题来自于:
authListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
auth = FirebaseAuth.getInstance();
FirebaseUser user = auth.getCurrentUser();
if (user != null) {
userUID = getIntent().getStringExtra("uid");
}
else{
startActivity(new Intent(MainActivity.this, LoginActivity.class));
finish();
}
}
};
我可以看到,userUID
为空,直到onAuthStateChanged
发生变化。为了解决这个问题,我建议将此行移至onCreate
MainActiviy
,因为uid
已在之前的活动中传递给Intent
。