I am attempting to have the user upload an image and then have it then displayed as a profile picture. I am able to upload the image to firebase successfully but I am not able to display it I am following this thread
The current problem i am facing is on how to successfully get the image url to be able to display it
the current state of the code
private DatabaseReference mUserDatabase;
private FirebaseUser mCurrentUser;
//Android Layout
private CircleImageView mDisplayImage;
private TextView mName;
private TextView mStatus;
private Button mStatusBtn;
private Button mImageBtn;
private ProgressDialog mProgressDialog;
private static final int GALLERY_PICK = 1;
private StorageReference mImageStorage;
private Context context = user_profile.this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile);
mDisplayImage = (CircleImageView) findViewById(R.id.profile_picture);
mName = (TextView) findViewById(R.id.profile_user_name);
mStatus = (TextView) findViewById(R.id.profile_user_status);
mStatusBtn = (Button) findViewById(R.id.profile_change_status_btn);
mImageBtn = (Button) findViewById(R.id.profile_change_image_btn);
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 = Objects.requireNonNull(dataSnapshot.child("name").getValue()).toString();
String status = Objects.requireNonNull(dataSnapshot.child("status").getValue()).toString();
String image = Objects.requireNonNull(dataSnapshot.child("image").getValue()).toString();
mName.setText(name);
mStatus.setText(status);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mStatusBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String status_value = mStatus.getText().toString();
Intent status_intent = new Intent(user_profile.this, change_status.class);
status_intent.putExtra("status_value", status_value);
startActivity(status_intent);
}
});
mImageBtn.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, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_PICK && resultCode == RESULT_OK) {
String imageUri = data.getDataString();
CropImage.activity(Uri.parse(imageUri))
.setAspectRatio(1, 1)
.start(this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
mProgressDialog = new ProgressDialog((user_profile.this));
mProgressDialog.setTitle("Uploading");
mProgressDialog.setMessage("Pleas Stand By");
mProgressDialog.setCanceledOnTouchOutside(false);
mProgressDialog.show();
Uri resultUri = result.getUri();
String current_user_id = mCurrentUser.getUid();
StorageReference filepath = mImageStorage.child("profile_images").child(current_user_id + (".jpeg"));
filepath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
final String download_url = Objects.requireNonNull(task.getResult()).getStorage().getDownloadUrl().toString();
mUserDatabase.child("image").setValue(download_url).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Glide
.with(context)
.load()
.into(mDisplayImage);
mProgressDialog.dismiss();
Toast.makeText(user_profile.this, "Succesful Upload", Toast.LENGTH_LONG).show();
}
}
});
} else {
Toast.makeText(user_profile.this, "Error Up Loading", Toast.LENGTH_SHORT).show();
mProgressDialog.dismiss();
}
}
});
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
public String niceRefLink (String date){
StorageReference storageRef = FirebaseStorage.getInstance().getReference();
StorageReference dateRef = storageRef.child("profile_images");
return dateRef.toString();
}}
I believe the issue is with this block of code
public String niceRefLink (String date){
StorageReference storageRef = FirebaseStorage.getInstance().getReference();
StorageReference dateRef = storageRef.child("profile_images");
return dateRef.toString();
}}
When the image is attempted to be displayed glide says that it is unable to locate the image this is how my database is looking
I tried to use the method niceRefLink to display the image but I was unsuccessful i have also tried the download_url string i have created but also did not work
HI, i tried the answer you submitted but I am still having issues the image is successfully getting uploaded to the database but it is still not getting displayed when i run the app i am getting the toast upload successful but the image stays as the preview image.
private String mImageUri;
private void getUserInfo(){
mUserDatabase.child("Users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists() && dataSnapshot.getChildrenCount()>0){
Map<String, Object> map = (Map<String, Object>) dataSnapshot.getValue();
if(map.get("image")!=null){
mImageUri = map.get("image").toString();
Glide.with(getApplication()).load(mImageUri).into(mDisplayImage);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
This code is, How to get image url and how to display in ImageView.
private void getUserInfo(){
mCustomerDatabase.child("Users").child(current_uid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists() && dataSnapshot.getChildrenCount()>0){
Map<String, Object> map = (Map<String, Object>) dataSnapshot.getValue();
if(map.get("image")!=null){
mProfileImageUrl = map.get("image").toString();
Glide.with(getApplication()).load(mProfileImageUrl).into(profileImage);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Hope it's help full and Enjoy.
Related
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.
I was watching YouTube for the instruction implementing storing image to firebase storage.
But, I got an error with getDownloadUrl() I do not know why, it was given codes from firebase helper.
public class SellerPage extends AppCompatActivity {
EditText Address;
EditText price;
EditText description;
Button register;
Button chooseImage;
private FirebaseAuth auth;
private FirebaseFirestore mFirestore;
private StorageReference mStorageRef;
private static final int RESULT_LOAD_IMAGE = 1;
private static final int IMAGE_PICK_CODE = 1000;
private static final int PERMISSION_CODE = 1001;
ImageView View;
public Uri imgUir;
private StorageTask uploadTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_seller_page);
auth = FirebaseAuth.getInstance();
mFirestore= FirebaseFirestore.getInstance();
mStorageRef = FirebaseStorage.getInstance().getReference("Images"); // Storage for the image
Address = (EditText) findViewById(R.id.Address);
price = (EditText) findViewById(R.id.Price);
description = (EditText) findViewById(R.id.description);
register = (Button) findViewById(R.id.addButton);
chooseImage = (Button) findViewById(R.id.image);
View = (ImageView) findViewById(R.id.imageView);
chooseImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Check runtime permission
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
if(checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_DENIED){
// permission not granted. then request it
String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE};
requestPermissions(permissions, PERMISSION_CODE);
}else{
//permition already granted
pickImageFromGallay();
}
}else{
// OS is less than marshmello
pickImageFromGallay();
}
}
}
);
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FileUploader();
addSellerInfo();
}
});
}
private void pickImageFromGallay(){
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, IMAGE_PICK_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK && requestCode == IMAGE_PICK_CODE && data != null){
imgUir = data.getData();
View.setImageURI(data.getData());
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
// super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch(requestCode){
case PERMISSION_CODE:{
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
pickImageFromGallay();
}else{
Toast.makeText(this,"Permission denied!", Toast.LENGTH_SHORT).show();
}
}
}
}
private String getExtension(Uri uri){
ContentResolver cr = getContentResolver();
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
return mimeTypeMap.getExtensionFromMimeType(cr.getType(uri));
}
private void FileUploader(){
final StorageReference Ref = mStorageRef.child(System.currentTimeMillis()+ "." + getExtension(imgUir));
Ref.putFile(imgUir)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Get a URL to the uploaded content
//Uri downloadUrl = taskSnapshot.getDownloadUrl();
Toast.makeText(SellerPage.this, "Uploading Image Successful", Toast.LENGTH_LONG).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
// ...
}
});
}
public void addSellerInfo(){
FirebaseUser user = auth.getCurrentUser();
String ID = user.getUid();
String addressStr = Address.getText().toString().trim();
String priceStr = price.getText().toString().trim();
String descriptionStr = description.getText().toString().trim();
CollectionReference parkspaces = mFirestore.collection("parkspaces");
sellerData parkspace = new sellerData(ID, addressStr, priceStr, descriptionStr);
parkspaces.add(parkspace);
}
}
call getDownloadUrl(), the call is asynchronous and you must subscribe on a success callback to obtain the results:
Ref.putFile(imgUir)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri downloadPhotoUrl) {
Log.e("downloaduri", downloadPhotoUrl.toString());
Toast.makeText(SellerPage.this, "Uploading Image Successful", Toast.LENGTH_LONG).show();
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
// ...
}
});
I was trying to show user's profile in an activity. But when I try to do this, it only shows email. Name, photo, phone number is not showing. How can I show all the field of current user?I
I tried
getCurrentuser()
to get current user info and set them in the field. But it is not showing all the field.
SignUp.java
private EditText signUpnameId, signUpemailId,signUppasswordId,signUpPhoneId;
private Button signup_btn;
private TextView signUpSignIn;
private FirebaseAuth mAuth;
private ProgressBar progressBar;
private ImageView signUpimageView;
private static final String IMAGE_DIRECTORY = "/demonuts";
private int GALLERY = 1, CAMERA = 2;
private DatabaseReference mDatabase;
private Uri imageUri;
private String imageurl;
private static final int IMAGE_REQUEST = 1;
private StorageReference storageReference,imagename;
private StorageTask uploadTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
this.setTitle("Sign Up Here");
// Initialize Firebase Auth
mAuth = FirebaseAuth.getInstance();
progressBar = findViewById(R.id.progressbarId);
signUpnameId = findViewById(R.id.signUpnameId);
signUpemailId = findViewById(R.id.signUpemailId);
signup_btn = findViewById(R.id.signup_btn);
signUpSignIn = findViewById(R.id.signUpSignIn);
signUppasswordId = findViewById(R.id.signUppasswordId);
signUpimageView =findViewById(R.id.signUpImageId);
signUpPhoneId = findViewById(R.id.signUpphoneId);
mDatabase = FirebaseDatabase.getInstance().getReference("Users");
storageReference = FirebaseStorage.getInstance().getReference("usersImage");
signUpSignIn.setOnClickListener(this);
signup_btn.setOnClickListener(this);
signUpimageView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.signup_btn:
userRegister();
break;
case R.id.signUpSignIn:
Intent intent = new Intent(getApplicationContext(),LogIn.class);
startActivity(intent);
break;
case R.id.signUpImageId:
if(uploadTask != null && uploadTask.isInProgress())
{
Toast.makeText(getApplicationContext(),"Upload in process.",Toast.LENGTH_SHORT).show();
}else {
showPictureDialog();
}
}
}
private void showPictureDialog(){
AlertDialog.Builder pictureDialog = new AlertDialog.Builder(this);
pictureDialog.setTitle("Select Action");
String[] pictureDialogItems = {
"Select photo from gallery" };
pictureDialog.setItems(pictureDialogItems,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
choosePhotoFromGallary();
break;
}
}
});
pictureDialog.show();
}
public void choosePhotoFromGallary() {
Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(galleryIntent, GALLERY);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == this.RESULT_CANCELED) {
return;
}
if (requestCode == GALLERY && data != null && data.getData() != null ) {
imageUri = data.getData();
try {
Picasso.get().load(imageUri).into(signUpimageView);
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Failed!", Toast.LENGTH_SHORT).show();
}
}
}
private String getFileExtension(Uri uri){
ContentResolver contentResolver = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(contentResolver.getType(uri));
}
private void userRegister() {
final String name = signUpnameId.getText().toString();
final String email = signUpemailId.getText().toString().trim();
final String password = signUppasswordId.getText().toString().trim();
final String phoneNum = signUpPhoneId.getText().toString();
if(email.isEmpty())
{
signUpemailId.setError("Enter an email address");
signUpemailId.requestFocus();
return;
}
if(!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches())
{
signUpemailId.setError("Enter a valid email address");
signUpemailId.requestFocus();
return;
}
//checking the validity of the password
if(password.isEmpty())
{
signUppasswordId.setError("Enter a password");
signUppasswordId.requestFocus();
return;
}
if(password.length() < 6)
{
signUppasswordId.setError("Password is too short. Password Should be more than 6");
signUppasswordId.requestFocus();
return;
}
//checking the validity of the password
if(name.isEmpty())
{
signUpnameId.setError("Enter a Name");
signUpnameId.requestFocus();
return;
}
if(imageUri == null)
{
signUpSignIn.setError("Please select an image first");
}
progressBar.setVisibility(View.VISIBLE);
mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressBar.setVisibility(View.GONE);
if(task.isSuccessful())
{
mAuth.getCurrentUser().sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful())
{
final StorageReference Imagename = storageReference.child("image"+imageUri.getLastPathSegment());
imageurl = imageUri.toString();
Imagename.putFile(imageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(getApplicationContext(),"Place added Done!",Toast.LENGTH_SHORT).show();
Task<Uri> uriTask = taskSnapshot.getMetadata().getReference().getDownloadUrl();
while(!uriTask.isSuccessful());
Uri downloadUrl = uriTask.getResult();
UserInfo userInfo = new UserInfo(name,email,phoneNum,downloadUrl.toString());
String uploadId = mDatabase.push().getKey();
mDatabase.child(uploadId).setValue(userInfo);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
// ...
}
});
}
else
{
Toast.makeText(getApplicationContext(),"Error: "+task.getException().getMessage(),Toast.LENGTH_SHORT).show();
}
}
});
}
else
{
if(task.getException() instanceof FirebaseAuthUserCollisionException)
{
Toast.makeText(getApplicationContext(),"Already registered",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(),"Eroor: "+ task.getException(),Toast.LENGTH_SHORT).show();
}
}
}
});
}
Profile.Java
private ImageView profileImageview;
private TextView profilenameview,profileemailview, profilephoneview;
private Button profilesignoutbtn;
private FirebaseUser firebaseUser;
private FirebaseAuth mAuth;
private FirebaseDatabase firebaseDatabase;
private ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
// Initialize Firebase Auth
mAuth = FirebaseAuth.getInstance();
final FirebaseUser user = mAuth.getCurrentUser();
firebaseDatabase = FirebaseDatabase.getInstance();
profileImageview = findViewById(R.id.profileImageView);
profileemailview = findViewById(R.id.profileemailview);
profilenameview = findViewById(R.id.profilenameview);
profilephoneview = findViewById(R.id.profilephoneview);
progressBar = findViewById(R.id.progressbarproId);
profilesignoutbtn = findViewById(R.id.profilesignout_btn);
profilesignoutbtn.setOnClickListener(this);
// Initialize Firebase Auth
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Image");
mAuth = FirebaseAuth.getInstance();
String userKey = user.getUid();
databaseReference.child("Profile");
databaseReference.child(userKey);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String userName = dataSnapshot.child("users").getValue(String.class);
profilenameview.setText(user.getDisplayName());
profileemailview.setText(user.getEmail());
Picasso.get().load(user.getPhotoUrl()).into(profileImageview);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
UserInfo.java
public class UserInfo{
String name,email,phoneNum,imageurl;
public UserInfo(String name, String email, String phoneNum, String imageurl) {
this.name = name;
this.email = email;
this.phoneNum = phoneNum;
this.imageurl = imageurl;
}
public UserInfo(String name, String email, String phoneNum, Uri uri) {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhoneNum() {
return phoneNum;
}
public void setPhoneNum(String phoneNum) {
this.phoneNum = phoneNum;
}
public String getImageurl() {
return imageurl;
}
public void setImageurl(String imageurl) {
this.imageurl = imageurl;
}
}
Android studio is showing that
sendEmailVerification()
may produce NullPointerException. Besides
getReference()
and
getDownloadUrl()
also may produce NullPOinterException.How can I solve every issues and correctly get the expected output? Here is a screenshot of profile.
You aren't actually defining the name of the user ,
Use this in onCompleteListener method of firebase auth
new UserProfileChangeRequest.Builder()
.setDisplayName(nameUser)
.build();
I trying to store an image into firebase storage with getDownloadUri but it's already deprecated so I using uri to store image but I have an error in this line: String link = uri.toString;
And the error is cannot resolve symbol uri
private DatabaseReference Userdatabase;
private StorageReference storageReference;
private FirebaseAuth firebaseAuth;
private StorageTask mUploadTask;
private Uri imageUri;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
imageView = (ImageView) findViewById(R.id.imageView);
firebaseAuth = FirebaseAuth.getInstance();
Userdatabase = FirebaseDatabase.getInstance().getReference("User");
progressDialog = new ProgressDialog(Signup.this);
storageReference = FirebaseStorage.getInstance().getReference("Seller");
signupButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RegisterAccount();
}
});
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
}
public void selectImage() {
Intent photoPickerIntent = new Intent();
photoPickerIntent.setType("image/*");
photoPickerIntent.setAction(Intent.ACTION_PICK);
startActivityForResult(photoPickerIntent, PICK_IMAGE_REQUEST);
}
private String getFileExtension(Uri uri) {
ContentResolver cR = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
}
#Override
public 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) {
imageUri = data.getData();
Picasso.with(this).load(imageUri).into(imageView);
}
}
public void RegisterAccount() {
final String email = emailText.getText().toString();
final String username = nameText.getText().toString();
final String pass = passwordText.getText().toString();
if ((TextUtils.isEmpty(address))) {
addressText.setError("address is required");
addressText.requestFocus();
return;
}
AddUser(email, username, pass, phone, comfirmpass, address);
}
public void AddUser(final String UserEmail, final String Username, final String Password,
final String PhoneNumber, final String confirmPassword, final String Address) {
String email = UserEmail.replace(".", ",");
Userdatabase = FirebaseDatabase.getInstance().getReference("User").child(email);
Userdatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
String value = dataSnapshot.getValue(String.class);
Toasty.warning(getApplicationContext(), "The Email you use already Exist !", Toast.LENGTH_SHORT, true).show();
return;
}
if (!dataSnapshot.exists()) {
if (imageUri != null) {
final StorageReference fileReference = storageReference.child(System.currentTimeMillis()
+ "." + getFileExtension(imageUri));
mUploadTask = fileReference.putFile(imageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
fileReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri downloadUri) {
String link = uri.toString;
Toast.makeText(Signup.this, "Register successful", Toast.LENGTH_LONG).show();
final User user = new User(Address, confirmPassword, UserEmail, Password, PhoneNumber, Username,
link);
Userdatabase.setValue(user);
}
});
}
});
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
return;
}
});
firebaseAuth.createUserWithEmailAndPassword(UserEmail, Password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressDialog.dismiss();
if (!task.isSuccessful()) {
Log.i(TAG, "Buyer FirebaseAuth Register : Fail");
Toasty.error(getApplicationContext(), "The Email you use already Exist !", Toast.LENGTH_SHORT, true).show();
} else {
Log.i(TAG, "Buyer FirebaseAuth Register : Success");
UserEmail.replace(".", ",");
final User user = new User(Address, confirmPassword, UserEmail, Password, PhoneNumber, Username,link);
Userdatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (!dataSnapshot.exists()) {
Userdatabase.setValue(user);
Log.i(TAG, "FirebaseDatabase Add Buyer : Success");
Toasty.success(getApplicationContext(), "Register Complete", Toast.LENGTH_SHORT, true).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.w(TAG, "Database Error");
}
});
}
}
});
}
I had removed some of the code, so if you need more details pls comment below. your help is much appreciated
You are getting the following error:
cannot resolve symbol uri
Because you are calling toString() method on an object that does not exist. To solve this, please change the following line of code:
String link = uri.toString();
to
String link = downloadUri.toString();
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);