I'm so new in coding and now I'm trying to write a socialnetwork app but i faced an error and I couldn't find any answer for that.
I could save my profile picture to firebase storage successfully but it I have to connect it to database so that I can use it later.
here is my code:
public class SetUpActivity extends AppCompatActivity
{
private EditText UserName, FullName , CountryName;
private Button SaveInfoButton;
private CircleImageView UserProfileImage;
private ProgressDialog loadingBar;
private FirebaseAuth mAuth;
private DatabaseReference UserRef;
private StorageReference UserProfileImageRef;
String currentUserID;
final static int Gallery_Pick = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_set_up);
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
UserRef = FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserID);
UserProfileImageRef = FirebaseStorage.getInstance().getReference().child("profile Image");
//storing profile image
UserName = (EditText) findViewById(R.id.setup_user_name);
FullName = (EditText) findViewById(R.id.setup_user_full_name);
CountryName = (EditText) findViewById(R.id.setup_user_country);
SaveInfoButton = (Button) findViewById(R.id.setup_information_button);
UserProfileImage = (CircleImageView) findViewById(R.id.set_up_profile_image);
loadingBar = new ProgressDialog( this);
SaveInfoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
SaveAccountSetupInformation();
}
});
UserProfileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent,Gallery_Pick);
}
});
UserRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot)
{
if(snapshot.exists()) {
if (snapshot.hasChild("profileimage"))
{
String image = snapshot.child("profileimage").getValue().toString();
Picasso.get().load(image).placeholder(R.drawable.profile).into(UserProfileImage);
}
else
{
Toast.makeText(SetUpActivity.this, "Plese Select Profile Image First...", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// some conditions for the picture
if(requestCode==Gallery_Pick && resultCode==RESULT_OK && data!=null)
{
Uri ImageUri = data.getData();
// crop the image
CropImage.activity(ImageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1, 1)
.start(this);
}
// Get the cropped image
if(requestCode==CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE)
{ // store the cropped image into result
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if(resultCode == RESULT_OK)
{
loadingBar.setTitle("Profile Image");
loadingBar.setMessage("Please wait, while we updating your profile image...");
loadingBar.show();
loadingBar.setCanceledOnTouchOutside(true);
Uri resultUri = result.getUri();
final StorageReference filePath = UserProfileImageRef.child(currentUserID + ".jpg");
//StorageReference filePath = UserProfileImageRef.child(currentUserID + ".jpg");
filePath.putFile(resultUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
final String downloadUrl = uri.toString();
UserRef.child("profileimage").setValue(downloadUrl).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful())
{
Toast.makeText(SetUpActivity.this, "Image Stored", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
else {
String message = task.getException().getMessage();
Toast.makeText(SetUpActivity.this, "Error:" + message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
});
}
});
}
else
{
Toast.makeText(this, "Error Occured: Image can not be cropped. Try Again.", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
}
private void SaveAccountSetupInformation()
{
String username = UserName.getText().toString();
String userfullname = FullName.getText().toString();
String country = CountryName.getText().toString();
if(TextUtils.isEmpty(username))
{
Toast.makeText(this,"Please Write Your UserName", Toast.LENGTH_SHORT).show();
}
else if(TextUtils.isEmpty(userfullname))
{
Toast.makeText(this,"Please Write Your Full Name", Toast.LENGTH_SHORT).show();
}
else if(TextUtils.isEmpty(country))
{
Toast.makeText(this,"Please Write Your Country", Toast.LENGTH_SHORT).show();
}
else
{
loadingBar.setTitle("Saving Information...");
loadingBar.setMessage("Please wait for a while...");
loadingBar.show();
loadingBar.setCanceledOnTouchOutside(true);
HashMap userMap = new HashMap();
userMap.put("username", username);
userMap.put("fullname", userfullname);
userMap.put("country", country);
userMap.put("status","Hey there, I am Using Pingoo");
userMap.put("gender", "none");
userMap.put("dob","None");
userMap.put("relationshipstatus","none");
UserRef.setValue(userMap).addOnCompleteListener(new OnCompleteListener()
{
#Override
public void onComplete(#NonNull Task task)
{
if(task.isSuccessful())
{
SendUserToMainActivity();
Toast.makeText(SetUpActivity.this,"Your Account Has Been Created Successfully :) Enjoy!", Toast.LENGTH_LONG).show();
SendUserToMainActivity();
loadingBar.dismiss();
}
else
{
String message = task.getException().getMessage();
Toast.makeText(SetUpActivity.this, "Oops!Something Went Wrong:(",Toast.LENGTH_LONG).show();
loadingBar.dismiss();
}
}
});
}
}
private void SendUserToMainActivity() {
Intent mainIntent = new Intent(SetUpActivity.this,MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}
}
I would appreciate if anyone could give me solution cause it's my school project and I really need to do it.
I've tried to find answer but i couldn't find it anywhere :(((
thank you in advance.
Related
I'm trying to make a feature where user has to upload their profile picture while signing up. But my app keeps stopping and is neither uploading details nor uploading profile picture. But if I remove code for uploading pic, it works fine. So there's something wrong with picture uploading. Please help me fix it-
public class SelectRegistrationActivity extends AppCompatActivity {
private TextView back;
private TextView fullName,email,phone,password,regButton,gender,age;
String flag="False";
private CircleImageView dp;
//private Uri result;
private Uri filePath;
// request code
private final int PICK_IMAGE_REQUEST = 22;
FirebaseAuth mAuth;
DatabaseReference userDatabaseRef;
ProgressDialog loader;
FirebaseDatabase database= FirebaseDatabase.getInstance();
String currentUserId;
FirebaseStorage storage;
StorageReference storageReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_registration);
back = findViewById(R.id.back);//inside bracket is id given to sign in button in activity_select_registration.xml
//the other back are just variable names
fullName = findViewById(R.id.fullName);
email = findViewById(R.id.email);
phone = findViewById(R.id.phone);
password = findViewById(R.id.password);
regButton = findViewById(R.id.regButton);
gender = findViewById(R.id.gender);
age = findViewById(R.id.age);
dp = findViewById(R.id.dp);
loader = new ProgressDialog(this);
mAuth = FirebaseAuth.getInstance();
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
FirebaseUser user = mAuth.getInstance().getCurrentUser();
userDatabaseRef = database.getReference().child("All Users");
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(SelectRegistrationActivity.this, AccountSelectionActivity.class);
startActivity(intent);
}
});
dp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
flag="True";
SelectImage();
}
});
regButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Email,Password etc are variables
final String Email = email.getText().toString().trim();
final String Password = password.getText().toString().trim();
final String FullName = fullName.getText().toString().trim();
final String Phone = phone.getText().toString().trim();
final String Gender = gender.getText().toString().trim();
final String Age = age.getText().toString().trim();
if (TextUtils.isEmpty(Email)) {
email.setError("Email is required!");
return;
}
if (TextUtils.isEmpty(Password)) {
password.setError("Password is required!");
return;
}
if (TextUtils.isEmpty(FullName)) {
fullName.setError("Name is required!");
return;
}
if (TextUtils.isEmpty(Phone)) {
phone.setError("Phone number is required!");
return;
}
if (TextUtils.isEmpty(Gender)) {
gender.setError("Gender is required!");
return;
}
if (TextUtils.isEmpty(Age)) {
age.setError("Age is required!");
return;
}
if (flag.equals("False")) {
Toast.makeText(SelectRegistrationActivity.this, "Upload profile picture!", Toast.LENGTH_SHORT).show();
return;
}
else {
loader.setMessage("Registration in process....");
loader.setCanceledOnTouchOutside(false);
loader.show();
mAuth.createUserWithEmailAndPassword(Email, Password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
String error = task.getException().toString();
Toast.makeText(SelectRegistrationActivity.this,
"Error occurred:" + error, Toast.LENGTH_SHORT).show();
} else {
String currentUserId = mAuth.getCurrentUser().getUid();
userDatabaseRef = database.getReference().child("All Users").child(currentUserId);
//HashMap userInfo = new HashMap();
HashMap userInfo = new HashMap();
userInfo.put("Name", FullName);
userInfo.put("Email", Email);
userInfo.put("Age", Age);
userInfo.put("Gender", Gender);
userInfo.put("Phone", Phone);
userInfo.put("Password", Password);
userInfo.put("Type", "Patient");
//userDatabaseRef.setValue(userInfo);
uploadImage();
userDatabaseRef.updateChildren(userInfo).addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()) {
Toast.makeText(SelectRegistrationActivity.this, "Details set Successful", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(SelectRegistrationActivity.this, task.getException().toString(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
finish();//takes user to screen 1
loader.dismiss();
}
}
});
}
// Select Image method
private void SelectImage()
{
// Defining Implicit Intent to mobile gallery
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Image from here..."), PICK_IMAGE_REQUEST);
}
// Override onActivityResult method
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
// Get the Uri of data
filePath = data.getData();
try {
// Setting image on image view using Bitmap
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
dp.setImageBitmap(bitmap);
}
catch (IOException e) {
// Log the exception
e.printStackTrace();
}
}
}
// UploadImage method
private void uploadImage()
{
if (filePath != null) {
// Defining the child of storageReference
StorageReference ref = storageReference.child("Patient/"+currentUserId);
// adding listeners on upload
// or failure of image
ref.putFile(filePath).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(SelectRegistrationActivity.this, "Image Uploaded!!", Toast.LENGTH_SHORT).show();
}
});
}
}
}
This is the logcat-
2022-08-24 18:07:09.903 12588-12588/? E/.example.hisss: Unknown bits set in runtime_flags: 0x800000
2022-08-24 18:07:11.013 12588-12651/com.example.hissss E/LB: fail to open file: No such file or directory
Use New keyword before storageReference.child and run code.
I am trying to display my image that stores successfully in Firebase. But whenever I try and display the image it returns a blank image and not the image stored. I think that the image name is wrong when being stored in Firebase. I also did research to try use Glide in my code but don't know how to implement it. I am using the latest dependencies for Firebase.
Code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
RootRef = FirebaseDatabase.getInstance().getReference();
UserProfileImageRef = FirebaseStorage.getInstance().getReference().child("Profile Images");
InitializeFields();
userName.setVisibility(View.INVISIBLE);
UpdateAccountSettings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
UpdateSettings();
}
});
RetrieveUserInfo();
userProfileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, GalleryPick);
}
});
}
private void UpdateSettings() {
String setUserName = userName.getText().toString();
String setUserStatus = userStatus.getText().toString();
if (TextUtils.isEmpty(setUserName)) {
Toast.makeText(this, "Please write your user name first....", Toast.LENGTH_SHORT).show();
}
if (TextUtils.isEmpty(setUserStatus)) {
Toast.makeText(this, "Please write your status....", Toast.LENGTH_SHORT).show();
}
else {
HashMap<String, String> profileMap = new HashMap<>();
profileMap.put("uid", currentUserID);
profileMap.put("name", setUserName);
profileMap.put("status", setUserStatus);
profileMap.put("image", photoUrl);
RootRef.child("Users").child(currentUserID).setValue(profileMap)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
SendUserToMainActivity();
Toast.makeText(SettingsActivity.this, "Profile Updated successfully", Toast.LENGTH_SHORT).show();
} else {
String message = task.getException().toString();
Toast.makeText(SettingsActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
}
}
});
}
}
private void RetrieveUserInfo() {
RootRef.child("Users").child(currentUserID)
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if ((dataSnapshot.exists()) && (dataSnapshot.hasChild("name") && (dataSnapshot.hasChild("image")))) {
String retrieveUserName = dataSnapshot.child("name").getValue().toString();
String retrieveUserStatus = dataSnapshot.child("status").getValue().toString();
String retrieveProfileImage = dataSnapshot.child("image").getValue().toString();
photoUrl = retrieveProfileImage;
userName.setText(retrieveUserName);
userStatus.setText(retrieveUserStatus);
//Picasso.get().load(retrieveProfileImage).into(userProfileImage);
Picasso.get().load(retrieveProfileImage).resize(100,100).centerCrop().into(userProfileImage);
//Glide.with(SettingsActivity.this).load(retrieveProfileImage).into(userProfileImage);
}
else if ((dataSnapshot.exists()) && (dataSnapshot.hasChild("name"))) {
String retrieveUserName = dataSnapshot.child("name").getValue().toString();
String retrieveUserStatus = dataSnapshot.child("status").getValue().toString();
userName.setText(retrieveUserName);
userStatus.setText(retrieveUserStatus);
}
else {
userName.setVisibility(View.VISIBLE);
Toast.makeText(SettingsActivity.this, "Please set & update your profile information...", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void InitializeFields() {
UpdateAccountSettings = (Button) findViewById(R.id.update_settings_button);
userName = (EditText) findViewById(R.id.set_user_name);
userStatus = (EditText) findViewById(R.id.set_profile_status);
userProfileImage = (CircleImageView) findViewById(R.id.set_profile_image);
loadingBar = new ProgressDialog(this);
}
private void SendUserToMainActivity() {
Intent mainIntent = new Intent(SettingsActivity.this, MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GalleryPick && resultCode == RESULT_OK && data != null) {
Uri ImageUri = data.getData();
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1,1)
.start(SettingsActivity.this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
loadingBar.setTitle("Set Profile Image");
loadingBar.setMessage("Please wait, your profile image is updating...");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
Uri resultUri = result.getUri();
StorageReference filePath = UserProfileImageRef.child(currentUserID + ".jpg");
filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
Toast.makeText(SettingsActivity.this, "Profile Image Uploaded Successfully", Toast.LENGTH_SHORT).show();
final String downloadedUrl = task.getResult().getStorage().getDownloadUrl().toString();
RootRef.child("Users").child(currentUserID).child("image")
.setValue(downloadedUrl)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(SettingsActivity.this, "Image saved in Database Successfully...", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
//Glide.with(SettingsActivity.this).load(downloadedUrl).into(userProfileImage);
}
else {
String message = task.getException().toString();
Toast.makeText(SettingsActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
else {
String message = task.getException().toString();
Toast.makeText(SettingsActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
}
}
}
Realtime Database before
Realtime Database before - Watch User Warren
Realtime Database after
Realtime Database after - Watch User Warren
Storage before
Storage before adding image
Storage after
Storage after image added
I wrote a code that lets people sign up to my up, but when I press the button the new user isn't created in the database (it stays null) what can i do?
here is the SignUpActivity.java:
public class SignUpActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
private EditText userEmail, userPassword1, userPassword2, userCode, userName, userDescription;
private ImageView image;
private ProgressDialog pDialog;
private boolean imagePressed = false;
private Uri filePath;
private FirebaseStorage storage;
private StorageReference storageReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
userCode = findViewById(R.id.userCode);
userDescription = findViewById(R.id.userDescription);
userEmail = findViewById(R.id.userEmail);
userName = findViewById(R.id.userName);
userPassword1 = findViewById(R.id.userPassword1);
userPassword2 = findViewById(R.id.userPassword2);
image = findViewById(R.id.userImageAdd);
mAuth = FirebaseAuth.getInstance();
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
imagePressed = true;
chooseImage();
}
});
}
private void chooseImage() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), Finals.PICK_IMAGE_REQUEST);
}
public void back(View view) {
finish();
}
public void submit(View view) {
pDialog = new ProgressDialog(this);
if (TextUtils.isEmpty(userEmail.getText().toString())) {
Toast.makeText(SignUpActivity.this, "Please enter email.", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(userPassword1.getText().toString())) {
Toast.makeText(SignUpActivity.this, "Please enter password.", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(userPassword2.getText().toString())) {
Toast.makeText(SignUpActivity.this, "Please repeat password.", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(userName.getText().toString())) {
Toast.makeText(SignUpActivity.this, "Please enter user name", Toast.LENGTH_SHORT).show();
} else if (!userPassword1.getText().toString().equals(userPassword2.getText().toString())) {
pDialog.dismiss();
Toast.makeText(SignUpActivity.this, "The passwords don't match.", Toast.LENGTH_SHORT).show();
} else {
pDialog.setMessage("Creating account...");
pDialog.show();
pDialog.setCanceledOnTouchOutside(false);
if (imagePressed && filePath != null) {
final StorageReference ref = storageReference.child("users/" + UUID.randomUUID().toString());
ref.putFile(filePath).continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()) {
throw task.getException();
}
return ref.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downUri = task.getResult();
boolean isTrainer = trainer();
register(userEmail.getText().toString(), userPassword1.getText().toString(), userName.getText().toString(), userDescription.getText().toString(),
downUri.toString(), isTrainer);
}
}
});
} else {
boolean isTrainer = trainer();
register(userEmail.getText().toString(), userPassword1.getText().toString(), userName.getText().toString(), userDescription.getText().toString(),
Finals.DEFAULT_USER_IMAGE_URL, isTrainer);
finish();
}
}
}
private boolean trainer() {
boolean trainer = false;
if (!TextUtils.isEmpty(userCode.getText())) {
if (userCode.getText().toString().equals(Finals.T_CODE))
trainer = true;
else if (!userCode.getText().toString().equals(Finals.T_CODE)) {
pDialog.dismiss();
Toast.makeText(this, "Not a real trainer code!", Toast.LENGTH_SHORT).show();
}
}
return trainer;
}
private void register(final String regEmail, final String regPassword,
final String regName, final String regDesc, final String url, final boolean trainer) {
mAuth.createUserWithEmailAndPassword(regEmail, regPassword).addOnCompleteListener(SignUpActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirebaseUser firebaseUser = mAuth.getCurrentUser();
String userId = firebaseUser.getUid();
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("id", mAuth.getCurrentUser().getUid());
hashMap.put("name", regName);
hashMap.put("description", regDesc);
hashMap.put("isTrainer", trainer);
hashMap.put("imageUrl", url);
FirebaseDatabase.getInstance().getReference().child("users").child(userId).setValue(hashMap)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
pDialog.dismiss();
Toast.makeText(SignUpActivity.this, "Created user", Toast.LENGTH_SHORT).show();
startActivity(new Intent(SignUpActivity.this, MainActivity.class));
} else {
pDialog.dismiss();
Toast.makeText(SignUpActivity.this, "Something went wrong", Toast.LENGTH_SHORT).show();
}
}
});
} else {
pDialog.dismiss();
Toast.makeText(SignUpActivity.this, "Creation failed :" + task.getException(), Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Finals.PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& data != null && data.getData() != null) {
filePath = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
image.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
this used to work on my previous phone but now it doesn't work on the new phone.
what could cause this bug?
Also the progress dialog wont show either.
when I try to access the code (say in this line - DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("users").child(id);) it returns null.
I don't get the "Something went wrong" either, it just goes to the LoginActivity (not the main Activity for whatever reason) who called it , and then I can login using the new user i created but can't access the data(it's null).
These are the database rules:
{
"rules": {
".read": true,
".write": true
}
}
Somehow, rewriting the code differently fixed the bug
new code -
private Context mContext;
private String email, username, password1, password2, trainerCode, description, imageUrl = Finals.DEFAULT_USER_IMAGE_URL;
private EditText mEmail, mPassword1, mPassword2, mUsername, mTrainerCode, mDescription;
private Button btnSubmit, btnBack;
private ImageView imageView;
private ProgressDialog pDialog;
private String userID;
private boolean isTrainer, imagePressed = false;
private Uri filePath;
//firebase
private FirebaseAuth mAuth;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference myRef;
private FirebaseStorage storage;
private StorageReference storageReference;
private View.OnClickListener imageClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
imagePressed = true;
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), Finals.PICK_IMAGE_REQUEST);
}
};
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
mContext = SignUpActivity.this;
pDialog = new ProgressDialog(this);
mEmail = findViewById(R.id.userEmail);
mUsername = findViewById(R.id.userName);
btnSubmit = findViewById(R.id.btn_submit);
mPassword1 = findViewById(R.id.userPassword1);
mPassword2 = findViewById(R.id.userPassword2);
mTrainerCode = findViewById(R.id.userCode);
mDescription = findViewById(R.id.userDescription);
imageView = findViewById(R.id.userImageAdd);
btnBack = findViewById(R.id.backBtn);
btnSubmit.setOnClickListener(btnSubmitListener);
imageView.setOnClickListener(imageClickListener);
btnBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
myRef = mFirebaseDatabase.getReference();
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
}
private View.OnClickListener btnSubmitListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
email = mEmail.getText().toString();
username = mUsername.getText().toString();
password1 = mPassword1.getText().toString();
password2 = mPassword2.getText().toString();
trainerCode = mTrainerCode.getText().toString();
description = mDescription.getText().toString();
isTrainer = false;
if (checkInputs(email, username, password1, password2, trainerCode)) {
pDialog.setMessage("Creating User...");
pDialog.show();
if (imagePressed && filePath != null)
uploadImage();
else
registerNewUser();
}
}
};
private void uploadImage() {
final StorageReference ref = storageReference.child("users/" + UUID.randomUUID().toString());
ref.putFile(filePath).continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()){
throw task.getException();
}
return ref.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
Uri downUri = task.getResult();
imageUrl = downUri.toString();
registerNewUser();
}
});
}
public void registerNewUser() {
mAuth.createUserWithEmailAndPassword(email, password1)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
Toast.makeText(SignUpActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
} else {
userID = mAuth.getCurrentUser().getUid();
addNewUser();
}
}
});
}
private boolean checkInputs(String email, String name, String password1, String password2, String trainerCode) {
if (email.equals("")) {
Toast.makeText(mContext, "Please enter email", Toast.LENGTH_SHORT).show();
return false;
}
if (name.equals("")) {
Toast.makeText(mContext, "Please enter name", Toast.LENGTH_SHORT).show();
return false;
}
if (password1.equals("")) {
Toast.makeText(mContext, "Please enter password", Toast.LENGTH_SHORT).show();
return false;
}
if (password2.equals("")) {
Toast.makeText(mContext, "Please repeat password", Toast.LENGTH_SHORT).show();
return false;
}
if (!password1.equals(password2)) {
Toast.makeText(mContext, "Passwords don't natch", Toast.LENGTH_SHORT).show();
return false;
}
if (!trainerCode.equals("")) {
if (trainerCode.equals(Finals.T_CODE)) {
isTrainer = true;
return true;
} else {
Toast.makeText(mContext, "Not a real trainer code!", Toast.LENGTH_SHORT).show();
return false;
}
}
return true;
}
public void addNewUser() {
UserClass user = new UserClass(description, email, userID, imageUrl, isTrainer, username, password1);
myRef.child("users").child(userID).setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
pDialog.dismiss();
Toast.makeText(mContext, "Created new User", Toast.LENGTH_SHORT).show();
startActivity(new Intent(SignUpActivity.this, MainActivity.class));
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Finals.PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& data != null && data.getData() != null) {
filePath = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Thanks a lot to all of you who have tried to help!
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
Below SettingsActivity , which I used :
public class SettingsActivity extends AppCompatActivity
{
private Button UpdateAccountSettings;
private EditText userName, userStatus;
private CircleImageView userProfileImage;
private String currentUserID;
private FirebaseAuth mAuth;
private DatabaseReference RootRef;
private static final int GalleryPick = 1;
private StorageReference UserProfileImagesRef;
private ProgressDialog loadingBar;
private Toolbar SettingsToolBar;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
RootRef = FirebaseDatabase.getInstance().getReference();
UserProfileImagesRef = FirebaseStorage.getInstance().getReference().child("Profile Images");
InitializeFields();
userName.setVisibility(View.VISIBLE);
UpdateAccountSettings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
UpdateSettings();
}
});
RetrieveUserInfo();
userProfileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, GalleryPick);
}
});
}
private void InitializeFields()
{
UpdateAccountSettings = (Button) findViewById(R.id.update_settings_button);
userName = (EditText) findViewById(R.id.set_user_name);
userStatus = (EditText) findViewById(R.id.set_profile_status);
userProfileImage = (CircleImageView) findViewById(R.id.set_profile_image);
loadingBar = new ProgressDialog(this);
SettingsToolBar = (Toolbar) findViewById(R.id.settings_toolbar);
setSupportActionBar(SettingsToolBar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowCustomEnabled(true);
getSupportActionBar().setTitle("Account Settings");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==GalleryPick && resultCode==RESULT_OK && data!=null)
{
Uri ImageUri = data.getData();
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1, 1)
.start(this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE)
{
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK)
{
loadingBar.setTitle("Set Profile Image");
loadingBar.setMessage("Please wait, your profile image is updating...");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
Uri resultUri = result.getUri();
StorageReference filePath = UserProfileImagesRef.child(currentUserID + ".jpg");
filePath.putFile(resultUri).addOnCompleteListener(new
OnCompleteListener<UploadTask.TaskSnapshot() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot task)
{
if (task.isSuccessful())
{
Toast.makeText(SettingsActivity.this, "Profile Image uploaded Successfully...", Toast.LENGTH_SHORT).show();
final String downloadUrl = task.getResult().getStorage().getDownloadUrl().toString();
RootRef.child("Users").child(currentUserID).child("image")
.setValue(downloadUrl)
.addOnCompleteListener(new OnCompleteListener<Void() {
#Override
public void onComplete(#NonNull Task<Void task)
{
if (task.isSuccessful())
{
Toast.makeText(SettingsActivity.this, "Image save in Database,
Successfully...", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
else
{
String message = task.getException().toString();
Toast.makeText(SettingsActivity.this, "Error: " + message,
Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
else
{
String message = task.getException().toString();
Toast.makeText(SettingsActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
}
}
private void UpdateSettings()
{
String setUserName = userName.getText().toString();
String setStatus = userStatus.getText().toString();
if (TextUtils.isEmpty(setUserName))
{
Toast.makeText(this, "Please write your user name first....", Toast.LENGTH_SHORT).show();
}
if (TextUtils.isEmpty(setStatus))
{
Toast.makeText(this, "Please write your status....", Toast.LENGTH_SHORT).show();
}
else
{
HashMap<String, Object profileMap = new HashMap<();
profileMap.put("uid", currentUserID);
profileMap.put("name", setUserName);
profileMap.put("status", setStatus);
RootRef.child("Users").child(currentUserID).updateChildren(profileMap)
.addOnCompleteListener(new OnCompleteListener<Void() {
#Override
public void onComplete(#NonNull Task<Void task)
{
if (task.isSuccessful())
{
SendUserToMainActivity();
Toast.makeText(SettingsActivity.this, "Profile Updated
Successfully...", Toast.LENGTH_SHORT).show();
}
else
{
String message = task.getException().toString();
Toast.makeText(SettingsActivity.this, "Error: " + message,
Toast.LENGTH_SHORT).show();
}
}
});
}
}
private void RetrieveUserInfo()
{
RootRef.child("Users").child(currentUserID)
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
if ((dataSnapshot.exists()) && (dataSnapshot.hasChild("name") && (dataSnapshot.hasChild("image"))))
{
String retrieveUserName = dataSnapshot.child("name").getValue().toString();
String retrievesStatus = dataSnapshot.child("status").getValue().toString();
String retrieveProfileImage = dataSnapshot.child("image").getValue().toString();
userName.setText(retrieveUserName);
userStatus.setText(retrievesStatus);
Picasso.get().load(retrieveProfileImage).into(userProfileImage);
}
else if ((dataSnapshot.exists()) && (dataSnapshot.hasChild("name")))
{
String retrieveUserName = dataSnapshot.child("name").getValue().toString();
String retrievesStatus = dataSnapshot.child("status").getValue().toString();
userName.setText(retrieveUserName);
userStatus.setText(retrievesStatus);
}
else
{
userName.setVisibility(View.VISIBLE);
Toast.makeText(SettingsActivity.this, "Please set & update your profile information...",
Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void SendUserToMainActivity()
{
Intent mainIntent = new Intent(SettingsActivity.this, MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}
}
you can add this into build.gradle and tag dependencies
implementation 'de.hdodenhof:circleimageview:3.0.0'
for create Circle ImageView
try it
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/image"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp"
android:src="#drawable/profileuser"
app:civ_border_color="#color/white"
app:civ_border_width="2dp" />
and for loading image added picasso library
Picasso Library
I am not able to pick a image from gallery when I use it in registration activity like as shown below and trying to send it to firebase real time database i failed, but when i create activity to insert only image and no user data to realtime database then i succeed but in registration activity i want to pick image with user data and also want to send it to firebase realtime database but i dont know how to do it
and here is my registrationActivity.java
public class RegistrationActivity extends AppCompatActivity{
private EditText userName, userPassword, userEmail, userAge;
private Button regButton;
private TextView userLogin;
private FirebaseAuth firebaseAuth;
private ImageView userProfilePic;
String email, name, age, password;
private FirebaseStorage firebaseStorage;
private static int PICK_IMAGE = 123;
Uri imagePath;
private StorageReference storageReference;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == PICK_IMAGE && resultCode == RESULT_OK && data.getData() != null){
imagePath = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imagePath);
userProfilePic.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
setupUIViews();
firebaseAuth = FirebaseAuth.getInstance();
firebaseStorage = FirebaseStorage.getInstance();
storageReference = firebaseStorage.getReference();
userProfilePic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("images/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Image"), PICK_IMAGE);
}
});
regButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(validate()){
//Upload data to the database
String user_email = userEmail.getText().toString().trim();
String user_password = userPassword.getText().toString().trim();
firebaseAuth.createUserWithEmailAndPassword(user_email, user_password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
//sendEmailVerification();
sendUserData();
firebaseAuth.signOut();
Toast.makeText(RegistrationActivity.this,"Successfully Registered, Upload complete!", Toast.LENGTH_SHORT).show();
finish();
startActivity(new Intent(RegistrationActivity.this, MainActivity.class));
}else{
Toast.makeText(RegistrationActivity.this, "Registration Failed", Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
userLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(RegistrationActivity.this, MainActivity.class));
}
});
}
private void setupUIViews(){
userName = (EditText)findViewById(R.id.etUserName);
userPassword = (EditText)findViewById(R.id.etUserPassword);
userEmail = (EditText)findViewById(R.id.etUserEmail);
regButton = (Button)findViewById(R.id.btnRegister);
userLogin = (TextView)findViewById(R.id.tvUserLogin);
userAge = (EditText)findViewById(R.id.etAge);
userProfilePic = (ImageView)findViewById(R.id.ivProfile);
}
private Boolean validate(){
Boolean result = false;
name = userName.getText().toString();
password = userPassword.getText().toString();
email = userEmail.getText().toString();
age = userAge.getText().toString();
if(name.isEmpty() || password.isEmpty() || email.isEmpty() || age.isEmpty() || imagePath == null){
Toast.makeText(this, "Please enter all the details", Toast.LENGTH_SHORT).show();
}else{
result = true;
}
return result;
}
private void sendEmailVerification(){
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
if(firebaseUser!=null)
firebaseUser.sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
sendUserData();
Toast.makeText(RegistrationActivity.this, "Successfully Registered, Verification mail sent!", Toast.LENGTH_SHORT).show();
firebaseAuth.signOut();
finish();
startActivity(new Intent(RegistrationActivity.this, MainActivity.class));
}else{
Toast.makeText(RegistrationActivity.this, "Verification mail has'nt been sent!", Toast.LENGTH_SHORT).show();
}
}
});
}
}
private void sendUserData(){
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference myRef = firebaseDatabase.getReference(firebaseAuth.getUid());
StorageReference imageReference = storageReference.child(firebaseAuth.getUid()).child("Images").child("Profile Pic"); //User id/Images/Profile Pic.jpg
UploadTask uploadTask = imageReference.putFile(imagePath);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(RegistrationActivity.this, "Upload failed!", Toast.LENGTH_SHORT).show();
}
}).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
Toast.makeText(RegistrationActivity.this, "Upload successful!", Toast.LENGTH_SHORT).show();
}
});
UserProfile userProfile = new UserProfile(age, email, name);
myRef.setValue(userProfile);
}
}
It always gives me alert that please fill all the details as i am not able to pick image from gallery
I looked through your code and couldn't find an OnActivityResult class in it, so create a protected void onActivityResult(int requestCode, int resultCode, Intent data) {} this will help you get the result data after you pick any image from your gallary.