Retrieve stored image from Firebase Storage - android

I am trying to store and retrieve image by using Firebase. It is okay when storing an image, but I can't show it in an ImageView. It doesn't give an error so I can't understand where is the mistake.
public class MainActivity extends AppCompatActivity {
private Button btnSelectImage;
private ImageView mImageView;
private StorageReference mStorage;
private static final int CAMERA_REQUEST_CODE = 1 ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSelectImage = (Button) findViewById(R.id.btn_image);
mImageView = (ImageView) findViewById(R.id.imageView);
//Get instance
mStorage = FirebaseStorage.getInstance().getReference();
btnSelectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_REQUEST_CODE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==CAMERA_REQUEST_CODE && resultCode==RESULT_OK){
Uri uri = data.getData();
StorageReference filePath = mStorage.child("CameraPhotos").child(uri.getLastPathSegment());
filePath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//Show image
Uri downloadUri = taskSnapshot.getDownloadUrl();
Picasso.with(MainActivity.this).load(downloadUri).into(mImageView);
Toast.makeText(MainActivity.this,"Upload Done",Toast.LENGTH_SHORT).show();
Log.v("Test","image load");
}
});
}
}
}
Also give permissions
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Here is my Firebase Storage Rules
service firebase.storage {
match /b/fir-app-ce89f.appspot.com/o {
match /{allPaths=**} {
allow read, write: if true;
}
}
}
Here is my Activity Layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.yusuf.firebaseapp.MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select Image"
android:id="#+id/btn_image"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<ImageView
android:layout_width="400dp"
android:layout_height="350dp"
android:id="#+id/imageView"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>

I suggest taking a look at FirebaseUI 0.6, which includes a Glide plugin that makes downloading an image from Firebase Storage as simple as:
// Reference to an image file in Firebase Storage
StorageReference storageReference = ...;
// ImageView in your Activity
ImageView imageView = ...;
// Load the image using Glide
Glide.with(this /* context */)
.using(new FirebaseImageLoader())
.load(storageReference)
.into(imageView);

I think it is easier if you use this way
StorageReference mImageRef =
FirebaseStorage.getInstance().getReference("image/test.jpg");
final long ONE_MEGABYTE = 1024 * 1024;
mImageRef.getBytes(ONE_MEGABYTE)
.addOnSuccessListener(new onSuccessListener<byte[]>() {
#Override
public void onSuccess(byte[] bytes) {
Bitmap bm = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
imageView.setMinimumHeight(dm.heightPixels);
imageView.setMinimumWidth(dm.widthPixels);
imageView.setImageBitmap(bm);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
}
});

private List<Upload> uploads;
Upload upload = uploads.get(position);
Glide.with(context).load(upload.getUrl()).into(holder.imageView);

Related

How to upload two(2) image with caption to firebase database?

Hi guys I'm trying to upload 2(two) images on firebase with captions but it only uploads the first successfully then the field for 2nd image box (nimagetrail2) copies the bitmap on the 1st image box (nimagetrial) on the database. Can someone help me fix this so that each image gets its own bitmap?
XML file
<ImageView
android:id="#+id/imagetrial"
android:layout_width="85dp"
android:layout_height="85dp"
android:layout_marginTop="32dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/id" />
<ImageView
android:id="#+id/imagetrail2"
android:layout_width="85dp"
android:layout_height="85dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/imagetrial"
app:srcCompat="#drawable/payment_l" />
<EditText
android:id="#+id/editcap"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:text="Name"
app:layout_constraintEnd_toEndOf="#+id/imagetrail2"
app:layout_constraintStart_toStartOf="#+id/imagetrail2"
app:layout_constraintTop_toBottomOf="#+id/imagetrail2" />
<EditText
android:id="#+id/editcap2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:text="Name"
app:layout_constraintEnd_toEndOf="#+id/editcap"
app:layout_constraintStart_toStartOf="#+id/editcap"
app:layout_constraintTop_toBottomOf="#+id/editcap" />
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:text="Button"
app:layout_constraintEnd_toEndOf="#+id/editcap2"
app:layout_constraintStart_toStartOf="#+id/editcap2"
app:layout_constraintTop_toBottomOf="#+id/editcap2" />
Java code
private ImageView nimagetrial, nimagetrial2;
private EditText neditcap,neditcap2;
private Button nsave;
private Bitmap bitmap,bitmap1;
private
Uri filepath,filepath1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_n_trial);
nimagetrial = findViewById(R.id.imagetrial);
nimagetrial2 = findViewById(R.id.imagetrail2);
neditcap = findViewById(R.id.editcap);
neditcap2 = findViewById(R.id.editcap2);
nsave = findViewById(R.id.button3);
nimagetrial.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ImagePicker.Companion.with(nTrial.this)
.crop()
.compress(1040)
.maxResultSize(1270,1270)
.start(10);
}
});
nimagetrial2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ImagePicker.Companion.with(nTrial.this)
.crop()
.compress(1040)
.maxResultSize(1270,1270)
.start(20);
}
});
nsave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
savetrialData();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 10 && resultCode == RESULT_OK){
filepath = data.getData();
try{
InputStream inputStream=getContentResolver().openInputStream(filepath);
bitmap= BitmapFactory.decodeStream(inputStream);
nimagetrial.setImageBitmap(bitmap);
}catch (Exception ex)
{
}
}else if (requestCode == 20 && resultCode == RESULT_OK){
filepath1 = data.getData();
try {
InputStream inputStream1 = getContentResolver().openInputStream(filepath1);
bitmap1 = BitmapFactory.decodeStream(inputStream1);
nimagetrial2.setImageBitmap(bitmap1);
}catch (Exception ex){
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void savetrialData() {
ProgressDialog dialog = new ProgressDialog(this);
dialog.setTitle("Trail Uploader");
dialog.show();
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference uploader = storage.getReference("ntrial"+new Random().nextInt(50));
uploader.putFile(filepath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(#NonNull UploadTask.TaskSnapshot taskSnapshot) {
uploader.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(#NonNull Uri uri) {
dialog.dismiss();
FirebaseDatabase mFD = FirebaseDatabase.getInstance();
DatabaseReference mDR = mFD.getReference("Trial");
nTrailModel obj = new nTrailModel(neditcap.getText().toString(), neditcap2.getText().toString(),uri.toString(),uri.toString());
mDR.child(neditcap.getText().toString()).setValue(obj);
neditcap.setText("");
neditcap2.setText("");
nimagetrial.setImageResource(R.drawable.id);
nimagetrial2.setImageResource(R.drawable.payment_l);
}
});
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot snapshot) {
float percent = (100*snapshot.getBytesTransferred())/snapshot.getTotalByteCount();
dialog.setMessage(" Uploadind T_T: "+(int)percent+" %");
}
});
}
}

Android Firebase Retrieve Image Url

I want to get the DownloadUrl from an image I uploaded to Firebase but when I try loading it later, I only get a not found exception:
public class ProfileActivity extends AppCompatActivity{
private static final int CHOOSE_IMAGE = 200;
//Initialize items
EditText inputUsername, inputBirthday;
FloatingActionButton mainaction;
FloatingActionButton homeaction;
FloatingActionButton profileaction;
StorageReference profileimageRef;
String profileimageurl;
Button actionSaveProfile;
FirebaseAuth mAuth;
ProgressBar progressBar;
ImageView profileimage;
Boolean isfabopen;
Uri uriProfileImage;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
isfabopen = false;
mainaction = findViewById(R.id.fab_expand);
homeaction = findViewById(R.id.fab_home);
profileaction = findViewById(R.id.fab_profile);
inputUsername = findViewById(R.id.input_username);
inputBirthday = findViewById(R.id.input_birthday);
actionSaveProfile = findViewById(R.id.action_save_profile);
profileimage = findViewById(R.id.profile_image);
progressBar = findViewById(R.id.progressbar);
mAuth = FirebaseAuth.getInstance();
//Expand, collapse menu
mainaction.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!isfabopen)
{
ShowFab();
}else
{
CloseFab();
}
}
});
profileimage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showImageChooser();
}
});
homeaction.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(ProfileActivity.this, MainActivity.class));
}
});
actionSaveProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveUserData(v);
}
});
loadUserData();
}
private void loadUserData() {
FirebaseUser user = mAuth.getCurrentUser();
//If no profile picture found
if(user.getPhotoUrl() != null)
{
String photoUrl = user.getPhotoUrl().toString();
//Set profile picture
Glide.with(this)
.load(user.getPhotoUrl().toString())
.into(profileimage);
}
//If no username found
if(user.getDisplayName() != null)
{
String username = user.getDisplayName();
//Insert display name
inputUsername.setText(user.getDisplayName());
}
}
private void saveUserData(View v)
{
String name = inputUsername.getText().toString().trim();
String birthtday = inputBirthday.getText().toString().trim();
//Check if has content
if(name.isEmpty())
{
Snackbar.make(v, R.string.message_username_empty, Snackbar.LENGTH_SHORT)
.setAction("Action", null).show();
inputUsername.requestFocus();
}else if(birthtday.isEmpty()) {
Snackbar.make(v, R.string.message_birthday_empty, Snackbar.LENGTH_SHORT)
.setAction("Action", null).show();
inputBirthday.requestFocus();
}
//Get user
FirebaseUser user = mAuth.getCurrentUser();
//Upload information
if(user != null && profileimageurl != null)
{
UserProfileChangeRequest profileChangeRequest = new UserProfileChangeRequest.Builder()
.setDisplayName(name)
.setPhotoUri(Uri.parse(profileimageurl))
.build();
Log.wtf("ImageURL3", profileimageurl);
//Show progressbar
progressBar.setVisibility(View.VISIBLE);
user.updateProfile(profileChangeRequest).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
//Hide progressbar
progressBar.setVisibility(View.GONE);
if(task.isSuccessful())
{
Toast.makeText(ProfileActivity.this, R.string.message_profile_updated, Toast.LENGTH_SHORT).show();
}else
{
Toast.makeText(ProfileActivity.this, task.getException().getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
//When got activity result from showImageChooser
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//Check if result is ok
if(requestCode == CHOOSE_IMAGE && resultCode == RESULT_OK && data !=null && data.getData() != null)
{
//Save uri of image
uriProfileImage = data.getData();
try
{
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uriProfileImage);
profileimage.setImageBitmap(bitmap);
uploadToFirebase();
}catch (Exception ex)
{
ex.printStackTrace();
}
}
}
private void uploadToFirebase() {
//Select destination filename, folder
profileimageRef = FirebaseStorage.getInstance().getReference("profilepictures/" + System.currentTimeMillis() + ".jpg");
Log.wtf("ImageURL", profileimageRef.toString());
//Upload image
if(uriProfileImage != null)
{
//Show progressbar
progressBar.setVisibility(View.VISIBLE);
profileimageRef.putFile(uriProfileImage).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
//Hide progressbar
progressBar.setVisibility(View.GONE);
//Check if was successful
if(task.isSuccessful())
{
//Set profile image url
profileimageurl = task.getResult().toString();
Log.wtf("ImageURL2", profileimageurl);
}else
{
Toast.makeText(ProfileActivity.this, task.getException().getLocalizedMessage() , Toast.LENGTH_SHORT).show();
}
}
});
}
}
private void showImageChooser()
{
//Create chooser
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
//Start chooser activity and wait for result
startActivityForResult(Intent.createChooser(intent, getString(R.string.label_profile_pic_chooser)), CHOOSE_IMAGE);
}
private void ShowFab() {
//Bool for menu open
isfabopen = true;
//Set buttons visible
homeaction.setVisibility(View.VISIBLE);
profileaction.setVisibility(View.VISIBLE);
//Rotate main button
mainaction.animate().rotation(135f);
//Expanding to top
homeaction.animate().translationY(getResources().getDimension(R.dimen.standard_100)).rotation(0f);
profileaction.animate().translationY(getResources().getDimension(R.dimen.standard_55)).rotation(0f);
}
private void CloseFab() {
//Bool for menu closed
isfabopen = false;
//Hide buttons
homeaction.setVisibility(View.VISIBLE);
profileaction.setVisibility(View.VISIBLE);
//Rotate main button
mainaction.animate().rotation(0f);
//Collapsing
homeaction.animate().translationY(getResources().getDimension(R.dimen.standard_0)).rotation(135f);
profileaction.animate().translationY(getResources().getDimension(R.dimen.standard_0)).rotation(135f);
}
//Check if user is logged in
#Override
protected void onStart() {
super.onStart();
//Check if user is already loggged in
if(mAuth.getCurrentUser() == null)
{
finish();
startActivity(new Intent(ProfileActivity.this, LoginActivity.class));
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
//Go back to home activity
finish();
startActivity(new Intent(ProfileActivity.this, MainActivity.class));
}
}
XML Code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<RelativeLayout
android:id="#+id/relativeLayout2"
android:layout_width="match_parent"
android:layout_height="200dp"
android:background="#color/colorPrimary"
android:backgroundTint="#color/colorPrimary"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<de.hdodenhof.circleimageview.CircleImageView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/profile_image"
android:layout_width="156dp"
android:layout_height="156dp"
android:src="#drawable/camera_placeholder"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/relativeLayout2">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingLeft="#dimen/standard_23"
android:paddingRight="#dimen/standard_23">
<EditText
android:id="#+id/input_username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="#color/colorProfileAccent"
android:hint="#string/label_username"
android:inputType="textPersonName"
android:paddingBottom="15dp"
android:textColor="#color/colorProfileAccent"
android:textColorHint="#color/colorProfileAccent" />
<EditText
android:id="#+id/input_birthday"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="#color/colorProfileAccent"
android:hint="#string/label_birthday"
android:inputType="textPersonName"
android:paddingBottom="15dp"
android:textColor="#color/colorProfileAccent"
android:textColorHint="#color/colorProfileAccent" />
<Button
android:id="#+id/action_save_profile"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="7dp"
android:background="#drawable/rounded_btn_profile"
android:text="#string/apply_changes"
android:textColor="#color/colorProfileText" />
</LinearLayout>
<ProgressBar
android:id="#+id/progressbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:visibility="gone" />
</RelativeLayout>
<android.support.design.widget.CoordinatorLayout
android:id="#+id/coordinatorLayout"
android:layout_width="wrap_content"
android:layout_height="197dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent">
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab_home"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/standard_23"
android:rotation="90"
android:visibility="gone"
app:fabSize="mini"
app:srcCompat="#drawable/ic_home" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab_profile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/standard_23"
android:rotation="0"
android:translationY="#dimen/standard_55"
android:visibility="gone"
app:fabSize="mini"
app:srcCompat="#drawable/ic_account_box" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab_expand"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
app:fabSize="normal"
app:srcCompat="#drawable/ic_add" />
</android.support.design.widget.CoordinatorLayout>
</android.support.constraint.ConstraintLayout>
I only get a java.io.FileNotFoundException: No such file or directory exception. Earlier I tried saving it with an Success-Listener as it's shown here: https://stackoverflow.com/a/50743192/6274419. But that also hadn't worked because the function doesn't exist in the newer Firebase version.
In general I want to display a profile picture and the username which are saved to Firebase and retrieved on next application startup.
Thanks in Advance!
It takes some time to upload the image in firebase. So you can only retrieve the image when it is completely saved in database. Please call the loadUserData() method in OnSuccess and let me know if it works.
private void uploadToFirebase() {
//Select destination filename, folder
profileimageRef = FirebaseStorage.getInstance().getReference("profilepictures/" + System.currentTimeMillis() + ".jpg");
Log.wtf("ImageURL", profileimageRef.toString());
//Upload image
if(uriProfileImage != null)
{
//Show progressbar
progressBar.setVisibility(View.VISIBLE);
profileimageRef.putFile(uriProfileImage).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
//Hide progressbar
progressBar.setVisibility(View.GONE);
//Check if was successful
if(task.isSuccessful())
{
//Set profile image url
profileimageurl = task.getResult().toString();
loadUserData();
Log.wtf("ImageURL2", profileimageurl);
}else
{
Toast.makeText(ProfileActivity.this, task.getException().getLocalizedMessage() , Toast.LENGTH_SHORT).show();
}
}
});
Solved it now by using another structure/method for retrieving the url with a UploadTask:
private void uploadToFirebase() {
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReference();
//Select destination filename, folder
final StorageReference profileimageRef = storageRef.child("profilepictures/" + System.currentTimeMillis() + ".jpg");
UploadTask uploadTask = profileimageRef.putFile(uriProfileImage);
Log.wtf("ImageURL", profileimageRef.toString());
//Upload image
if(uriProfileImage != null)
{
//Show progressbar
progressBar.setVisibility(View.VISIBLE);
Task<Uri> uriTask = uploadTask.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 profileimageRef.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
progressBar.setVisibility(View.GONE);
if(task.isSuccessful()) {
profileimageurl = task.getResult().toString();
}
}
});
}
}

Rotate image from uri address, using Picasso

I have successfully upload a Users profile image to the Firebase storage area under their UserID.
From there I have put the file path to that image in the Firebase database under the usersID
Firebase Database Structure, Showing he profileImage uri that is linked to the firebase storage area
When I am displaying the image on the page the image is rotated the wrong way around. The photo on my phone is portrait, but it is saving in the Firebase storage area as landscape.
Image Stored In Landscape orientation in Firebase Storage, but was taken in portrait orientation
The image rendered on my phone in the wrong orientation
What I want to be able to do is let the user select an image from the gallery, then display the image on a page.Then I want to be able to let the user rotate the image themselves, left or right using two buttons.
When I press the rotate buttons. The image successfully rotates once.
Then when I press the Save Profile Image button it sends the original image from the gallery to the Firebase Storage area. It is storing and sending the wrong image to the Storage. Essentially, it is saving the original, unrotated image to the storage.
Is there a way that I can fix this?
Here is my code:
private FirebaseAuth auth;
private DatabaseReference myRef;
private FirebaseDatabase database;
private StorageReference storageReference;
private FirebaseUser user;
private ImageView profileImage;
private Uri imageUri;
private static final int GALLERY_INTENT = 2;
private ProgressDialog progressDialog;
/*
Skip irrelevant code
*/
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_upload_image, container, false);
// Creating firebase links etc
database = FirebaseDatabase.getInstance();
myRef = FirebaseDatabase.getInstance().getReference();
auth = FirebaseAuth.getInstance();
storageReference = FirebaseStorage.getInstance().getReference();
user = auth.getCurrentUser();
// Setting buttons
profileImage = (ImageView) view.findViewById(R.id.imageViewProfileImage);
ImageView rotateLeft = (ImageView) view.findViewById(R.id.imageRotateLeft);
ImageView rotateRight = (ImageView) view.findViewById(R.id.imageRotateRight);
Button uploadProfileImage = (Button) view.findViewById(R.id.buttonUploadProfileImage);
Button saveProfileImage = (Button) view.findViewById(R.id.buttonSaveProfileImage);
// Rotate Left is a button
rotateLeft.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(profileImage != null)
{
// Rotate image 90
Picasso.get().load(imageUri).rotate(90).into(profileImage);
}
}
});
// Rotate Right is a button
rotateRight.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(profileImage != null)
{
// Rotate image -90
Picasso.get().load(imageUri).rotate(-90).into(profileImage);
}
}
});
uploadProfileImage.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// Send user to gallery
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, GALLERY_INTENT);
}
});
// Save image to storage area
saveProfileImage.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
progressDialog.setMessage("Uploading Image Please Wait...");
progressDialog.show();
final StorageReference filePath = storageReference.child("Images").child(user.getUid()).child(imageUri.getLastPathSegment());
filePath.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>()
{
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot)
{
Toast.makeText(getActivity(), "Uploaded Successfully!", Toast.LENGTH_SHORT).show();
Uri downloadUri = taskSnapshot.getDownloadUrl();
// Save image uri in the Firebase database under the usersID
myRef.child("Users").child(user.getUid()).child("profileImage").setValue(downloadUri.toString());
progressDialog.dismiss();
}
}).addOnFailureListener(new OnFailureListener()
{
#Override
public void onFailure(#NonNull Exception e)
{
progressDialog.dismiss();
Toast.makeText(getActivity(), "Failed To Upload!", Toast.LENGTH_SHORT).show();
}
});
}
});
return view;
}
// Get image data and display on page
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GALLERY_INTENT && resultCode == RESULT_OK)
{
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Displaying Image...");
progressDialog.show();
imageUri = data.getData();
Picasso.get().load(imageUri).into(profileImage);
progressDialog.dismiss();
}
}
You can try downloading image as a Bitmap, then rotating it and then saving. Here is the code you can use to do that with Picasso:
int rotationAngle; // You set this angle before calling the method
Target target = new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
Matrix matrix = new Matrix();
matrix.postRotate(rotationAngle);
Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(),
matrix, true);
// Save the rotatedBitmap elsewhere
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {}
};
void downloadImageRotateAndSave() {
Picasso.with(getContext()).load(imageUri).into(target);
}
first let see what is the problem. First of all, picaso open the image file and retrieve a bitmap from it. This bitmap is what is displayed into the imageView. When you rotate the image, what you are doing is rotating the bitmap, but the file with the original photo never change. So if you want to upload the rotate photo, you have to retrieve the new bitmap from the image view, create a new file with it and upload the new file.
That must do the trick.
Good luck

Displaying images from Firebase DB that's stored in Firebase Storage

I am making a fitness android application and I am storing progress images of Users using the Firebase Storage. A reference to the Firebase Database is also made with the URL of the image thats found in Firebase Storage.
I am attempting to retrieve the images and show them in a GridLayout but am recieveing a 'Bound to Type Error'
I am displaying the images using a recyclerView.
I am also using Picasso to load the image.
Photo Activity
public class PhotosActivity extends BaseActivity {
#BindView(R.id.activity_photos_fab)
FloatingActionButton newPhoto;
private StorageReference mStorage;
private ProgressDialog mProgressDialog;
RecyclerView recyclerView;
FirebaseRecyclerAdapter adapter;
private static final int GALLERY_INTENT = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photos);
ButterKnife.bind(this);
mStorage = FirebaseStorage.getInstance().getReference();
mProgressDialog = new ProgressDialog(this);
recyclerView = (RecyclerView) findViewById(R.id.activity_photos_recyclerView);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GALLERY_INTENT && resultCode == RESULT_OK) {
mProgressDialog.setTitle("Uploading..");
mProgressDialog.show();
// Get the URI of the photo
Uri uri = data.getData();
StorageReference filepath = mStorage.child("Photos").child(userEmail).child(uri.getLastPathSegment());
Firebase photosReference = new Firebase(Utils.FIRE_BASE_PHOTOS_REFERENCE + userEmail);
// Add the photo to the database
// if successful then show a toast to say a photo has been added
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(getApplicationContext(), "You added a photo", Toast.LENGTH_LONG).show();
mProgressDialog.dismiss();
}
});
String photoURL = filepath.getDownloadUrl().toString();
bus.post(new PhotoService.AddPhotoRequest(photoURL, userEmail));
}
}
#Override
protected void onResume() {
super.onResume();
Firebase photosReference = new Firebase(Utils.FIRE_BASE_PHOTOS_REFERENCE + userEmail);
Query sortQuery = photosReference.orderByKey();
adapter = new FirebaseRecyclerAdapter<Photo, PhotoViewHolder>(Photo.class,
R.layout.list_individual_photo,
PhotoViewHolder.class,
sortQuery) {
#Override
protected void populateViewHolder(PhotoViewHolder photoViewHolder, Photo photo, int i) {
photoViewHolder.populate(PhotosActivity.this, photo);
}
};
GridLayoutManager layoutManager = new GridLayoutManager(getApplicationContext(), 4);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
}
#Override
protected void onPause() {
super.onPause();
adapter.cleanup();
}
#OnClick(R.id.activity_photos_fab)
public void setNewPhoto() {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, GALLERY_INTENT);
}
}
PhotoViewHolder
public class PhotoViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.list_individual_photo_imageView)
ImageView photoImage;
#BindView(R.id.list_individual_photo_progressBar)
ProgressBar photoProgressBar;
public PhotoViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
public void populate (Context context, Photo photo) {
itemView.setTag(photo);
Picasso.with(context).load(photo.getPhotoURl())
.fit()
.centerCrop()
.into(photoImage, new Callback() {
#Override
public void onSuccess() {
photoProgressBar.setVisibility(View.GONE);
}
#Override
public void onError() {
}
});
}
}
LivePhotoService
public class LivePhotoService extends BaseLiveService {
#Subscribe
public void getPhotos(final PhotoService.GetPhotoRequest request) {
final PhotoService.GetPhotoResponse response = new PhotoService.GetPhotoResponse();
response.valueEventListener = request.firebase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
response.photo = dataSnapshot.getValue(Photo.class);
if(response.photo != null) {
bus.post(response);
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
Toast.makeText(application.getApplicationContext(), firebaseError.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}
Photo Object
public class Photo {
private String photoID;
private String photoURl;
private HashMap<String, Object> photoDate;
private String ownerEmail;
public Photo(String photoID, String photoURl, HashMap photoDate, String ownerEmail) {
this.photoID = photoID;
this.photoURl = photoURl;
this.photoDate = photoDate;
this.ownerEmail = ownerEmail;
}
public String getPhotoID() {
return photoID;
}
public String getPhotoURl() {
return photoURl;
}
public HashMap getPhotoDate() {
return photoDate;
}
public String getOwnerEmail() {
return ownerEmail;
}
}
Consider using Firebase-UI Android library which gives you ability to load images from storage ref directly. In your case it would look something like this
I'm not sure if Picasso is supported but you can use Glide
For example:
mStorageRef = FirebaseStorage.getInstance().getReference();
Glide.with(this /* context */)
.using(new FirebaseImageLoader())
.load(mStorageRef + "/Photos/" + userId)
.error(R.drawable.default)
.into(imageView);

In Android what does it mean, "FirebaseApp was not initialized with a bucket name."?

I made this code to upload image to firebase with a child directory "photos".
I found this error:
java.lang.IllegalStateException: FirebaseApp was not initialized with a bucket name.
public class Firebase extends AppCompatActivity {
public TextView text1;
public Button button1;
public Button button2;
public StorageReference mStorage;
public ProgressDialog mProgress;
public static final int GALLERY_INTENT = 2;
public static final String FIREBASE_URL = "https://ivepos.firebaseio.com/weather";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(firebase);
mProgress = new ProgressDialog(this);
mStorage = FirebaseStorage.getInstance().getReference();
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK);
i.setType("image/*");
startActivityForResult(i, GALLERY_INTENT);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_INTENT && resultCode == RESULT_OK){
mProgress.setMessage("Uploading...");
mProgress.show();
Uri uri = data.getData();
StorageReference filepath = mStorage.child("photos").child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(Firebase.this, "Upload done", Toast.LENGTH_SHORT).show();
mProgress.dismiss();
}
});
}
}
}
It looks like your google-services.json may not contain the Firebase Storage URL. This is possible if you downloaded the file right after creating the project, since creating the bucket may take a few moments.
The solution is to download the latest google-services.json from the Firebase Cosnole, drop it into your project's app directory, and rebuild the app.
Please check your storage bucket setting.

Categories

Resources