uri.tostring() on a null object reference - android

public class profile_activity extends AppCompatActivity implements View.OnClickListener {
private static final int CHOOSE_IMAGE = 101;
ImageView imageViewprofile;
EditText editTextName;
Uri uriProfile;
ProgressBar progressbar;
String profileImageUrl;
Button buttonSave;
FirebaseAuth mauth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_activity);
editTextName = (EditText) findViewById(R.id.editTextName);
imageViewprofile = (ImageView) findViewById(R.id.imageViewProfile);
progressbar = (ProgressBar) findViewById(R.id.progressBar2);
buttonSave =findViewById(R.id.buttonSave);
mauth = FirebaseAuth.getInstance();
loadUserInfo();
imageViewprofile.setOnClickListener(this);
buttonSave.setOnClickListener(this);
}
private void loadUserInfo() {
if(mauth.getCurrentUser() != null){
FirebaseUser user = mauth.getCurrentUser();
if(user != null) {
if (user.getPhotoUrl() != null) {
Glide.with(this).load(user.getPhotoUrl().toString()).into(imageViewprofile);
}
if (user.getDisplayName() != null) {
editTextName.setText(user.getDisplayName());
}
Toast.makeText(getApplicationContext(),"load user info chal rha hai",Toast.LENGTH_SHORT).show();
}
}
}
#Override
protected void onStart() {
super.onStart();
if(mauth.getCurrentUser() == null){
finish();
startActivity(new Intent(this,MainActivity.class));
}
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.imageViewProfile:
showImageChooser();
break;
case R.id.buttonSave:
saveinfo();
break;
}
}
private void saveinfo(){
uploadImageToFirebaseStorage();
String name = editTextName.getText().toString();
if(name.isEmpty()) {
editTextName.setError("Name cannot be empty!");
editTextName.requestFocus();
return;
}
if(profileImageUrl== null){
Toast.makeText(getApplicationContext(),"User profile nalla h 1",Toast.LENGTH_SHORT).show();
}
FirebaseUser user = mauth.getCurrentUser();
if(user != null && profileImageUrl != null){
UserProfileChangeRequest profile = new UserProfileChangeRequest.Builder().
setDisplayName(name).
setPhotoUri(Uri.parse(profileImageUrl)).
build();
user.updateProfile(profile).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(profile_activity.this,"Profile updated",Toast.LENGTH_SHORT).show();
}
}
});
}
if (user==null){
Toast.makeText(getApplicationContext(),"User nalla h",Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==CHOOSE_IMAGE && resultCode==RESULT_OK && data != null && data.getData() != null){
uriProfile = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),uriProfile);
imageViewprofile.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void uploadImageToFirebaseStorage(){
final StorageReference profileImageRef = FirebaseStorage.getInstance().getReference("profilepic"+System.currentTimeMillis()+".jpg");
if(uriProfile != null){
progressbar.setVisibility(View.VISIBLE);
profileImageRef.putFile(uriProfile)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressbar.setVisibility(View.GONE);
//profileImageUrl = profileImageRef.getDownloadUrl().toString();
profileImageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
profileImageUrl = uri.toString();
if(profileImageUrl== null){
Toast.makeText(getApplicationContext(),"User profile nalla h",Toast.LENGTH_SHORT).show();
}
Toast.makeText(profile_activity.this,"Image upload successfull",Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(profile_activity.this,e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressbar.setVisibility(View.GONE);
Toast.makeText(profile_activity.this,e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
}
private void showImageChooser(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Profile Image"),CHOOSE_IMAGE);
}
}
My aim is to load the information on the profile if it already saved.
But it's not saving due the following:
The profileImageUrl is null but only in saveinfo method, it's getting value in uploadImageToFirebaseStorage and still it's null in saveinfo method, I have made it double sure that profilimageurl is a global variable.
I don't understand this.
I'm pretty new to firebase. Please help me out.
Here's the whole code.

As zgc7009 pointed out the problem is occurring due to asynchronous call , when you call
uploadImageToFirebaseStorage();
you assume that the method will return after uploading the image and setting a url to profileImageUrl but no , it returns immediately after setting your listeners, then control reaches if(profileImageUrl== null) which is true because the image is not uploaded yet and your listener callback is not executed to set the profileImageUrl
then the control reaches if(user != null && profileImageUrl != null) which is false for the same reason, SO NOW YOU GET IT , RIGHT?
FIX
if i am not wrong you want to show new user image when he changes the profile but that only can happen when the image is uploaded that means onSuccessLisener() on putFile() is executed that means that code depends on the callback so move it in the callback .
Move the code from saveInfo() to uploadImageToFirebaseStorage(); like that
private void uploadImageToFirebaseStorage(){
final StorageReference profileImageRef = FirebaseStorage.getInstance().getReference("profilepic"+System.currentTimeMillis()+".jpg");
if(uriProfile != null){
progressbar.setVisibility(View.VISIBLE);
profileImageRef.putFile(uriProfile)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressbar.setVisibility(View.GONE);
//profileImageUrl = profileImageRef.getDownloadUrl().toString();
profileImageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
profileImageUrl = uri.toString();
FirebaseUser user = mauth.getCurrentUser();
if(user != null){
UserProfileChangeRequest profile = new UserProfileChangeRequest.Builder().
setDisplayName(name).
setPhotoUri(Uri.parse(profileImageUrl)).
build();
user.updateProfile(profile).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(profile_activity.this,"Profile updated",Toast.LENGTH_SHORT).show();
}
}
});
}
if (user==null){
Toast.makeText(getApplicationContext(),"User nalla h",Toast.LENGTH_SHORT).show();
}
Toast.makeText(profile_activity.this,"Image upload successfull",Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(profile_activity.this,e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressbar.setVisibility(View.GONE);
Toast.makeText(profile_activity.this,e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
}
**note** i removed some `if` conditions because those were guranteed to be true,you will also need to make some variable final because now those are getting used within the inner class
Alternatively
uploadImageToFirebaseStorage(); make this method return the UploadTak if you do want to move code from saveInfo something like below
private Task<UploadTask> uploadImageToFirebaseStorage(){
final StorageReference profileImageRef = FirebaseStorage.getInstance().getReference("profilepic"+System.currentTimeMillis()+".jpg");
if(uriProfile != null){
progressbar.setVisibility(View.VISIBLE);
return profileImageRef.putFile(uriProfile)
}
}
Now set the listener in the saveInfo()
I also encourage you to break the code into methods because code now looks messy, have a good day Himanjli

Related

How do I set download URL for an image to firestore database and realtime Database

I have implemented the code to upload the user photo to storage and retrieve it to the firestore and realtimeDB. the problem is when I set the imageuri to database :
then I'm (or user) updating a photo to firebase, the URI is successfully updated to the profile string..(firestore) and image srting (realtimeDB). but after some time/after the app closes, the photo not loading properly.(or its gone), it didn't use the firebase token as the download Uri.
its like this :
content://com.android.providers.media.documents/document/image%3A81399
then I attached another code to get the updated image URL from storage. But another problem
for now, Both Databases didn't store the URLs
I have attached the code below.
public class ProfileFragment extends Fragment {
public ProfileFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
CircleImageView profileImageView;
FragmentProfileBinding binding;
private Uri photoUri;
private String imageUrl;
FirebaseFirestore firestore;
FirebaseStorage storage;
FirebaseAuth auth;
StorageReference storageReference;
DocumentReference documentReference;
DatabaseReference DBreference;
String currentUserId;
User user; //class
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
binding = FragmentProfileBinding.inflate(inflater, container, false);
firestore = FirebaseFirestore.getInstance();
auth = FirebaseAuth.getInstance();
storage = FirebaseStorage.getInstance();
auth = FirebaseAuth.getInstance();
FirebaseUser fUser = FirebaseAuth.getInstance().getCurrentUser();
currentUserId = fUser.getUid();
documentReference = firestore.collection("Users").document(currentUserId);
storageReference = FirebaseStorage.getInstance().getReference().child("Profile Pictures");
DBreference = FirebaseDatabase.getInstance().getReference().child("Users");
update = binding.updateBtn;
profileImageView= binding.profilePhoto;
clickListener();
return binding.getRoot();
}
private void clickListener() {
profileImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
//noinspection deprecation
startActivityForResult(intent, 3);
}
});
update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressDialog.show();
StorageReference reference = storage.getReference().child("Profile Pictures")
.child(FirebaseAuth.getInstance().getUid());
reference.putFile(photoUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
storageReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
imageUrl = uri.toString();
updateUserProfileToFirestore();
updateUserProfileToDataBase();
}
});
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull #NotNull UploadTask.TaskSnapshot snapshot) {
long totalSi = snapshot.getTotalByteCount();
long transferS = snapshot.getBytesTransferred();
long totalSize = (totalSi / 1024);
long transferSize = transferS / 1024;
progressDialog.setMessage("Uploaded " + ((int) transferSize) + "KB / " + ((int) totalSize) + "KB");
}
});
}
});
}
#SuppressWarnings("deprecation")
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (data.getData() != null) {
photoUri = data.getData();
// profileImageView.setImageURI(imageUri);
}
Toast.makeText(getContext(), "Photo selected!", Toast.LENGTH_SHORT).show();
}catch (Exception e){
Toast.makeText(getContext(), "Error"+e, Toast.LENGTH_SHORT).show();
}
}
private void updateUserProfileToFirestore() {
Map<String, Object> profile = new HashMap<>();
profile.put("profile", imageUrl);
final DocumentReference sDoc = firestore.collection("Users").document(FirebaseAuth.getInstance().getUid());
firestore.runTransaction(new Transaction.Function<Void>() {
#Override
public Void apply(#NonNull Transaction transaction) throws FirebaseFirestoreException {
DocumentSnapshot snapshot = transaction.get(sDoc);
transaction.update(sDoc, profile);
// transaction.update(sDoc, "name", binding.nameBox.getText() );
return null;
}
}).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
progressDialog.setMessage("updated!");
progressDialog.dismiss();
Toast.makeText(getContext(), "Photo Updated!", Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.setMessage("Can't upload");
progressDialog.dismiss();
Toast.makeText(getContext(), "Failed to update, try again later", Toast.LENGTH_SHORT).show();
}
});
// final DatabaseReference
}
// Realtime database
private void updateUserProfileToDataBase() {
HashMap<String, Object> map = new HashMap<>();
map.put("image", imageUrl);
DBreference.child(FirebaseAuth.getInstance().getUid())
.updateChildren(map)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
progressDialog.dismiss();
}
}).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
Toast.makeText(getContext(), "Success", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull #NotNull Exception e) {
Toast.makeText(getContext(), "Failed!", Toast.LENGTH_SHORT).show();
}
});
}
}
Solved! It's based on the storage reference. just changed to "reference".
because I already declared the storage reference. but I entered it twice

Downloading Photo from Firebase Storage

I have tried really every method i found and it stil didnt worked so I am writing here
I am trying to download photo from Firebase storage from my folder "images" where will be file with same name as current Authorized user ID. Only problem here is that it doesnt work. Only background of object is shown (I am changing photo on ShapableImageView)
Bellow I add code, logs and photo from app .
Code :
private void downloadProfile() {
User localUser = new User("","","0","","",0,0,0);
if(mAuth.getCurrentUser()!=null){
database_ref.child("users").child(mAuth.getCurrentUser().getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(snapshot.exists()){
localUser.name = snapshot.child("name").getValue().toString();
localUser.mail = mAuth.getCurrentUser().getEmail();
localUser.age = snapshot.child("age").getValue().toString();
localUser.phone = snapshot.child("phone").getValue().toString();
localUser.address = snapshot.child("address").getValue().toString();
localUser.login_method = Integer.parseInt(snapshot.child("login_method").getValue().toString());
localUser.playlist_amount = Integer.parseInt(snapshot.child("playlist_amount").getValue().toString());
localUser.fav_song_amount = Integer.parseInt(snapshot.child("fav_song_amount").getValue().toString());
profile_email.setText(localUser.mail);
profile_name.setText( localUser.name);
age_edit_t.setText(localUser.age);
phone_edit_t.setText(localUser.phone);
address_edit_t.setText(localUser.address);
// Image download
storageReference = storage.getReferenceFromUrl("gs://altas-notas.appspot.com");
storageReference.child("images/"+mAuth.getCurrentUser().getUid()+".jpg").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
profile_img.setImageURI(uri);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
Logs : https://pastebin.com/F0hCxZsv
No matter how i try to download and set photo its transparent or default.
If it matters , I also add part of code that change image :
private void startGallery() {
Intent cameraIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
cameraIntent.setType("image/*");
if (cameraIntent.resolveActivity(getActivity().getPackageManager()) != null) {
startActivityForResult(cameraIntent, 1000);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
//super method removed
if (resultCode == RESULT_OK) {
if (requestCode == 1000) {
returnUri = data.getData();
Bitmap bitmapImage = null;
try {
bitmapImage = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), returnUri);
profile_img.setImageBitmap(bitmapImage);
} catch (IOException e) {
e.printStackTrace();
}
//Upload image
storageReference = FirebaseStorage.getInstance().getReference();
storageReference.child("images/"+mAuth.getCurrentUser().getUid()).putFile(returnUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful()){
System.out.println("Upload image is successful!");
}else{
System.out.println("Upload image failed!");
}
}
});
//Upload rest of information
updateProfile();
}
}
}
Here in your code:
storageReference.child("images/"+mAuth.getCurrentUser().getUid()+".jpg")
You don't need the .jpg. Try it like this:
storageReference.child("images/"+mAuth.getCurrentUser().getUid())

Firebase Anonymously authentication won work

I'm trying to upload a picture to firebase storage and the take picture is in the form of a bitmap. But I don't want any authentication at all so I have followed the Firebase tutorial on anonymous login. When running the app I don't get any errors but the picture won't upload. I don't really care if the picture taking part is perfect, right now I want to focus on the uploading onto Firebase.
public class MainActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
ImageView imageView;
Button btnOpen;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
imageView = findViewById(R.id.image_view);
btnOpen = findViewById(R.id.btn_open);
textView = findViewById(R.id.textView);
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{
Manifest.permission.CAMERA
}, 100);
}
btnOpen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 100);
}
});
}
#Override
public void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
Log.e("USER", currentUser.toString());
}
public void signInAnonymously() {
mAuth.signInAnonymously()
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d("TAG", "signInAnonymously:success");
FirebaseUser user = mAuth.getCurrentUser();
} else {
// If sign in fails, display a message to the user.
Log.w("TAG", "signInAnonymously:failure", task.getException());
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100) {
assert data != null;
Bitmap takenImage = (Bitmap) Objects.requireNonNull(data.getExtras()).get("data");
signInAnonymously();
// saveImage(takenImage);
imageView.setImageBitmap(takenImage);
}
}
private void saveImage(Bitmap inBitmap) {
long tsLong = System.currentTimeMillis() / 1000;
String ts = Long.toString(tsLong);
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReferenceFromUrl("gs://savephototest.appspot.com");
StorageReference mountainImagesRef = storageRef.child(ts + ".jpg");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
inBitmap.compress(Bitmap.CompressFormat.JPEG, 20, baos);
byte[] data = baos.toByteArray();
UploadTask uploadTask = mountainImagesRef.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getUploadSessionUri();
Log.d("downloadUrl-->", "" + downloadUrl);
}
});
}
}
You are starting the upload of the image before the sign-in (which happens asynchronously) completes. So if you have security rules on storage that the user is signed in before they can upload, that means the write will be rejected.
Since you're leaving onFailure empty, you won't see that error. So the first step to verify if this is happening is to not ignore the error, but surface it. For example with:
public void onFailure(#NonNull Exception exception) {
throw exception;
}
If this is indeed the cause of the problem, you'll need to ensure that the upload only starts after the sign-in has been completed.
A very quick way to do that is to move the call to saveImage into the method that signs in:
public void signInAnonymouslyAndUpload() {
mAuth.signInAnonymously()
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.d("TAG", "signInAnonymously:success");
FirebaseUser user = mAuth.getCurrentUser();
saveImage(takenImage);
} else {
// If sign in fails, display a message to the user.
Log.w("TAG", "signInAnonymously:failure", task.getException());
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100) {
assert data != null;
Bitmap takenImage = (Bitmap) Objects.requireNonNull(data.getExtras()).get("data");
signInAnonymouslyAndUpload();
imageView.setImageBitmap(takenImage);
}
}

Firebase realtime-database don't show items displayed on

I'm beginner in android coding and I have a problem with displaying items in RT-database the items doesn't show up but only the image get uploaded in the storage
by following a tutorial I made this code first i used .getDownloadUrl() then i realized that it's deprecated now so i tried this solution and it's always the same problem the items doesn't shows up in the RT-database but only the image get uploaded in the storage
this is yhe code:
public class AddProductActivity extends AppCompatActivity {
private static final int PICK_IMAGE_REQUEST =1;
private Button ChooseImage;
private Button AddProductButton;
private Button To_the_list;
private EditText name;
private ImageView item_image;
private ProgressBar mProgressBar;
private Uri mImageUri;
private StorageReference mStorageRef;
private DatabaseReference mDatabaseRef;
private StorageTask mProductTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_product);
ChooseImage = findViewById(R.id.choose_img);
AddProductButton= findViewById(R.id.add_new_product);
To_the_list = findViewById(R.id.to_list);
name=findViewById(R.id.product_name);
item_image=findViewById(R.id.product_image);
mProgressBar= findViewById(R.id.progress_bar2);
mStorageRef= FirebaseStorage.getInstance().getReference("Products");
mDatabaseRef= FirebaseDatabase.getInstance().getReference("Products");
ChooseImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFileChooser();
}
});
AddProductButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ProductFile();
}
});
To_the_list.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
private void openFileChooser(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent,PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == PICK_IMAGE_REQUEST && resultCode==RESULT_OK && data != null && data.getData() != null)
{
mImageUri = data.getData();
Picasso.with(this).load(mImageUri).into(item_image);
}
}
private String getFileExtension(Uri uri){
ContentResolver cR = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
}
private void ProductFile() {
if (mImageUri != null) {
final StorageReference fileReference = mStorageRef.child(System.currentTimeMillis() + "." + getFileExtension(mImageUri));
mProductTask = fileReference.putFile(mImageUri);
mProductTask.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 fileReference.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
mProgressBar.setProgress(0);
}
}, 500);
String downloadUri = task.getResult().toString();
Product submit = new Product(
name.getText().toString().trim(),
downloadUri);
String uploadId = mDatabaseRef.push().getKey();
mDatabaseRef.child(uploadId).setValue(submit);
} else {
Log.e("Upload","Upload failed");
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(AddProductActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(this, "Other details not Provided", Toast.LENGTH_SHORT).show();
}
}
No error but image shows up in storage but nothing in realtime-database

how to get url of an uploaded image in firebase storage v16.0.1 [duplicate]

This question already has answers here:
How to use getdownloadurl in recent versions?
(5 answers)
Closed 3 years ago.
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. where to add storagerefernce.downloadUrl().
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
btnChoose = (ImageButton) findViewById(R.id.btnChoose);
imageView = (ImageView) findViewById(R.id.imgView);
btnChoose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
chooseImage();
}
});
}
public 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
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();
imgname = filePath.getLastPathSegment();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
uploadImage();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
private void uploadImage()
{
if(filePath != null)
{
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading...");
progressDialog.show();
StorageReference ref = storageReference.child("images/"+ imgname);
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+"%");
}
});
}
}
}
You can try this way.
val ref = mStorageReference?.child("images/mMobileNumber.jpg")
val uploadTask = ref?.putFile(Uri.fromFile(File(mImagePath)))
uploadTask?.continueWithTask(Continuation<UploadTask.TaskSnapshot, Task<Uri>>
{ task ->
if (!task.isSuccessful) {
task.exception?.let {
throw it
}
}
return#Continuation ref.downloadUrl
})?.addOnCompleteListener { task ->
if (task.isSuccessful) {
val downloadUri = task.result
mTempDatabaseReference?.child("image")?.setValue(downloadUri.toString())
} else {
// Handle failures
// ...
}
}

Categories

Resources