I'm new to android development and I have used firebase inside the project and tried all the ways to show the user profile picture inside the image view but none of the solutions works for me. Uploading profile image to firebase is working fine whenever I click on the save button the profile image and cover image uploaded successfully but it's not showing inside the imageview
public class Profile extends AppCompatActivity {
public static final int CAMERA_PERMISSION_CODE = 101;
public static final int CAMERA_REQUEST_CODE = 102;
public static final int PICK_IMAGE_REQUEST = 111;
private Uri uri;
private Uri coverUri;
EditText fullName, email, phone;
Button saveProfileBtn, logoutProfileBtn;
ImageView userProfileImage, userCoverImage;
ImageButton cameraBtn, userCoverBtn;
FirebaseStorage storage;
StorageReference storageReference;
FirebaseAuth fAuth;
FirebaseFirestore fStore;
FirebaseUser fUser;
String userID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ActionBar actionBar;
actionBar = getSupportActionBar();
ColorDrawable colorDrawable = new ColorDrawable(Color.parseColor("#3498DB"));
actionBar.setBackgroundDrawable(colorDrawable);
actionBar.setTitle(Html.fromHtml("<font color='#ffffff'>Profile Settings </font>"));
fullName = findViewById(R.id.userNameProfile);
email = findViewById(R.id.emailUserProfile);
phone = findViewById(R.id.phoneNoProfile);
saveProfileBtn = findViewById(R.id.saveBtnProfile);
logoutProfileBtn = findViewById(R.id.logoutBtn);
userProfileImage = findViewById(R.id.proImgProfile);
cameraBtn = findViewById(R.id.cameraBtnProfile);
userCoverImage = findViewById(R.id.coverPhotoPS);
userCoverBtn = findViewById(R.id.coverImageUpload);
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
fAuth = FirebaseAuth.getInstance();
fStore = FirebaseFirestore.getInstance();
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
cameraBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ImagePicker.with(Profile.this)
.crop() //Crop image(Optional), Check Customization for more option
.compress(512) //Final image size will be less than 1 MB(Optional)
.maxResultSize(512, 512) //Final image resolution will be less than
// 512 x 512(Optional)
.start(10);
// uploadImage();
}
});
userCoverBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ImagePicker.with(Profile.this)
.crop() //Crop image(Optional), Check Customization for more option
.compress(512) //Final image size will be less than 1 MB(Optional)
.maxResultSize(512, 512) //Final image resolution will be less than
// 512 x 512(Optional)
.start(20);
}
});
userID = fAuth.getCurrentUser().getUid();
DocumentReference documentReference = fStore.collection("users").document(userID);
documentReference.addSnapshotListener(this, new EventListener<DocumentSnapshot>() {
#Override
public void onEvent(#Nullable DocumentSnapshot value, #Nullable FirebaseFirestoreException error) {
fullName.setText(value.getString("fname"));
email.setText(value.getString("email"));
phone.setText(value.getString("phone"));
}
});
saveProfileBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
uploadImage(); //Calling function to upload profile image
coverUploadImage(); //Calling function to upload cover image
String fname = fullName.getText().toString();
String femail = email.getText().toString();
String fphone = phone.getText().toString();
if (TextUtils.isEmpty(fname)) {
fullName.setError("Please Enter Your Full Name");
return;
}
if (TextUtils.isEmpty(femail)) {
email.setError("Please Enter Your Email Address");
return;
}
if (fphone.length() < 10) {
phone.setError("Phone Number Shouble Be 10 Digit");
return;
}
if (TextUtils.isEmpty(fphone)) {
phone.setError("Please Enter Your Phone Number");
return;
}
DocumentReference documentReference =
FirebaseFirestore.getInstance().collection("users").document(userID);
Map<String, Object> user = new HashMap<>();
user.put("fname", fname);
user.put("email", femail);
user.put("phone", fphone);
documentReference.update(user).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
Toast.makeText(Profile.this, "Profile Updated Successfully", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Profile.this, "Failed to Update the Profile", Toast.LENGTH_SHORT).show();
}
});
}
});
logoutProfileBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(getApplicationContext(), login.class));
finish();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 10) {
uri = data.getData();
userProfileImage.setImageURI(uri);
}
if (requestCode == 20)
{
coverUri = data.getData();
userCoverImage.setImageURI(coverUri);
}
}
private void showUploadedImage() {
Uri uri = fUser.getPhotoUrl();
Glide.with(this).load(uri).into(userProfileImage);
}
// Function to upload profile image
private void uploadImage() {
if (uri != null) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading Profile Image");
progressDialog.show();
StorageReference ref = storageReference.child("userProfileImages/" + FirebaseAuth.getInstance().getCurrentUser().getUid());
ref.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(Profile.this, "Profile Picture Uploaded Successfully",
Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(Profile.this,
"Failed to Uploaded Profile Picture"+e.getMessage(), Toast.LENGTH_SHORT).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot snapshot) {
double progress = (100.0*snapshot.getBytesTransferred()/snapshot
.getTotalByteCount());
progressDialog.setMessage("Uploaded "+(int)progress+"%");
}
});
}
}
// Function to upload cover image
private void coverUploadImage() {
if (coverUri != null) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading Cover Picture");
progressDialog.show();
StorageReference ref =
storageReference.child("userCoverImages/" + FirebaseAuth.getInstance().getCurrentUser().getUid());
ref.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(Profile.this, "Cover Picture Uploaded Successfully",
Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(Profile.this,
"Failed to Upload Cover Picture"+e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot snapshot) {
double progress = (100.0*snapshot.getBytesTransferred()/snapshot
.getTotalByteCount());
progressDialog.setMessage("Uploaded "+(int)progress+"%");
}
});
}
}
public void saveDocument(View view) {
}
}
You are saying that the uploading is working successfully, so try another way to get the image URL from storage and put the link in the hashmap with the user's phone, name, and email after uploading the image.
So try this:
StorageReference ref = storageReference.child("userProfileImages/" + FirebaseAuth.getInstance().getCurrentUser().getUid());
// Use add on progress like this.
ref.putFile(uri).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot snapshot) {
}
}).continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()){
throw task.getException();
}
return ref.getDownloadUrl();
}
}).addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String photoUrl = uri.toString();
// This is the uri that you want to use after to put in the user's hashmap
Glide.with(MainActivity.this).load(photoUrl).into(userProfileImage);
}
});
Related
I am trying to figure out what is wrong with my code and no data is uploaded in FirebaseDatabase. When I press the post button image url is getting in FirebaseStorage but the rest data does not appear in my database. Here is the code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_a_boat);
firebaseStorage = FirebaseStorage.getInstance();
storageReference = firebaseStorage.getReference();
Brand = findViewById(R.id.BrandOfProduct);
Name = findViewById(R.id.Name);
Categories = findViewById(R.id.Categories);
Description = findViewById(R.id.Description);
Price = findViewById(R.id.Price);
Quantity = findViewById(R.id.Quantity);
UploadProduct = findViewById(R.id.Update);
firebaseAuth = FirebaseAuth.getInstance();
databaseReference = firebaseDatabase.getInstance().getReference("ProductDetails");
try {
String userid = FirebaseAuth.getInstance().getCurrentUser().getUid();
dataa = firebaseDatabase.getInstance().getReference("User").child(userid);
dataa.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
UsersBs usersBs = snapshot.getValue(UsersBs.class);
Address = usersBs.getAddress();
ProductImage = (ImageButton) findViewById(R.id.ProductImage);
ProductImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onSelectImageclick(v);
}
});
UploadProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
brand = Brand.getText().toString().trim();
name = Name.getText().toString().trim();
categories = Categories.getSelectedItem().toString().trim();
description = Description.getText().toString().trim();
quantity = Quantity.getText().toString().trim();
price = Price.getText().toString().trim();
uploadImage();
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}catch (Exception e){
Log.e("Σφάλμα: ",e.getMessage());
}
}
private void uploadImage() {
if(imageUri != null){
final ProgressDialog progressDialog = new ProgressDialog(UploadAProduct.this);
progressDialog.setTitle("Σαλπάρισμα.....");
progressDialog.show();
RandomUID = UUID.randomUUID().toString();
reference = storageReference.child(RandomUID);
BusinessId = FirebaseAuth.getInstance().getCurrentUser().getUid();
reference.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
reference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
ProductDetails info = new ProductDetails(brand, name, categories, quantity, price, description, uri, RandomUID, BusinessId);
Toast.makeText(UploadAProduct.this, ""+info, Toast.LENGTH_SHORT).show();
firebaseDatabase.getInstance().getReference("ProductDetails")
//.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child(RandomUID)
.setValue(info)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
progressDialog.dismiss();
Toast.makeText(UploadAProduct.this,"Έτοιμή για σαλπάρισμα!",Toast.LENGTH_SHORT).show();
}
});
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(UploadAProduct.this,e.getMessage(),Toast.LENGTH_SHORT).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0*taskSnapshot.getBytesTransferred()/taskSnapshot.getTotalByteCount());
progressDialog.setMessage("Σαλπάρισε "+(int) progress+"%");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setCancelable(true);
}
});
}
}
private void startCropImageActivity(Uri imageuri){
CropImage.activity(imageuri)
.setGuidelines(CropImageView.Guidelines.ON)
.setMultiTouchEnabled(true)
.start(this);
}
private void onSelectImageclick(View v){
CropImage.startPickImageActivity(this);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if(cropImageUri !=null && grantResults.length>0 && grantResults[0]== PackageManager.PERMISSION_GRANTED){
startCropImageActivity(cropImageUri);
}else{
Toast.makeText(this,"Ακύρωση! Η άδεια δεν εγκρύθηκε!",Toast.LENGTH_SHORT).show();
}
}
#Override
#SuppressLint("NewApi")
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if(requestCode==CropImage.PICK_IMAGE_CHOOSER_REQUEST_CODE && resultCode== Activity.RESULT_OK){
imageUri = CropImage.getPickImageResultUri(this,data);
if(CropImage.isReadExternalStoragePermissionsRequired(this,imageUri)){
cropImageUri = imageUri;
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},0);
}else{
startCropImageActivity(imageUri);
}
}
if(requestCode==CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE){
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if(resultCode==RESULT_OK){
((ImageButton) findViewById(R.id.ProductImage)).setImageURI(result.getUri());
Toast.makeText(this,"Η εικόνα περικόπηκε με επιτυχία!",Toast.LENGTH_SHORT).show();
}else if(resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE){
Toast.makeText(this,"Αποτυχία περικοπής"+result.getError(),Toast.LENGTH_SHORT).show();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
Well, I checked whether there was a problem with my database rules but nothing seems wrong, both "read" and "write" are turned "true". I also tried to delete my Firebase project and create a new one but the same problem was still there.
I am trying to take inputs from one user and send the same data to another user. I am not sure what to put as an argument in child so that it refers to the same data and I can retrieve and show the data to another user for approval. I am able to send the image but for the data fields like visitor,mobile and flat not sure what to do.
My code is as follows.
Data entry File Code
public class Main4Activity extends AppCompatActivity {
private static final int PERMISSION_CODE = 1000;
private static final int IMAGE_CAPTURE_CODE = 1001;
Button btn;
ImageView imageView;
static Uri image_uri;
ImageView mImageView;
TextView mCaptureBtn;
Button uploadbtn;
static String downloadurl;
public static String Dvisitor;
public static String Dmobile;
static DatabaseReference reff;
//for upload
private Uri filePath;
private final int PICK_IMAGE_REQUEST = 71;
FirebaseStorage storage;
StorageReference storageReference;
//for upload
static String URL;
//Data store of Visitor
static EditText visitor;
static EditText mbnumber;
EditText bnmbr;
static EditText fnmbr;
EditText emal;
EditText pswrd;
HashMap<String,Object> map = new HashMap<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main4);
//for upload
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
//for upload
mImageView = (ImageView) findViewById(R.id.imageView2);
mCaptureBtn = (TextView) findViewById(R.id.textView4);
//Data for Visitor
visitor = (EditText) findViewById(R.id.vname);
mbnumber = (EditText) findViewById(R.id.mnumber);
bnmbr = (EditText) findViewById(R.id.blknmbr);
fnmbr = (EditText) findViewById(R.id.fltnmbr);
emal = (EditText) findViewById(R.id.emailId);
pswrd = (EditText) findViewById(R.id.passwordfield2);
btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
upload();
FirebaseDatabase.getInstance().getReference().child("Image").push().setValue(map)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
map.put("visitor",visitor.getText().toString());
map.put("mobile",mbnumber.getText().toString());
map.put("block",bnmbr.getText().toString());
map.put("flat",fnmbr.getText().toString());
map.put("email",emal.getText().toString());
map.put("password",pswrd.getText().toString());
Toast.makeText(Main4Activity.this, "Successful data registration", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Main4Activity.this, "Failed data registration", Toast.LENGTH_SHORT).show();
}
});
}
});
//Camera functionality click and upload starts
mCaptureBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED || checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
String[] permission = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
requestPermissions(permission, PERMISSION_CODE);
} else {
openCamera();
}
} else {
openCamera();
}
}
});
imageView = (ImageView) findViewById(R.id.imageView);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Main4Activity.this, MainActivity.class);
startActivity(intent);
}
});
}
private void openCamera() {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "New Picture");
values.put(MediaStore.Images.Media.DESCRIPTION, "From the Camera");
image_uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
startActivityForResult(cameraIntent, IMAGE_CAPTURE_CODE);
{
}
}
#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) {
openCamera();
} else {
Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
}
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
mImageView.setImageURI(image_uri);
}
}
private void upload(){
if(image_uri != null)
{
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading...");
progressDialog.show();
final StorageReference ref = storageReference.child("images/"+ UUID.randomUUID().toString());
ref.putFile(image_uri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(Main4Activity.this, "Uploaded", Toast.LENGTH_SHORT).show();
ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
DatabaseReference imagestore = FirebaseDatabase.getInstance().getReference().child("Image").push();
//HashMap<String, String> hasmap = new HashMap<>();
URL = uri.toString();
map.put("imgurl",URL);
//map.put("imageurl", String.valueOf(uri));
imagestore.setValue(map).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Intent intent= new Intent(Main4Activity.this,Main5Activity.class);
startActivity(intent);
}
});
//This is your image url do whatever you want with it.
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(Main4Activity.this, "Failed "+e.getMessage(), Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot
.getTotalByteCount());
progressDialog.setMessage("Uploaded " + (int) progress + "%");
}
});
}
}
}
//Camera functionality click and upload starts
Code for another user to Approve
public class Main5Activity extends AppCompatActivity {
Button btnAllow, btnProhibit;
private String Dvisitor;
private String Dmobile;
private String Dflat;
DatabaseReference reff;
ImageView img;
private DatabaseReference Post;
static TextView textView;
String roadies;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main5);
btnAllow = (Button) findViewById(R.id.button);
btnProhibit = (Button) findViewById(R.id.button2);
textView = (TextView) findViewById(R.id.textView5);
img = (ImageView) findViewById(R.id.imageView3);
imageshow();
init();
readonetime();
}
private void readonetime() {
Query query = Post.orderByKey().limitToLast(1);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot child: dataSnapshot.getChildren()) {
String post = dataSnapshot.child("visitor").getValue(String.class);
String post1 = dataSnapshot.child("mobile").getValue(String.class);
String post2 = dataSnapshot.child("flat").getValue(String.class);
textView.setText("Mr. "+post+"with mobile number: " + post1+"wants to visit your flat: " + post2);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void init() {
Post = FirebaseDatabase.getInstance().getReference().child("Image");
}
private void imageshow() {
reff = FirebaseDatabase.getInstance().getReference().child("Image");
reff.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Picasso.get().load(Main4Activity.URL).fit().into(img);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(Main5Activity.this, "OoooooLalalala", Toast.LENGTH_SHORT).show();
}
});
btnAllow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Main5Activity.this, Main8Activity.class);
startActivity(intent);
}
});
btnProhibit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Main5Activity.this, Main9Activity.class);
startActivity(intent);
}
});
}
}
In your Main5Activity, I think:
This:
for(DataSnapshot child: dataSnapshot.getChildren()) {
String post = dataSnapshot.child("visitor").getValue(String.class);
String post1 = dataSnapshot.child("mobile").getValue(String.class);
String post2 = dataSnapshot.child("flat").getValue(String.class);
textView.setText("Mr. "+post+"with mobile number: " + post1+"wants to visit your flat: " + post2);
}
Must be like this:
for(DataSnapshot ds: dataSnapshot.getChildren()) {
String post = ds.child("visitor").getValue(String.class);
String post1 = ds.child("mobile").getValue(String.class);
String post2 = ds.child("flat").getValue(String.class);
textView.setText("Mr. "+post+"with mobile number: " + post1+"wants to visit your flat: " + post2);
}
I want to save image url in real-time database but none of the solutions that I tried is solve the problem, the code that I wrote it saving the image in firebase storage but I want to save the image url in real-time database, so can anyone help?
this code just save the image in firebase storage
private Button btn_upload,btn_choose;
private ImageView imageView;
private Uri filepath;
private FirebaseStorage storage;
private StorageReference storageReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_choose= (Button) findViewById(R.id.btn_choose);
btn_upload= (Button) findViewById(R.id.btn_upload);
imageView= (ImageView) findViewById(R.id.myImage);
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
btn_upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
uploadImage();
}
});
btn_choose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
chooseImage();
}
});
}
// choose image function code
private void uploadImage() {
if(filepath!=null) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading...");
progressDialog.show();
StorageReference reference = storageReference.child("images/" + UUID.randomUUID().toString());
reference.putFile(filepath).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Image uploaded", Toast.LENGTH_SHORT) .show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progres = (100.0*taskSnapshot.getBytesTransferred()/taskSnapshot.getTotalByteCount());
progressDialog.setMessage("Uploaded"+(int)progres+"%");
}
}) ;
} }
I want to store image in real-time database
You can request download URL for the file after uploading finishes.
Then Add the URL to Real-time Database
reference.putFile(filepath).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Image uploaded", Toast.LENGTH_SHORT) .show();
reference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
//You will get donwload URL in uri
Log.d(TAG, "Download URL = "+ uri.toString());
//Adding that URL to Realtime database
mDatabase.child("imageUrl").setValue(uri.toString());
}
});
}
})
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& data != null && data.getData() != null )
{
filePath = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
private void uploadImage() {
name = txtname.getText().toString();
if(filePath != null)
{
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading...");
progressDialog.show();
StorageReference ref = storageReference.child("images/"+ name);
ref.putFile(filePath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Uploaded", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Failed "+e.getMessage(), Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0*taskSnapshot.getBytesTransferred()/taskSnapshot
.getTotalByteCount());
progressDialog.setMessage("Uploaded "+(int)progress+"%");
}
});
}
Toast.makeText(this, name, Toast.LENGTH_SHORT).show();
}
I want to upload my picture into my image into my database and save it as a url and then call it to my circle image view as a profile picture. But it's not being saved as a url and it's not showing up as a profile.
I have tried switching my code up. Invalidating and restarting android studio. Cleaning and rebuilding the project countless amounts of times. Wiped the data from my phone and my emulator. And I watched a bunch of videos and read answers here and elsewhere.
private Button UpdateAccountSettings;
private EditText userName, userStatus;
private CircleImageView userProfileImage;
private String currentUserID;
private FirebaseAuth mAuth;
private DatabaseReference RootRef;
private static final int GalleryPick = 1;
private StorageReference UserProfileImagesRef;
private ProgressDialog loadingBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
RootRef = FirebaseDatabase.getInstance().getReference();
UserProfileImagesRef = FirebaseStorage.getInstance().getReference().child("Profile Images");
InitializeFields();
userName.setVisibility(View.INVISIBLE);
UpdateAccountSettings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
UpdateSettings();
}
});
RetrieveUserInfo();
userProfileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, GalleryPick);
}
});
}
private void InitializeFields() {
userName = (EditText) findViewById(R.id.set_user_name);
userStatus = (EditText) findViewById(R.id.set_profile_status);
userProfileImage = (CircleImageView) findViewById(R.id.set_profile_image);
loadingBar = new ProgressDialog(this);
UpdateAccountSettings = (Button) findViewById(R.id.update_settings_button);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GalleryPick && resultCode==RESULT_OK && data!=null){
Uri ImageUri = data.getData();
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1,1)
.start(this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if(resultCode == RESULT_OK){
loadingBar.setTitle("Set Profile Image");
loadingBar.setMessage("Please wait your profile image is updating...");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
final Uri resultUri = result.getUri();
StorageReference filePath = UserProfileImagesRef.child(currentUserID + ".jpg");
filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful())
{
Toast.makeText(SettingsActivity.this, "Profile pic upload successful", Toast.LENGTH_SHORT).show();
String downloadUrl = task.getResult().getMetadata().getReference().getDownloadUrl().toString();
RootRef.child("Users").child(currentUserID).child("image")
.setValue(downloadUrl)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(SettingsActivity.this, "Image is saved", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
} else {
String message = task.getException().toString();
Toast.makeText(SettingsActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
} else {
String message = task.getException().toString();
Toast.makeText(SettingsActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
}
}
private void UpdateSettings() {
String setUserName = userName.getText().toString();
String setStatus = userStatus.getText().toString();
if(TextUtils.isEmpty(setUserName)){
Toast.makeText(this, "Please enter your user name...", Toast.LENGTH_SHORT).show();
}
if(TextUtils.isEmpty(setStatus)){
Toast.makeText(this, "Please write your status...", Toast.LENGTH_SHORT).show();
}
else {
HashMap<String, Object> profileMap = new HashMap<>();
profileMap.put("uid", currentUserID);
profileMap.put("name", setUserName);
profileMap.put("status", setStatus);
RootRef.child("Users").child(currentUserID).updateChildren(profileMap)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
SendUserToMainActivity();
Toast.makeText(SettingsActivity.this, "Profile Updated Successfully", Toast.LENGTH_SHORT).show();
} else{
String message = task.getException().toString();
Toast.makeText(SettingsActivity.this, "Error:", Toast.LENGTH_SHORT).show();
}
}
});
}
}
private void RetrieveUserInfo() {
RootRef.child("Users").child(currentUserID)
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if ((dataSnapshot.exists()) && (dataSnapshot.hasChild("name") && (dataSnapshot.hasChild("image"))))
{
String retrieveUserName = dataSnapshot.child("name").getValue().toString();
String retrieveStatus = dataSnapshot.child("status").getValue().toString();
String retrieveProfileImage = dataSnapshot.child("image").getValue().toString();
userName.setText(retrieveUserName);
userStatus.setText(retrieveStatus);
Picasso.get().load(retrieveProfileImage).into(userProfileImage);
}
else if ((dataSnapshot.exists()) && (dataSnapshot.hasChild("name")))
{
String retrieveUserName = dataSnapshot.child("name").getValue().toString();
String retrieveStatus = dataSnapshot.child("status").getValue().toString();
userName.setText(retrieveUserName);
userStatus.setText(retrieveStatus);
}
else {
userName.setVisibility(View.VISIBLE);
Toast.makeText(SettingsActivity.this, "Update your info", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void SendUserToMainActivity() {
Intent mainIntent = new Intent(SettingsActivity.this, MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}
I want to upload the image into my Firebase database using an image URL and then display it in my circle image view as a profile picture.
EDIT !!
I uploaded that code and imported continuation but this is what I see now.
Code2
private void uploadImage() {
if(filePath != null)
{
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading...");
progressDialog.show();
progressDialog.setCancelable(false);
final StorageReference ref = storageReference.child("images/"+ UUID.randomUUID().toString());
ref.putFile(filePath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(AdminPanel.this, "Uploaded", Toast.LENGTH_SHORT).show();
// Upload upload=new Upload( databaseReference.child(cat_spinner.getSelectedItem().toString()).child(databaseReference.push().getKey()).setValue(taskSnapshot.))
ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
DatabaseReference url= databaseReference.child(cat_spinner.getSelectedItem().toString()).child(databaseReference.push().getKey());
Upload upload=new Upload( uri.toString());
url.setValue(upload);
Intent Refresh=new Intent(AdminPanel.this, AdminPanel.class);
startActivity(Refresh);
finish();
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(AdminPanel.this, "Failed "+e.getMessage(), Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0*taskSnapshot.getBytesTransferred()/taskSnapshot
.getTotalByteCount());
progressDialog.setMessage("Uploaded "+(int)progress+"%");
}
});
}
}
I think the update should be like this:
final StorageReference filePath = UserProfileImagesRef.child(currentUserID + ".jpg");
filePath.putFile(resultUri).continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()) {
throw task.getException();
}
// Continue with the task to get the download URL
return filePath.getDownloadUrl();
}}).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful())
{
Toast.makeText(SettingsActivity.this, "Profile pic upload successful", Toast.LENGTH_SHORT).show();
String downloadUrl = task.getResult().toString();
RootRef.child("Users").child(currentUserID).child("image")
.setValue(downloadUrl)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(SettingsActivity.this, "Image is saved", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
} else {
String message = task.getException().toString();
Toast.makeText(SettingsActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
} else {
String message = task.getException().toString();
Toast.makeText(SettingsActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
I am currently working on an Incident Reporting application which allows users to choose and upload images.
I am already successful in posting images to Firebase Storage but I am wondering if it is possible to have a link/url in Firebase Database from which I can click to redirect me to Firebase Storage to see that image.
I want this function so that along with user inputs such as Title, Date, Remarks, the end-user would be able to see the "image" child with the link along with other inputs
I have tried searching StackOverflow and Youtube for answers but most of them are old and seem outdated. There is a command "getDownloadUrl" but i believe it has been deprecated.
This is the code from my class that uploads my image to Firebase Storage
private void uploadImage() {
if (filePath != null) {
final ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.setTitle("Uploading...");
progressDialog.show();
StorageReference ref = storageReference.child("images/"+ UUID.randomUUID().toString());
ref.putFile(filePath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(getActivity(),"Uploaded", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(getActivity(),"Failed"+e.getMessage(), Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0*taskSnapshot.getBytesTransferred()/taskSnapshot.getTotalByteCount());
progressDialog.setMessage("Uploaded"+(int)progress+"%");
}
});
}
}
private void chooseImage() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"),PICK_IMAGE_REQUEST);
}
ReportFragment
import static android.app.Activity.RESULT_OK;
import static com.firebase.ui.auth.AuthUI.getApplicationContext;
public class ReportFragment extends Fragment implements
AdapterView.OnItemSelectedListener{
private Button btnChoose,btnUpload;
private ImageView imageView;
private Uri filePath;
private final int PICK_IMAGE_REQUEST = 71;
private TextView mDisplayDate;
private DatePickerDialog.OnDateSetListener mDateSetListener;
private EditText reportedBy;
private TextView date; //upstairs declare alr as mDisplayDate
private Spinner spinner; //downstairs declare alr as spinner3
private EditText location;
private Spinner spinner2; //downstairs declare alr as spinner2
private EditText details;
private Spinner spinner3; //downstairs declare alr as spinner1
private EditText remarks;
private EditText title;
private Button submitIncident;
public static TextView resultTextView3;
Button scan_btn3;
private ImageView imageView2;
private TextView imgUrl1;
DatabaseReference databaseIncidents;
FirebaseStorage storage;
StorageReference storageReference;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable
ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_report, container, false);
databaseIncidents =
FirebaseDatabase.getInstance().getReference("Incidents");
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
btnChoose = (Button) v.findViewById(R.id.btnChoose);
btnUpload = (Button) v.findViewById(R.id.btnUpload);
imageView = (ImageView) v.findViewById(R.id.imgView);
reportedBy = (EditText) v.findViewById(R.id.etreportedby);
// Below have already line 151
// date = (TextView) v.findViewById(R.id.tvdate);
location = (EditText) v.findViewById(R.id.etlocation);
details = (EditText) v.findViewById(R.id.etdetails);
remarks = (EditText) v.findViewById(R.id.etremarks);
title = (EditText) v.findViewById(R.id.ettitle);
submitIncident = (Button) v.findViewById(R.id.btnSubmit);
resultTextView3 = (TextView)v.findViewById(R.id.result_text3);
scan_btn3 = (Button)v.findViewById(R.id.btn_scan3);
imageView2 = (ImageView)v.findViewById(R.id.ivimagescardinput);
imgUrl1 = (TextView)v.findViewById(R.id.tvimagescard);
btnChoose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
chooseImage();
}
});
// btnUpload.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// uploadImage();
// }
// });
scan_btn3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new
Intent(getActivity(),ScanCodeActivity.class));
}
});
submitIncident.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
incidentSubmit();
uploadImage();
Glide.with(getActivity()).load(URL).into(imageView2);
}
});
return`
}
private void incidentSubmit(){
String reportedname = reportedBy.getText().toString().trim();
String location1 = location.getText().toString();
String details1 = details.getText().toString();
String remarks1 = remarks.getText().toString();
String urgency1 = spinner.getSelectedItem().toString();
String type1 = spinner2.getSelectedItem().toString();
String splocation1 = spinner3.getSelectedItem().toString();
String date1 = mDisplayDate.getText().toString();
String title1 = title.getText().toString();
String qrlocation1 = resultTextView3.getText().toString();
String image1 = imgUrl1.getText().toString();
if(!TextUtils.isEmpty(reportedname)) {
String incidentId = databaseIncidents.push().getKey();
Incident incident = new
Incident(reportedname,location1,details1,remarks1,urgency1,type1,splocation1,date1,title1,qrlocation1,image1);
databaseIncidents.child(incidentId).setValue(incident);
Toast.makeText(getActivity(), "Incident Added", Toast.LENGTH_LONG).show();
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, new IncmanFragment());
fragmentTransaction.commit();
} else {
Toast.makeText(getActivity(), "All fields must be entered",Toast.LENGTH_LONG).show();
}
}
private void uploadImage() {
if (filePath != null) {
final StorageReference ref = storageReference.child("images/"+ UUID.randomUUID().toString());
ref.putFile(filePath).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful()) {
ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String URL = uri.toString();
databaseIncidents.child("imageId").setValue(URL.toString());
}
});
}
}
});
}
}
private void chooseImage() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"),PICK_IMAGE_REQUEST);
}
#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) {
filePath = data.getData();
try{
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getApplicationContext().getContentResolver(),filePath);
imageView.setImageBitmap(bitmap);
}
catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String text = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), text, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
Any help or tutorials is greatly appreciated!
Database Inputs (not including image)
For storing the images to your Firebase Storage, you first set a correct reference and just store the image there, very similar to Firebase Database data storing.
To have a link in the Firebase Database, you can just use downloadUri you can get from storage and have it stored in the database.
The code for this looks something like this, you can take an inspiration from this and come up with a code that suits you more:
private void uploadFile(Bitmap bitmap) {
FirebaseStorage storage = FirebaseStorage.getInstance();
final StorageReference storageRef = storage.getReference();
final StorageReference ImagesRef = storageRef.child("images/"+mAu.getCurrentUser().getUid()+".jpg");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 20, baos);
byte[] data = baos.toByteArray();
final UploadTask uploadTask = ImagesRef.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Log.i("whatTheFuck:",exception.toString());
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onSuccess(final UploadTask.TaskSnapshot taskSnapshot) {
// taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (!task.isSuccessful()) {
Log.i("problem", task.getException().toString());
}
return ImagesRef.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("users").child(mAu.getCurrentUser().getUid());
Log.i("seeThisUri", downloadUri.toString());// This is the one you should store
ref.child("imageURL").setValue(downloadUri.toString());
} else {
Log.i("wentWrong","downloadUri failure");
}
}
});
}
});
}
If i understand correctly you can upload images to storage succesfully but you are having trouble when you want to get that image direct url.
Try this code:
StorageReference storageRef=FirebaseStorage.getInstance().getReference().child("images/"+ UUID.randomUUID().toString());
storageRef.putFile(filePath).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful()){
storageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String URL = uri.toString();
//This is your image url do whatever you want with it.
}
});
}
}
});