简体   繁体   中英

Why my getUID always be null?

I made an app that can let user log in and set marker on the google map and the marker connect to a chatroom that belongs to the user who set it.

I use firebase mail authentication ,the problem is that i can't get the uid and it's null,i tried a lot of ways,but it still didn't work.

Actually I can sotre my account data in firebase in createActivity with uid and it work,but when I switch to other activity ,the uid became null,I ask this before and someone told me to use this code:

Intent intent = new Intent(CreateActivity.this, MainActivity.class);
                        intent.putExtra("uid", currentUid);
                        startActivity(intent);

But it doesn't work.

can someone please help me find where is the problem ,here is my relative code:

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(store the marker part):

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()));
        }
    });


}

}

If you need more information,I'll update it.

You need to change this line:

userUID = getIntent().getStringExtra("uid");

with this line:

String userUID = user.getUid();
Log.d("TAG", userUID);

Hope it helps.

If I donot miss understand, the MapFragment is a part of your MainActivity . Your problem comes from this:

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();
        }
    }
};

As I can see, your userUID is null until there's an onAuthStateChanged changed. To sovlve it, I suggest to move this line to the onCreate of MainActiviy as your uid is passed to Intent in previous activity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM