Retrieve Image from Firebase using Picasso - android

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

Related

adding profileimage node to firebase realtime database

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.

Firebase Won't create new user data in database

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!

Profile image not showing in circle imageView [closed]

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

Not able to pick image from gallery in android app in my registration activity

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.

deactivate account from firebase chat app

i'm using the firebase database for my chat application, When i click on the deactivate button it deletes the user from the Authentication section of firebase but not from the database section of firebase and my all user activity retrieve the user data from the database section. because of this when a user deactivate his account it get delete, but his account is still visible to the other user. below this i'm attaching my codes..
public class SettingsActivity extends AppCompatActivity{
ImageView ivCamera;
private DatabaseReference mUserDatabase;
private FirebaseUser mCurrentUser;
private CircleImageView mDisplayImage;
private TextView mName;
private TextView mStatus;
private Button mProfileBtn;
private Button mDeactivateBtn;
//private Button mImageBtn;
private static final int GALLERY_PICK = 1;
private StorageReference mImageStorage;
private ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
mDisplayImage = (CircleImageView) findViewById(R.id.settings_image);
mName = (TextView) findViewById(R.id.settings_name);
mStatus = (TextView) findViewById(R.id.settings_status);
mProfileBtn = (Button) findViewById(R.id.settings_profile_btn);
mDeactivateBtn = (Button) findViewById(R.id.deactivate_btn);
ivCamera = (ImageView) findViewById(R.id.ivCamera);
mProgressDialog = new ProgressDialog(this);
mImageStorage = FirebaseStorage.getInstance().getReference();
mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
String current_uid = mCurrentUser.getUid();
mUserDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(current_uid);
mUserDatabase.keepSynced(true);
mUserDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name = dataSnapshot.child("name").getValue().toString();
final String image = dataSnapshot.child("image").getValue().toString();
String status = dataSnapshot.child("status").getValue().toString();
String thumb_image = dataSnapshot.child("thumb_image").getValue().toString();
mName.setText(name);
mStatus.setText(status);
if (!image.equals("default")) {
//Picasso.with(SettingsActivity.this).load(image).placeholder(R.drawable.avatar).into(mDisplayImage);
Picasso.with(SettingsActivity.this).load(image).networkPolicy(NetworkPolicy.OFFLINE)
.placeholder(R.drawable.avatar).into(mDisplayImage, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
Picasso.with(SettingsActivity.this).load(image).placeholder(R.drawable.avatar).into(mDisplayImage);
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
//ivGallery =(ImageView) findViewById(R.id.ivGallery);
//ivGallery.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View view) {
//}
//});
mProfileBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String name_value = mName.getText().toString();
String status_value = mStatus.getText().toString();
Intent status_Intent = new Intent(SettingsActivity.this, StatusActivity.class);
status_Intent.putExtra("status_value", status_value);
status_Intent.putExtra("name_value", name_value);
startActivity(status_Intent);
}
});
ivCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(galleryIntent, "SELECT IMAGE"), GALLERY_PICK);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_PICK && resultCode == RESULT_OK) {
Uri imageUri = data.getData();
CropImage.activity(imageUri).setAspectRatio(1, 1).start(this);
//Toast.makeText(SettingsActivity.this, imageUri, Toast.LENGTH_LONG).show();
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
mProgressDialog = new ProgressDialog(SettingsActivity.this);
mProgressDialog.setTitle("Uploading Image.....");
mProgressDialog.setMessage("Please wait while we upload and process the image.");
mProgressDialog.setCanceledOnTouchOutside(false);
mProgressDialog.show();
Uri resultUri = result.getUri();
File thumb_filePath = new File(resultUri.getPath());
String current_user_id = mCurrentUser.getUid();
Bitmap thumb_bitmap = new Compressor(this)
.setMaxWidth(200)
.setMaxHeight(200)
.setQuality(75)
.compressToBitmap(thumb_filePath);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
thumb_bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
final byte[] thumb_byte = baos.toByteArray();
StorageReference filePath = mImageStorage.child("profile_images").child(current_user_id + ".jpg");
final StorageReference thumb_filepath = mImageStorage.child("profile_images").child("thumbs").child(current_user_id + ".jpg");
filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
final String download_url = task.getResult().getDownloadUrl().toString();
UploadTask uploadTask = thumb_filepath.putBytes(thumb_byte);
uploadTask.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> thumb_task) {
String thumb_downloadUrl = thumb_task.getResult().getDownloadUrl().toString();
if (thumb_task.isSuccessful()) {
Map update_hashMap = new HashMap();
update_hashMap.put("image", download_url);
update_hashMap.put("thumb_image", thumb_downloadUrl);
mUserDatabase.updateChildren(update_hashMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
mProgressDialog.dismiss();
Toast.makeText(SettingsActivity.this, "Success Uploading.", Toast.LENGTH_LONG).show();
}
}
});
} else {
Toast.makeText(SettingsActivity.this, "Error in Uploading thumbnail.", Toast.LENGTH_LONG).show();
mProgressDialog.dismiss();
}
}
});
} else {
Toast.makeText(SettingsActivity.this, "Error in Uploading.", Toast.LENGTH_LONG).show();
mProgressDialog.dismiss();
}
}
});
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
public static String random() {
Random generator = new Random();
StringBuilder randomStringBuilder = new StringBuilder();
int randomLength = generator.nextInt(10);
char tempChar;
for (int i = 0; i < randomLength; i++) {
tempChar = (char) (generator.nextInt(96) + 32);
randomStringBuilder.append(tempChar);
}
return randomStringBuilder.toString();
}
public void deactivate(View view)
{
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user!=null)
{
mProgressDialog.setTitle("Deactivate Account");
mProgressDialog.setMessage("Deactivating...");
mProgressDialog.show();
mUserDatabase.child(mCurrentUser.getUid()).removeValue();
user.delete().addOnCompleteListener(new OnCompleteListener<Void>() {
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(getApplicationContext(), "Account is Deactivated", Toast.LENGTH_LONG).show();
finish();
Intent intent = new Intent(SettingsActivity.this, RegisterActivity.class);
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "Account could not be Deactivate", Toast.LENGTH_LONG).show();
}
mProgressDialog.dismiss();
}
});
}
}
}
i want that when the user deactivate his account it will not visible anymore in the all user activity
There are multiple ways to doing this.
When you delete account of user. You should delete all nodes attaching to that user. so that any activity related to user will not be visible to other users.!
if you don't want to remove from database section. you can put another key value with the name of status. if user status is deleted or disable. don't fetch the data of that user in activity.
Hope this will help you to answer your question.
if you've still questions in your mind, you can ask.
For deleting child:
rootRef.child(node).removeValue();
Simple deleting the node.
you can customize it according to your need.
DatabaseReference delete = FirebaseDatabase.getInstance().getReference().child("Node");
delete.setValue(null);

Categories

Resources