Android Firebase multiple image upload - android

I am writing an app to test out firebase where a user can list a product with images.
I'm having issues with the upload as although the pictures are stored, they are not linked to the product (images array not being passed?) and LeakCanary signals an outofmemory error.
All help and input appreciated.
Here's my Product Model
#IgnoreExtraProperties
public class Product {
public String uid;
public String seller;
public String name;
public String description;
public String city;
public double price = 0.0;
public List<Uri> images = new ArrayList<>();
public Product () {
}
public Product(String uid, String seller, String name, String description, String city, double price, List<Uri> images) {
this.uid = uid;
this.seller = seller;
this.name = name;
this.description = description;
this.city = city;
this.price = price;
this.images = images;
}
// [START post_to_map]
#Exclude
public Map<String, Object> toMap() {
HashMap<String, Object> result = new HashMap<>();
result.put("uid", uid);
result.put("seller", seller);
result.put("name", name);
result.put("description", description);
result.put("city", city);
result.put("price", price);
result.put("images", images);
return result;
}
}
And here are is my AddProductActivity
public class AddProductActivity extends BaseActivity implements AddProductContract.View, View.OnClickListener {
private AddProductContract.Presenter mPresenter;
private Bitmap mBitmap;
private byte[] mByteArray;
private List<String> mPhotos;
private Button mPublishBtn;
private EditText mProductNameField;
private EditText mProductDescriptionField;
private EditText mProductPriceField;
private DatabaseReference mFirebaseDatabase;
private StorageReference mFirebaseStorage;
private StorageTask mUploadTask;
private List<Uri> uploadedImages = new ArrayList<>();
private LinearLayout mLinearLayout;
private ImageButton mImageButton;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data == null) {
showEmptyImageError();
} else {
mPhotos = (List<String>) data.getSerializableExtra(GalleryActivity.PHOTOS);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_edit_product_2);
mFirebaseDatabase = FirebaseDatabase.getInstance().getReference();
mFirebaseStorage = FirebaseStorage.getInstance().getReference();
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
mToolbar.setTitle(R.string.addItemTextview);
mLinearLayout = (LinearLayout) findViewById(R.id.activity_add_product);
mLinearLayout.setOnClickListener(this);
mImageButton = (ImageButton) findViewById(R.id.imageButton);
mImageButton.setOnClickListener(this);
mPublishBtn = (Button) findViewById(R.id.publishItemBtn);
mPublishBtn.setOnClickListener(this);
mProductNameField = (EditText) findViewById(R.id.productNameField);
mProductDescriptionField = (EditText) findViewById(R.id.productDescriptionField);
mProductPriceField = (EditText) findViewById(R.id.priceField);
// mPresenter = new AddProductPresenter(this);
}
#Override
public void onClick(View view) {
if ((view == mLinearLayout)) {
hideKeyboard();
} else if (view == mImageButton) {
GalleryConfig config = new GalleryConfig.Build()
.limitPickPhoto(8)
.singlePhoto(false)
.hintOfPick("You can pick up to 8 pictures.")
.filterMimeTypes(new String[]{"image/*"})
.build();
GalleryActivity.openActivity(AddProductActivity.this, 2, config);
} else if (view == mPublishBtn) {
final String name = mProductNameField.getText().toString();
final String description = mProductDescriptionField.getText().toString();
final double price = Double.parseDouble(mProductPriceField.getText().toString());
setPublishingEnabled(false);
showErrorToast(getResources().getString(R.string.publishing));
final String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
mFirebaseDatabase.child("users").child(userId).addListenerForSingleValueEvent(
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
if (user == null) {
showErrorToast(getResources().getString(R.string.empty_user));
} else {
publishProduct(userId, user.getUsername(), name, description,
user.getCity(), price, mPhotos);
}
setPublishingEnabled(true);
finish();
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w("AddProductActivity", "getUser:onCancelled", databaseError.toException());
setPublishingEnabled(true);
}
}
);
}
}
private void setPublishingEnabled(boolean enabled) {
if (enabled) {
mPublishBtn.setVisibility(View.VISIBLE);
} else {
mPublishBtn.setVisibility(View.GONE);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle arrow click here
if (item.getItemId() == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
#Override
public void showEmptyImageError() {
Toast.makeText(getApplicationContext(), R.string.empty_image_error, Toast.LENGTH_SHORT).show();
}
private void publishProduct(String userId, String seller, String name, String description,
String city, double price, List<String> images) {
for (String photo : images) {
Uri file = Uri.fromFile(new File(photo));
StorageReference photoRef = mFirebaseStorage.child("images/" + file.getLastPathSegment());
mUploadTask = photoRef.putFile(file);
mUploadTask.addOnFailureListener(exception -> Log.i("It didn't work", "double check"))
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getDownloadUrl();
uploadedImages.add(downloadUrl);
}
});
}
String key = mFirebaseDatabase.child("products").push().getKey();
Product product = new Product(userId, seller, name, description, city, price, uploadedImages);
Map<String, Object> productValues = product.toMap();
Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put("/products/" + key, productValues);
childUpdates.put("/user-products/" + userId + "/" + key, productValues);
mFirebaseDatabase.updateChildren(childUpdates);
}
//
// private List<Uri> uploadPhotos(List<String> input) {
// images = new ArrayList<>();
// Observable.just(input)
// .map(this::doInBackground)
// .subscribeOn(Schedulers.io())
// .observeOn(AndroidSchedulers.mainThread())
// .doOnSubscribe(this::onPreExecute)
// .subscribe(this::onPostExecute);
// return images;
// }
//
// private void onPreExecute() {
// Log.i("Start time", "SET");
// Toast.makeText(this, R.string.image_formatting_toast, Toast.LENGTH_SHORT).show();
// }
//
// private List<Uri> doInBackground(List<String> photos) {
// for (String photo : mPhotos) {
// Uri file = Uri.fromFile(new File(photo));
// StorageReference photoRef = mFirebaseStorage.child("images/" + file.getLastPathSegment());
// mUploadTask = photoRef.putFile(file);
//
// mUploadTask.addOnFailureListener(exception -> Log.i("It didn't work", "double check"))
// .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
// #Override
// public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Uri downloadUrl = taskSnapshot.getDownloadUrl();
// images.add(downloadUrl);
// }
// });
// }
// return images;
// }
//
// private void onPostExecute(List<Uri> uriSet) {
// Toast.makeText(this, R.string.product_visibility_toast, Toast.LENGTH_SHORT).show();
// Log.i("End time", "SET");
// }
}

Trying to understand your code flow, I can see one thing:
inside your publishProduct method you should put the code (to update the childeren in Firebase) into the addOnSuccessListener, like this:
private void publishProduct(String userId, String seller, String name, String description,
String city, double price, List<String> images) {
String key = mFirebaseDatabase.child("products").push().getKey();
for (String photo : images) {
Uri file = Uri.fromFile(new File(photo));
StorageReference photoRef = mFirebaseStorage.child("images/" + file.getLastPathSegment());
mUploadTask = photoRef.putFile(file);
mUploadTask.addOnFailureListener(exception -> Log.i("It didn't work", "double check"))
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getDownloadUrl();
uploadedImages.add(downloadUrl);
Product product = new Product(userId, seller, name, description, city, price, uploadedImages);
Map<String, Object> productValues = product.toMap();
Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put("/products/" + key, productValues);
childUpdates.put("/user-products/" + userId + "/" + key, productValues);
mFirebaseDatabase.updateChildren(childUpdates);
}
});
}
}
And, if you want to know if the updateChildren operation is completed or not, add the onComplete and onFailure listeners, like this:
mFirebaseDatabase.updateChildren(childUpdates).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
Update
I think you can try to change your database structure, removing the list of images from the product's nodes, adding instead a node in your database that will store only the list of images associated with each product:
"/product-images/" + yourKey + "/" + imageKey
contains the list of his images. imageKey is different from one image the another (it could be for example the image name). yourKey could be the userId or the key associated with each product, it depends on how the database is structured. Then, you can try to use setValue instead of updateChildren into your OnSuccessListener, something like this:
mUploadTask.addOnFailureListener(exception -> Log.i("It didn't work", "double check"))
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getDownloadUrl();
mFirebaseDatabase.child("product-images").child(yourKey).child(imageKey).setValue(downloadUrl.toString());
}
});
Hope this helps!

Related

User profile isn't working. Only e-mail is showing

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

Add new data under child with existing data using ModelClass

I need some help with my app.
I have an Activity where I add user info like name, birthday and add an profileimage for the user.
And when I add the profileimage I get this in my firebase:
And that is working fine. I am using ModelClass, and I know that when I use setValue it deletes the the existing data under that child and saves the new data. But is there a way to just add the new data and still not delete the existing data with ModelClass? I know it works with Hashmap, but I want to use ModelClass.
Here is my Activity for saving info:
public class UserInfoActivity extends AppCompatActivity implements DatePickerDialog.OnDateSetListener {
private CircleImageView civuserinfoprofileimage;
private EditText etuserinfofirstname, etuserinfolastname;
private Button btnbirthdaypicker, btnsaveuserinfo;
private TextView tvbirthday;
private FirebaseAuth mAuth;
private DatabaseReference UsersRef;
private StorageReference UserProfileImageRef;
private ProgressDialog loadingBar;
String currentUserID;
final static int Gallery_Pick = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_info);
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserID);
UserProfileImageRef = FirebaseStorage.getInstance().getReference().child("profilepictures");
loadingBar = new ProgressDialog(this);
civuserinfoprofileimage = (CircleImageView)findViewById(R.id.civ_userinfoprofileimage);
etuserinfofirstname = (EditText)findViewById(R.id.et_userinfofirstname);
etuserinfolastname = (EditText)findViewById(R.id.et_userinfolastname);
btnbirthdaypicker = (Button)findViewById(R.id.btn_birthdaypicker);
tvbirthday = (TextView) findViewById(R.id.tv_birthday);
btnsaveuserinfo = (Button)findViewById(R.id.btn_saveuserinfo);
btnsaveuserinfo.setVisibility(View.INVISIBLE);
btnbirthdaypicker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DialogFragment datePicker = new DatePickerFragment();
datePicker.show(getSupportFragmentManager(), "date picker");
}
});
btnsaveuserinfo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SaveAccountSetupInformation();
}
});
civuserinfoprofileimage.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, Gallery_Pick);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == Gallery_Pick && 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("Profile Image");
loadingBar.setMessage("Saving profileimage");
loadingBar.show();
loadingBar.setCanceledOnTouchOutside(true);
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()) {
btnsaveuserinfo.setVisibility(View.VISIBLE);
Task<Uri> result = task.getResult().getMetadata().getReference().getDownloadUrl();
result.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
final String downloadUrl = uri.toString();
UsersRef.child("profileimage").setValue(downloadUrl)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Intent selfIntent = new Intent(UserInfoActivity.this, UserInfoActivity.class);
selfIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(selfIntent);
Toast.makeText(UserInfoActivity.this, "Pofileimage saved", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
} else {
String message = task.getException().getMessage();
Toast.makeText(UserInfoActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
});
}
}
});
}
else {
Toast.makeText(UserInfoActivity.this, "Error: Image can not be cropped. Try Again.", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
}
private void SaveAccountSetupInformation() {
String firstname = etuserinfofirstname.getText().toString();
String lastname = etuserinfolastname.getText().toString();
String birthday = tvbirthday.getText().toString();
if (TextUtils.isEmpty(firstname) || TextUtils.isEmpty(lastname) || TextUtils.isEmpty(birthday)) {
Toast.makeText(this, "Please enter information..", Toast.LENGTH_SHORT).show();
} else {
FirebaseUser firebaseUser = mAuth.getCurrentUser();
String userid = firebaseUser.getUid();
User user = new User(userid, firstname, lastname, birthday);
UsersRef.setValue(user);
}
}
ModelClass:
public class User {
private String id;
private String lastname;
private String firstname;
private String birthday;
private String profileimage;
public User(String id, String lastname, String firstname, String birthday, String profileimage) {
this.id = id;
this.lastname = lastname;
this.firstname = firstname;
this.birthday = birthday;
this.profileimage = profileimage;
}
public User() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public String getProfileimage() {
return profileimage;
}
public void setProfileimage(String profileimage) {
this.profileimage = profileimage;
}
As far as I understand you're asking about this code:
User user = new User(userid, firstname, lastname, birthday);
UsersRef.setValue(user);
Please read about how to create a minimal, complete, verifiable example, as it's harder for us to isolate that code than it is/should be for you.
When you call setValue() on a location, any existing data at that location is replaced. To only update part of a location, you have to call updateChildren() on it. But as you found, you can't use updateChildren() with a Java class, it only takes a Map.
If you want to update just one child, you can use setValue on a DatabaseReference to that specific child. For example:
UsersRef.child("profileimage").setValue("Value of profile image");
If you want to update multiple-but-not-all child nodes, you'll need to use updateChildren() with a Map. Java 9 and 10 seems to have some nice syntactic sugar to make that more readable: https://stackoverflow.com/a/6802502

progress dialog did not dismiss and I cant update user profile

First I retrieve user info from database, then I want to update the data, but when I click the "save" textview (which I already setOnClick), the progress dialog shows out, did not dismiss and the whole program just keep loading there
public class UserProfile extends Fragment {
private DatabaseReference databaseReference;
private StorageReference storageReference;
private String link;
private StorageTask mUploadTask;
private Uri imageUri;
private ProgressDialog progressDialog;
private final static int PICK_IMAGE_REQUEST = 1;
private CircleImageView circleImageView;
private EditText emailText,nameText,passwordText,confirmPasswordText,mobileText,addressText;
private TextView save;
private List<String> userList;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable final ViewGroup container, #Nullable Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.user_profile, container, false);
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);
emailText = (EditText) view.findViewById(R.id.input_email);
nameText = (EditText) view.findViewById(R.id.input_name);
passwordText = (EditText) view.findViewById(R.id.input_password);
confirmPasswordText = (EditText) view.findViewById(R.id.input_reEnterPassword);
mobileText = (EditText) view.findViewById(R.id.input_mobile);
addressText = (EditText) view.findViewById(R.id.input_address);
circleImageView = (CircleImageView) view.findViewById(R.id.circleImageView);
save = (TextView) view.findViewById(R.id.Save);
progressDialog = new ProgressDialog(getContext());
emailText.setEnabled(false);
userList = new ArrayList<>();
String Email = getArguments().getString("Email");
String email = Email.replace(".", ",");
databaseReference = FirebaseDatabase.getInstance().getReference("User").child(email);
storageReference = FirebaseStorage.getInstance().getReference("User");
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
userList.add(String.valueOf(snapshot.getValue()));
}
emailText.setText(userList.get(2));
nameText.setText(userList.get(6));
passwordText.setText(userList.get(4));
confirmPasswordText.setText(userList.get(1));
mobileText.setText(userList.get(5));
addressText.setText(userList.get(0));
Picasso.get().load(userList.get(3)).into(circleImageView);
return;
}
if (!dataSnapshot.exists()) {
Toast.makeText(getActivity(), "Data not exist!!", Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
return;
}
});
circleImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(getContext(),
Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Permission is not granted
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
Manifest.permission.READ_EXTERNAL_STORAGE)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed; request the permission
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
PICK_IMAGE_REQUEST);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
} else {
selectImage();
}
}
});
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
UpdateAccount();
}
});
return view;
}
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 = getActivity().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.get().load(imageUri).into(circleImageView);
}
}
public void UpdateAccount() {
final String email = emailText.getText().toString();
final String username = nameText.getText().toString();
final String pass = passwordText.getText().toString();
final String phone = mobileText.getText().toString();
final String comfirmpass = confirmPasswordText.getText().toString();
final String address = addressText.getText().toString();
if ((TextUtils.isEmpty(username))) {
nameText.setError("Username is required");
nameText.requestFocus();
return;
}
if ((TextUtils.isEmpty(pass))) {
passwordText.setError("Password is required");
passwordText.requestFocus();
return;
}
if ((TextUtils.isEmpty(phone))) {
mobileText.setError("Phone number is required");
mobileText.requestFocus();
return;
}
if ((TextUtils.isEmpty(comfirmpass))) {
confirmPasswordText.setError("Confirm password is required");
confirmPasswordText.requestFocus();
return;
}
if ((TextUtils.isEmpty(address))) {
addressText.setError("address is required");
addressText.requestFocus();
return;
}
progressDialog.setMessage("Updating your account");
progressDialog.show();
UpdateUser(email, username, pass, phone, comfirmpass, address);
}
public void UpdateUser(final String UserEmail, final String Username, final String Password,
final String PhoneNumber, final String confirmPassword, final String Address) {
//first we encode the email into "," to enable check the firebase database
final String email = UserEmail.replace(".", ",");
databaseReference = FirebaseDatabase.getInstance().getReference("User").child(email);
Log.d("UserEmail", databaseReference.toString());
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull final DataSnapshot dataSnapshot) {
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) {
link = downloadUri.toString();
final User user = new User(email, Username, Password, PhoneNumber, confirmPassword,
Address, link);
databaseReference.setValue(user);
Toasty.success(getActivity().getApplicationContext(), "Update Successful!!", Toast.LENGTH_SHORT, true).show();
progressDialog.dismiss();
}
});
}
});
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
return;
}
});
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
}
I had removed some codes, if you need more info please leave a comment below

Null Pointer Exception as notification was added

I don't get the error when i run the app everything works fine, but when i click on the send message button the app crashes but the message still gets sent. below is my code for the chatActivity and logcat message
package com.paddi.paddi.paddi;
public class ChatActivity extends AppCompatActivity
{
private String messageReceiverId;
private String messageReceiverName;
// private Toolbar ChatToolBar;
private TextView userNameTitle;
private TextView userLastSeen;
private CircleImageView userChatProfileImage;
private ImageButton SendMessageButton;
// private ImageButton SelectImageButton;
private EditText InputMessageText;
FirebaseUser fuser;
DatabaseReference rootRef;
private FirebaseAuth mAuth;
private String messageSenderId;
private RecyclerView userMessagesList;
private final List<Messages> messageList = new ArrayList<>();
private LinearLayoutManager linearLayoutManager;
private MessageAdapter messageAdapter;
private static int Gallery_Pick = 1;
private StorageReference MessageImageStorageRef;
private ProgressDialog loadingBar;
private String downloadImageUrl;
Intent intent;
ValueEventListener seenListener;
String userid;
APIServiceFragment apiService;
boolean notify = false;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
rootRef = FirebaseDatabase.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
messageSenderId = mAuth.getCurrentUser().getUid();
messageReceiverId = getIntent().getExtras().get("visit_user_id").toString();
messageReceiverName = getIntent().getExtras().get("user_name").toString();
MessageImageStorageRef = FirebaseStorage.getInstance().getReference().child("Messages_Pictures");
apiService = Client.getClient("https://fcm.googleapis.com/").create(APIServiceFragment.class);
// ChatToolBar = (Toolbar) findViewById(R.id.chat_bar_layout);
// setSupportActionBar(ChatToolBar);
loadingBar = new ProgressDialog(this);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowCustomEnabled(true);
LayoutInflater layoutInflater = (LayoutInflater)
this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View action_bar_view = layoutInflater.inflate(R.layout.chat_custom_bar, null);
actionBar.setCustomView(action_bar_view);
userNameTitle = (TextView) findViewById(R.id.custom_profile_name);
userLastSeen = (TextView) findViewById(R.id.custom_user_last_seen);
userChatProfileImage = (CircleImageView) findViewById(R.id.custom_profile_image_last_seen);
SendMessageButton = (ImageButton) findViewById(R.id.send_message_btn);
// SelectImageButton = (ImageButton) findViewById(R.id.select_image);
InputMessageText = (EditText) findViewById(R.id.input_message);
messageAdapter = new MessageAdapter(messageList);
userMessagesList = (RecyclerView) findViewById(R.id.messages_list_of_users);
linearLayoutManager = new LinearLayoutManager(this);
userMessagesList.setHasFixedSize(true);
userMessagesList.setLayoutManager(linearLayoutManager);
userMessagesList.setAdapter(messageAdapter);
FetchMessages();
userNameTitle.setText(messageReceiverName);
rootRef.child("Users").child(messageReceiverId).addValueEventListener(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
final String online = dataSnapshot.child("online").getValue().toString();
final String userThumb = dataSnapshot.child("user_thumb_image").getValue().toString();
Picasso.with(ChatActivity.this).load(userThumb).fit().centerInside().networkPolicy(NetworkPolicy.OFFLINE).placeholder(R.drawable.default_profile)
.into(userChatProfileImage, new Callback() {
#Override
public void onSuccess()
{
}
#Override
public void onError()
{
Picasso.with(ChatActivity.this).load(userThumb).fit().centerInside().placeholder(R.drawable.default_profile).into(userChatProfileImage);
}
});
if (online != null) {
if (online.equals("true"))
{
userLastSeen.setText("online");
}
else
{
LastSeenTime getTime = new LastSeenTime();
long last_seen = Long.parseLong(online);
//problem with last seen time here
String lastSeenDisplayTime = getTime.getTimeAgo(last_seen, getApplicationContext()).toString();
userLastSeen.setText(lastSeenDisplayTime);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError)
{
}
});
SendMessageButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
SendMessage();
}
});
// SelectImageButton.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);
//}
//});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==Gallery_Pick && resultCode==RESULT_OK &&data!=null)
{
loadingBar.setTitle("Sending Image");
loadingBar.setMessage("Please Wait");
loadingBar.show();
Uri ImageUri = data.getData();
final String message_sender_ref = "Messages/" + messageSenderId + "/" + messageReceiverId;
final String message_receiver_ref = "Messages/" + messageReceiverId + "/" + messageSenderId;
DatabaseReference user_message_key = rootRef.child("Messages").child(messageSenderId)
.child(messageReceiverId).push();
final String message_push_id = user_message_key.getKey();
final StorageReference filePath = MessageImageStorageRef.child(message_push_id + ".jpg");
final StorageTask<UploadTask.TaskSnapshot> taskSnapshotStorageTask = filePath.putFile(ImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
downloadImageUrl = filePath.getDownloadUrl().toString();
// return filePath.getDownloadUrl();
Map messageTextBody = new HashMap();
messageTextBody.put("message", downloadImageUrl);
messageTextBody.put("isseen", true);
messageTextBody.put("type", "image");
messageTextBody.put("time", ServerValue.TIMESTAMP);
messageTextBody.put("from", messageSenderId);
messageTextBody.put("to", messageReceiverId);
Map messageBodyDetails = new HashMap();
messageBodyDetails.put(message_sender_ref + "/" + message_push_id, messageTextBody);
messageBodyDetails.put(message_receiver_ref + "/" + message_push_id, messageTextBody);
rootRef.updateChildren(messageBodyDetails, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if (databaseError != null) {
Log.d("Chat_Log", databaseError.getMessage().toString());
}
InputMessageText.setText("");
loadingBar.dismiss();
}
});
Toast.makeText(ChatActivity.this, "Picture Sent Successfully.", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
} else {
Toast.makeText(ChatActivity.this, "Picture not sent, Try again", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
}
private void FetchMessages()
{
rootRef.child("Messages").child(messageSenderId).child(messageReceiverId)
.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s)
{
if (dataSnapshot.exists())
{
Messages messages = dataSnapshot.getValue(Messages.class);
messageList.add(messages);
messageAdapter.notifyDataSetChanged();
userMessagesList.smoothScrollToPosition(userMessagesList.getAdapter().getItemCount());
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s)
{
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot)
{
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s)
{
}
#Override
public void onCancelled(DatabaseError databaseError)
{
}
});
// seenMessage(userid);
}
private void seenMessage(final String userid) //add String and userid
{
rootRef = FirebaseDatabase.getInstance().getReference("Messages");
seenListener = rootRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
for (DataSnapshot snapshot : dataSnapshot.getChildren())
{
Messages messages = snapshot.getValue(Messages.class);
if (messages.getTo().equals(fuser.getUid()) && messages.getFrom().equals(ChatActivity.this.userid))//change messages to userid
{
Map messageTextBody = new HashMap();
messageTextBody.put("isseen", true);
snapshot.getRef().updateChildren(messageTextBody);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void SendMessage()
{
notify = true;
String messageText = InputMessageText.getText().toString();
if (TextUtils.isEmpty(messageText))
{
Toast.makeText(ChatActivity.this,
"Input message", Toast.LENGTH_SHORT).show();
}
else
{
String message_sender_ref = "Messages/" + messageSenderId + "/" + messageReceiverId;
final String message_receiver_ref = "Messages/" + messageReceiverId + "/" + messageSenderId;
DatabaseReference user_message_key = rootRef.child("Messages").child(messageSenderId)
.child(messageReceiverId).push();
String message_push_id = user_message_key.getKey();
Map messageTextBody = new HashMap();
messageTextBody.put("message", messageText);
messageTextBody.put("isseen", false);
messageTextBody.put("type", "text");
messageTextBody.put("time", ServerValue.TIMESTAMP);
messageTextBody.put("from", messageSenderId);
messageTextBody.put("to", messageReceiverId);
Map messageBodyDetails = new HashMap();
messageBodyDetails.put(message_sender_ref + "/" + message_push_id, messageTextBody);
messageBodyDetails.put(message_receiver_ref + "/" + message_push_id, messageTextBody);
rootRef.updateChildren(messageBodyDetails).addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task)
{
if (task.isSuccessful())
{
Toast.makeText(ChatActivity.this, "Message Sent", Toast.LENGTH_SHORT).show();
InputMessageText.setText("");
}
else
{
String message = task.getException().getMessage();
Toast.makeText(ChatActivity.this, "Error:" + message, Toast.LENGTH_SHORT).show();
InputMessageText.setText("");
}
}
});
**i tried sending chat notification with the code below
and that was what triggered the error the messages still get sent but the app crashes and restarts itself.**
final String msg = messageText;
rootRef = FirebaseDatabase.getInstance().getReference("Users").child(fuser.getUid());
rootRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
User user = dataSnapshot.getValue(User.class);
if (notify) {
sendNotification(message_receiver_ref, user.getUsername(), msg);
}
notify = false;
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
private void sendNotification(String message_receiver_ref, final String username, final String message)
{
DatabaseReference tokens = FirebaseDatabase.getInstance().getReference("Tokens");
Query query = tokens.orderByKey().equalTo(message_receiver_ref);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
for (DataSnapshot snapshot: dataSnapshot.getChildren())
{
Token token = snapshot.getValue(Token.class);
Data data = new Data(fuser.getUid(), R.mipmap.app_icon, username+": "+message, "New Message",
userid);
Sender sender = new Sender(data, token.getToken());
apiService.sendNotification(sender)
.enqueue(new retrofit2.Callback<MyResponse>() {
#Override
public void onResponse(Call<MyResponse> call, Response<MyResponse> response)
{
if (response.code() == 200)
{
if (response.body().success != 1)
{
Toast.makeText(ChatActivity.this, "Failed!", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onFailure(Call<MyResponse> call, Throwable t)
{
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError)
{
}
});
}
}
this is the logcat below
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
at com.paddi.paddi.paddi.ChatActivity.SendMessage(ChatActivity.java:504)
at com.paddi.paddi.paddi.ChatActivity.access$200(ChatActivity.java:58)
at com.paddi.paddi.paddi.ChatActivity$2.onClick(ChatActivity.java:251)
at android.view.View.performClick(View.java:5274)
at android.view.View$PerformClick.run(View.java:21543)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5765)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
You are getting the following error:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
Because your fuser object is not initialized. To solve this, please add the following line of code in your onCreate() method:
fuser = FirebaseAuth.getInstance().getCurrentUser().getUid();

firebase / glide creating a reference of a image and displaying it

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.

Categories

Resources