I cannot seem to log in into my main activity - java

I cannot log in to my application, and I found no error in the codes. It keeps showing, email is required every time I tried to log in. I connect this app with FireStore as well. So, I need help what did I did wrong here because it supposed to go to the main activity after my login page:
public class Login extends AppCompatActivity {
EditText mPassword,mEmail;
FirebaseAuth auth;
Button mlogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_user);
final TextView register = findViewById(R.id.register_txt);
mPassword = findViewById(R.id.password_et);
mEmail = findViewById(R.id.email_et);
mlogin = findViewById(R.id.login_bt);
auth = FirebaseAuth.getInstance();
String email = mEmail.getText().toString().trim();
String password = mPassword.getText().toString().trim();
mlogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (TextUtils.isEmpty(email)) {
mEmail.setError("Email is required.");
return;
}
if (TextUtils.isEmpty(password)) {
mPassword.setError("Password is required");
return;
}
if(password.length() < 6) {
mPassword.setError("6 or more character long");
return;
}
auth.signInWithEmailAndPassword(email,password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
Toast.makeText(Login.this,"Login",Toast.LENGTH_SHORT)
.show();
startActivity(new Intent(getApplicationContext(),MainActivity.class));
} else {
Toast.makeText(Login.this, "Error" + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
});
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(),Register.class));
}
});
}
}
This is my register, firebase auth, and firestore connected to get information on the users.
public class Register extends AppCompatActivity {
public static final String TAG = "TAG";
EditText mfullname, mPassword, mphoneNo, mEmail;
TextView register;
FirebaseAuth auth;
FirebaseFirestore fstore;
String userID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register_user);
final TextView login = findViewById(R.id.login_text);
register = findViewById(R.id.register_bt);
mEmail = findViewById(R.id.email_et);
mPassword = findViewById(R.id.password_et);
mfullname = findViewById(R.id.fullname_et);
mphoneNo = findViewById(R.id.phoneNum_et);
auth = FirebaseAuth.getInstance();
fstore = FirebaseFirestore.getInstance();
if(auth.getCurrentUser() != null)
{
startActivity(new Intent(getApplicationContext(),MainActivity.class));
finish();
}
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = mEmail.getText().toString().trim();
String password = mPassword.getText().toString().trim();
String fullName = mfullname.getText().toString();
String phoneNo = mphoneNo.getText().toString();
if (TextUtils.isEmpty(email)) {
mEmail.setError("Email is required.");
return;
}
if (TextUtils.isEmpty(password)) {
mPassword.setError("Password is required");
return;
}
if(password.length() <6){
mPassword.setError("6 or more character long");
return;
}
auth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Toast.makeText(Register.this,"User Created",Toast.LENGTH_SHORT).show();
userID = auth.getCurrentUser().getUid();
DocumentReference documentReference = fstore.collection("Users").document(userID);
Map<String,Object> user = new HashMap<>();
user.put("fName",fullName);
user.put("email",email);
user.put("phone",phoneNo);
documentReference.set(user).addOnSuccessListener(aVoid -> {
Log.d(TAG, "onSuccess: user profile is created for" + userID);}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG, "onFailure: " + e.toString());
}
});
startActivity(new Intent(getApplicationContext(),Login.class));
} else {
Toast.makeText(Register.this, "Error" + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
});
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(),Login.class));
}
});
}
}
MainActivity class:
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
ArrayList<HomeModel> homeModel;
MainAdapter mainAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navView = findViewById(R.id.nav_view);
navView.setOnNavigationItemSelectedListener(navListener);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new HomeFragment()).addToBackStack(null).commit();
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.navigation_home:
selectedFragment = new HomeFragment();
break;
case R.id.navigation_dashboard:
selectedFragment = new DashboardFragment();
break;
case R.id.navigation_notifications:
selectedFragment = new NotificationsFragment();
break;
case R.id.navigation_profile:
selectedFragment = new ProfileFragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
selectedFragment).addToBackStack(null).commit();
return true;
}
};
}

Related

Firebase signOut() method or AuthListener not working as intended

I have a Fragment with a signOut button in my android studio app that is supposed to log the user out of his account and then redirect him back to the login page. I've tried several things so far and looked at every thread I could find but nothing is working. There is no error, just no reaction at all.
First thing I've tried is this:
public class PreferenceFragment extends Fragment {
private PreferenceViewModel preferenceViewModel;
private FragmentPreferenceBinding binding;
private Button btnSignOut;
private FirebaseAuth auth;
private FirebaseAuth.AuthStateListener authListener;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
preferenceViewModel =
new ViewModelProvider(this).get(PreferenceViewModel.class);
auth = FirebaseAuth.getInstance();
View view = inflater.inflate(R.layout.fragment_preference, container, false);
btnSignOut = (Button) view.findViewById(R.id.sign_out);
binding = FragmentPreferenceBinding.inflate(inflater, container, false);
View root = binding.getRoot();
final TextView textView = binding.textPreference;
preferenceViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
textView.setText(s);
}
});
authListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = auth.getCurrentUser();
if (user == null) {
// user auth state is changed - user is null
// launch login activity
startActivity(new Intent(getActivity(), LoginActivity.class));
getActivity().finish();
}
}
};
btnSignOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
auth.signOut();
}
});
return root;
}
#Override
public void onDestroyView() {
super.onDestroyView();
binding = null;
}
#Override
public void onStart() {
super.onStart();
auth.addAuthStateListener(authListener);
}
#Override
public void onStop() {
super.onStop();
if (authListener != null) {
auth.removeAuthStateListener(authListener);
}
}
}
This is my LoginActivity:
public class LoginActivity extends AppCompatActivity {
private EditText inputEmail, inputPassword;
private FirebaseAuth auth;
private ProgressBar progressBar;
private Button btnSignup, btnLogin, btnReset;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Get Firebase auth instance
auth = FirebaseAuth.getInstance();
if (auth.getCurrentUser() != null) {
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
}
// set the view now
setContentView(R.layout.activity_login);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
btnSignup = (Button) findViewById(R.id.btn_signup);
btnLogin = (Button) findViewById(R.id.btn_login);
btnReset = (Button) findViewById(R.id.btn_reset_password);
//Get Firebase auth instance
auth = FirebaseAuth.getInstance();
btnSignup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, SignupActivity.class));
}
});
btnReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, ResetPasswordActivity.class));
}
});
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = inputEmail.getText().toString();
final String password = inputPassword.getText().toString();
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
return;
}
progressBar.setVisibility(View.VISIBLE);
//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.
progressBar.setVisibility(View.GONE);
if (!task.isSuccessful()) {
// there was an error
if (password.length() < 6) {
inputPassword.setError(getString(R.string.minimum_password));
} else {
Toast.makeText(LoginActivity.this, getString(R.string.auth_failed), Toast.LENGTH_LONG).show();
}
} else {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
}
});
}
});
}
}
First I thought it might be the signOut() that isn't working as intended or logging me back in automatically. But if I put the signOut() into the onStop() method of the MainActivity it is working, obviously only when I close the app:
#Override
public void onStop() {
super.onStop();
FirebaseAuth.getInstance().signOut();
}
then I thought the program might not be calling the same FirebasAuth instance so I've tried calling the FirebaseAuth instance from the MainActivity to the same effect:
(MainActivity)getActivity()).auth.signOut();
I've tried several other things like putting the authListener in the MainActivity or removing the code calling the FirebasAuth instance at the start of the LoginActivity, always to the same effect. Maybe it has to do with my startActivity but I'm not sure how to do it differently. Thanks in advance for any help.

Android ImageView null object when trying to set Image

I am having difficulty setting an ImageView with a string download url that is in a user object that came from the firebase storage DB. The method setImage() is saying the Imageview is a null object and this is true as I have tried to debug it and it comes up as null. How can I resolve this. I think it has something to do with the anonymous inner class.
public class DashBoard extends AppCompatActivity {
private FirebaseAuth mAuth;
private ArrayList<String> motivatingMessages;
private Button gymLocations, profile,health;
public ImageView profileImageView;
private TextView welcome;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
showProfilePicture();
profileImageView = findViewById(R.id.personalProfile);
mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
setContentView(R.layout.activity_dash_board);
//getSupportActionBar().setTitle("Welcome To Bodify");
profile = findViewById(R.id.buttonProfile);
gymLocations = findViewById(R.id.gymFinderButton);
health = findViewById(R.id.healthButton);
welcome = findViewById(R.id.welcomeUser);
final String userID = mAuth.getUid();
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("User").child(userID);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
User user = snapshot.getValue(User.class);
if (user != null) {
welcome.setText("User Logged in: ");
welcome.append(user.getUserName());
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(DashBoard.this, "Error Occurred: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
gymLocations.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), GymsNearMe.class));
}
});
profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), PersonalProfile.class));
}
});
health.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(DashBoard.this,Health.class));
}
});
}
public void showProfilePicture() {
mAuth = FirebaseAuth.getInstance();
final String userID = mAuth.getUid();
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("User").child(userID);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
User user = snapshot.getValue(User.class);
String image = user.getmImageUrl();
setImage(image);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(DashBoard.this, "Error Occurred: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
public void setImage(String image) {
Picasso.get().load(image).into(profileImageView);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.logOut) {
mAuth.signOut();
startActivity(new Intent(getApplicationContext(), LogIn.class));
}
return true;
}
}
enter code here
It looks like you are trying to find the view before inflating the layout:
profileImageView = findViewById(R.id.personalProfile);
move that line after the inflation so after the line:
setContentView(R.layout.activity_dash_board);
In other words, the order of the lines should be:
setContentView(R.layout.activity_dash_board);
mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
profileImageView = findViewById(R.id.personalProfile);
showProfilePicture();
and you do not need to set the mAuth again in the showProfilePicture
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dash_board);
profileImageView = findViewById(R.id.personalProfile);
profile = findViewById(R.id.buttonProfile);
gymLocations = findViewById(R.id.gymFinderButton);
health = findViewById(R.id.healthButton);
welcome = findViewById(R.id.welcomeUser);
showProfilePicture();
mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
try with this order

Loading profile image and username in the navigation bar from firebase

image of database structure
code for database structure
I am trying to retrieve the profile image and username that is saved by the user during the registration process in the navigation header. Here is something that I did . At first I tried to get string current user but it showed me null pointer exception then I tried with if statement and changed the child from current user id to Users , it only solved the null pointer but this didn't retrive the data from firebase.
MainActivity.java
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;
import de.hdodenhof.circleimageview.CircleImageView;
public class MainActivity extends AppCompatActivity {
private NavigationView navigationView;
private DrawerLayout drawerLayout;
private RecyclerView postlist;
private Toolbar mToolbar;
private ActionBarDrawerToggle actionBarDrawerToggle;
private FirebaseAuth mAuth;
private FirebaseUser FirebaseUser;
private DatabaseReference UsersRef;
private CircleImageView NavProfileImage;
private TextView NavProfileUserName;
String currentUserID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirebaseUser mFirebaseUser = mAuth.getCurrentUser();
if (mFirebaseUser != null) {
currentUserID = mFirebaseUser.getUid();
}
mAuth = FirebaseAuth.getInstance();
mToolbar =(Toolbar) findViewById(R.id.main_page_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("Home");
drawerLayout = (DrawerLayout) findViewById(R.id.drawable_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(MainActivity.this,drawerLayout,R.string.drawer_open, R.string.drawer_close);
navigationView = (NavigationView)findViewById(R.id.navigation_view);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
View navView = navigationView.inflateHeaderView(R.layout.nav_header);
NavProfileImage = (CircleImageView)navView.findViewById(R.id.nav_profile_image);
NavProfileUserName = (TextView) navView.findViewById(R.id.nav_user_full_name);
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
UsersRef.child(currentUserID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
if(dataSnapshot.exists())
{ if (dataSnapshot.hasChild("fullname")){
String fullname = dataSnapshot.child("fullname").getValue().toString();
NavProfileUserName.setText(fullname);
}if (dataSnapshot.hasChild("profileimages")) {
String image = dataSnapshot.child("profileimages").getValue().toString();
Picasso.with(MainActivity.this).load(image).placeholder(R.drawable.profile).into(NavProfileImage);
}else {
Toast.makeText(MainActivity.this, "Profile name do not exists...", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item)
{ UserMenuSelector(item);
return false;
}
});
}
#Override
protected void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser == null)
{
sendUserToLoginActivity();
}else{
CheckUserExistance();
}
}
private void CheckUserExistance()
{
final String current_user_id = mAuth.getCurrentUser().getUid();
UsersRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!dataSnapshot.hasChild(current_user_id)){
sendUserToSetupActivity();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void sendUserToSetupActivity() {
Intent setupIntent = new Intent(MainActivity.this, SetupActivity.class);
setupIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(setupIntent);
finish();
}
private void sendUserToLoginActivity()
{
Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(loginIntent);
finish();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (actionBarDrawerToggle.onOptionsItemSelected(item))
{
return true;
}
return super.onOptionsItemSelected(item);
}
private void UserMenuSelector(MenuItem item)
{
switch (item.getItemId())
{
case R.id.nav_home:
Toast.makeText(this,"Home",Toast.LENGTH_SHORT).show();
break;
case R.id.nav_post:
break;
case R.id.nav_Profile:
Toast.makeText(this,"profile",Toast.LENGTH_SHORT).show();
break;
case R.id.nav_find_friends:
Toast.makeText(this,"frns",Toast.LENGTH_SHORT).show();
break;
case R.id.nav_logout:
mAuth.signOut();
sendUserToLoginActivity();
break;
}
}
}
I use the glide for loading images from firebase. It would be something like this:
import com.bumptech.glide.Glide;
UserModel userModel = new UserModel;
Glide.with(YourActivity.this)
.load(userModel.getUser_image())
.into(user_image);
For more info please look at the github repository.
After seeing your database structure I believe that the child inside Users node is the UID of current firebase user and in the Users node if you are trying to fetch user details of current user then your query should be like this
if (mFirebaseUser != null) {
currentUserID = mFirebaseUser.getUid();
}
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
UsersRef.child(currentUserID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
if(dataSnapshot.exists())
{ if (dataSnapshot.hasChild("fullname")){
String fullname = dataSnapshot.child("fullname").getValue().toString();
NavProfileUserName.setText(fullname);
}if (dataSnapshot.hasChild("profileimages")) {
String image = dataSnapshot.child("profileimages").getValue().toString();
Picasso.with(MainActivity.this).load(image).placeholder(R.drawable.profile).into(NavProfileImage);
}else {
Toast.makeText(MainActivity.this, "Profile name do not exists...", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
At the time of register the user you should save the user's info like this
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
userModel.setUserid(user.getUid());
userModel.setMobile("120xxxxxxxx");
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName("Some Name")
.setPhotoUri("Phot url of the user")
.build();
user.updateProfile(profileUpdates);
Then when you want to retrive the image from the user's info with the other info's too....
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
headerResult = new AccountHeaderBuilder()
.withActivity(MainActivity.this)
.withHeaderBackground(R.drawable.gradient_home_background)
.addProfiles(
new ProfileDrawerItem().withName(user.getDisplayName()).withEmail(user.getPhoneNumber()).withIcon(user.getPhotoUrl())
)
.withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() {
#Override
public boolean onProfileChanged(View view, IProfile profile, boolean currentProfile) {
return false;
}
})
.build();
} else {
headerResult = new AccountHeaderBuilder()
.withActivity(MainActivity.this)
.withHeaderBackground(R.drawable.gradient_home_background)
.withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() {
#Override
public boolean onProfileChanged(View view, IProfile profile, boolean currentProfile) {
return false;
}
})
.build();
}
I see, you did use mAuth before initializing it! So it is returning null.
FirebaseUser mFirebaseUser = **mAuth**.getCurrentUser();
if (mFirebaseUser != null) {
currentUserID = mFirebaseUser.getUid();
}
**mAuth = FirebaseAuth.getInstance();**
Move mAuth = FirebaseAuth.getInstance(); line just before FirebaseUser mFirebaseUser = mAuth.getCurrentUser(); line

error: cannot find symbol method getDownloadUrl()

I'm still a beginner in programming. I'm developing an application for a college job. However, I came across this mistake. I do not know how I can fix it. This problem:
error: cannot find symbol method getDownloadUrl()
How can I solve this error?
Here is my code:
package com.valcirjr98.logindj;
$public class ProfileActivity extends AppCompatActivity {
private static final int CHOOSE_IMAGE = 101;
TextView textView;
ImageView imageView;
EditText editText;
Uri uriProfileImage;
ProgressBar progressBar;
String profileImageUrl;
FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
mAuth = FirebaseAuth.getInstance();
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
editText = (EditText) findViewById(R.id.editTextDisplayName);
imageView = (ImageView) findViewById(R.id.imageView);
progressBar = (ProgressBar) findViewById(R.id.progressbar);
textView = (TextView) findViewById(R.id.textViewVerified);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showImageChooser();
}
});
loadUserInformation();
findViewById(R.id.buttonSave).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
saveUserInformation();
}
});
}
#Override
protected void onStart() {
super.onStart();
if (mAuth.getCurrentUser() == null) {
finish();
startActivity(new Intent(this, MainActivity.class));
}
}
private void loadUserInformation() {
final FirebaseUser user = mAuth.getCurrentUser();
if (user != null) {
if (user.getPhotoUrl() != null) {
Glide.with(this)
.load(user.getPhotoUrl().toString())
.into(imageView);
}
if (user.getDisplayName() != null) {
editText.setText(user.getDisplayName());
}
if (user.isEmailVerified()) {
textView.setText("Email Verified");
} else {
textView.setText("Email Not Verified (Click to Verify)");
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
user.sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(ProfileActivity.this, "Verification Email Sent", Toast.LENGTH_SHORT).show();
}
});
}
});
}
}
}
private void saveUserInformation() {
String displayName = editText.getText().toString();
if (displayName.isEmpty()) {
editText.setError("Name required");
editText.requestFocus();
return;
}
FirebaseUser user = mAuth.getCurrentUser();
if (user != null && profileImageUrl != null) {
UserProfileChangeRequest profile = new UserProfileChangeRequest.Builder()
.setDisplayName(displayName)
.setPhotoUri(Uri.parse(profileImageUrl))
.build();
user.updateProfile(profile)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(ProfileActivity.this, "Profile Updated", Toast.LENGTH_SHORT).show();
}
}
});
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CHOOSE_IMAGE && resultCode == RESULT_OK && data != null && data.getData() != null) {
uriProfileImage = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uriProfileImage);
imageView.setImageBitmap(bitmap);
uploadImageToFirebaseStorage();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void uploadImageToFirebaseStorage() {
StorageReference profileImageRef =
FirebaseStorage.getInstance().getReference("profilepics/" + System.currentTimeMillis() + ".jpg");
if (uriProfileImage != null) {
progressBar.setVisibility(View.VISIBLE);
profileImageRef.putFile(uriProfileImage)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressBar.setVisibility(View.GONE);
profileImageUrl = taskSnapshot.getDownloadUrl().toString();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressBar.setVisibility(View.GONE);
Toast.makeText(ProfileActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menuLogout:
FirebaseAuth.getInstance().signOut();
finish();
startActivity(new Intent(this, MainActivity.class));
break;
}
return true;
}
private void showImageChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Profile Image"), CHOOSE_IMAGE);
}
}
profileImageRef.putFile(uriProfileImage).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
profileImageUrl= taskSnapshot.getDownloadUrl().toString();
}
});
*
This method worked for me.
profileImageRef.putFile(uriProfileImage).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful() && task != null) {
profileImageUrl = task.getResult().getDownloadUrl().toString();
}
}
});
Try this!

I Can't Finish my Registration. I'm always getting "Registration Error"

Here is the program
MainActivity.java
I am having the problem where it says "Registration Error".
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button buttonSignup;
private EditText editTextEmail;
private EditText editTextPassword;
private TextView textViewSignin;
private ProgressDialog progressDialog;
private FirebaseAuth firebaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firebaseAuth = FirebaseAuth.getInstance();
if(firebaseAuth.getCurrentUser() != null) {
finish();
startActivity(new Intent(getApplicationContext(), ProfileActivity.class));
}
progressDialog = new ProgressDialog(this);
buttonSignup = (Button) findViewById(R.id.buttonSignup);
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
textViewSignin =(TextView) findViewById(R.id.textViewSignin);
buttonSignup.setOnClickListener(this);
textViewSignin.setOnClickListener(this);
}
private void registerUser() {
String email = editTextEmail.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
if(TextUtils.isEmpty(email)){
Toast.makeText(this, "Please enter email", Toast.LENGTH_SHORT).show();
return;
}
if(TextUtils.isEmpty(password)){
Toast.makeText(this, "Please enter password", Toast.LENGTH_SHORT).show();
return;
}
progressDialog.setMessage("Registering User");
progressDialog.show();
firebaseAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
//checking if success
if(task.isSuccessful()){
//display some message here
Toast.makeText(MainActivity.this,"Successfully registered",Toast.LENGTH_LONG).show();
}else{
//display some message here
Toast.makeText(MainActivity.this,"Registration Error",Toast.LENGTH_LONG).show();
}
progressDialog.dismiss();
}
});
}
#Override
public void onClick(View v) {
if (v == buttonSignup) {
registerUser();
}
if (v == textViewSignin) {
startActivity(new Intent(this, LoginActivity.class));
}
}
}
I am using firebase-auth:10.2.0
And none of the Toast messages appear after I hit the "Register User" button.
Try it:
In onCreate() method:
firebaseAuth = FirebaseAuth.getInstance(); if(firebaseAuth.getCurrentUser() != null) {
startActivity(new Intent(getApplicationContext(), ProfileActivity.class));
finish();
}
2. When click Registration Button:
createUserWithEmailAndPassword(email, password) .addOnCompleteListener(RegisterActivity, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
hideProgressDialog();
if (!task.isSuccessful()) {
Toast.makeText(RegisterActivity.this, "Registration Error", Toast.LENGTH_SHORT).show();
} else {
Intent intent = new Intent(RegisterActivity.this, PrifileActivity.class);
startActivity(intent);
finish();
}
}
});

Categories