Rotate image from uri address, using Picasso - android

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

Related

Not able to upload image on real time database, working in fragments in android studio

public class statusFragment extends Fragment {
//StatusfragmentBinding binding;
TopStatusAdapter statusAdapter;
ArrayList<UserStatus> userStatuses;
///we are creating customize fragment where first layut is created then class creat to attach then to the activities by creating classes while in simple activities creation both layout and activity is created at same time
ImageButton camerastatus;
RecyclerView statusList;
ProgressDialog dialog;
// for uploading
FirebaseDatabase database;
private FirebaseStorage firebaseStorage;
private StorageReference storageReference;
private FirebaseAuth firebaseAuth;
private static int PICK_IMAGE = 123;
private Uri imagepath;
private String ImageUriAcessToken;
userprofile user; //user obj
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.statusfragment,container,false);
dialog = new ProgressDialog(getContext());
dialog.setMessage("Uploading Image...");
dialog.setCancelable(false);
//like specific
database= FirebaseDatabase.getInstance();
userStatuses= new ArrayList<>();//need to remove from TopstatusAdapter
statusList = view.findViewById(R.id.statusList);
camerastatus= view.findViewById(R.id.camerastatus);
statusAdapter= new TopStatusAdapter(getContext(),userStatuses);
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
layoutManager.setOrientation(RecyclerView.VERTICAL);
statusList.setLayoutManager(layoutManager);
statusList.setAdapter(statusAdapter);
StorageReference reference = storage.getReference().child("SImages").child(firebaseAuth.getUid()).child("Status Pic");
//before like video
database.getReference().child("status").child(firebaseAuth.getUid())
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
user = snapshot.getValue(userprofile.class);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
camerastatus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//before:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, 75);
}
});
return view;
}
#Override
public void onActivityResult(int requestCode, int resultCode,#Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(data != null) {
if(data.getData() != null) {
//firebase to upload data
FirebaseStorage storage = FirebaseStorage.getInstance();
Date date = new Date();
StorageReference reference = storage.getReference().child("SImages").child(firebaseAuth.getUid()).child("Status Pic");
reference.putFile(data.getData()).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful()) {
reference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
//dialog.dismiss();
UserStatus userStatus = new UserStatus();
userStatus.setName(user.getUsername());
userStatus.setLastUpdated(date.getTime());
HashMap<String,Object> obj=new HashMap<>();
obj.put("name", userStatus.getName());
obj.put("lastUpdated", userStatus.getLastUpdated());
String imageUrl = uri.toString();
Status status = new Status(imageUrl, userStatus.getLastUpdated());
database.getReference().child("status").child("stories").updateChildren(obj);
database.getReference().child("stories").child("status")
.child("stories")
.push()
.setValue(status);
}
});
}
}
});
}
}
}
}[image1[\]\[1\]][1]
[1]: https://i.stack.imgur.com/6eCEz.jpg
this is a status fragment , i want to make a module like WhatsApp status, here in the code above i am uploading the image on firebase storage that is working fine , image is being uploaded but in real-time database the image is not being uploaded.
I have attached the screenshot of my storage where data is being uploaded and also the screenshot of real time database where image is not being uploaded .

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.

Retrieve stored image from Firebase Storage

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

Displaying decoded images from firebase on Recyclerview in Android

I have a fragment where a user takes a picture with camera and then its uploaded to Firebase. I encode the image into a string with no issues. I see the converted image string in my Firebase console. The issue I have is when decoding the image string from Firebase to display as an Image in a recyclerview nothing displays.
If you can help me understand what my issue is and how to correct it I would really appreciated it. I have been trying to figure this out for 3 days by reading other Stackexchange post and I cant figure out where my issue is.
Thanks.
My Fragment:
public class AddImageFragment extends Fragment {
public static final int REQUEST_IMAGE_CAPTURE = 111;
private EditText progressDetail;
private Button cameraButton;
private Button saveButton;
private Button cancelButton;
private ImageView capturedImage;
private DatabaseReference mDatabaseReference;
public ImageProgress mImageProgress;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.add_image_fragment, container, false);
progressDetail = (TextInputEditText) v.findViewById(R.id.progressStatusEditText);
capturedImage = (ImageView) v.findViewById(R.id.capturedImageView);
cameraButton = (Button) v.findViewById(R.id.takePictureButton);
saveButton = (Button) v.findViewById(R.id.saveButton);
cameraButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openCamera();
}
});
//initialize firebase database
mDatabaseReference = FirebaseDatabase.getInstance().getReference();
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//get current user
FirebaseUser user =FirebaseAuth.getInstance().getCurrentUser();
String uid = user.getUid();
try {
Bitmap image = decodeFromFirebaseBase64(mImageProgress.getImageUrl());
capturedImage.setImageBitmap(image);
}catch (IOException e){
e.printStackTrace();
}
myNewImage(uid, progressDetail.getText().toString(),capturedImage.toString());
getActivity().onBackPressed();
}
});
return v;
}
private void myNewImage(String uid, String progressDetails, String imageUrl) {
ImageProgress imageProgress = new ImageProgress(progressDetails, imageUrl);
mDatabaseReference.child("Progress").child(uid).child("Images").push().setValue(imageProgress);
}
private void openCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == getActivity().RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
capturedImage.setImageBitmap(imageBitmap);
encodeBitmapAndSaveToFirebase(imageBitmap);
}
}
public void encodeBitmapAndSaveToFirebase(Bitmap bitmap) {
//current user
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String uid = user.getUid();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
String imageEncoded = Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT);
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
reference.child("Progress").child(uid).child("imageUrl").push().setValue(imageEncoded);
}
public static Bitmap decodeFromFirebaseBase64(String image) throws IOException {
byte[] decodeByteArray = android.util.Base64.decode(image, Base64.DEFAULT);
return BitmapFactory.decodeByteArray(decodeByteArray, 0, decodeByteArray.length);
}
}
Activity
public class WeightProgressActivity extends BaseActivity {
public ImageProgress mImageProgress;
private FloatingActionButton fab;
ScaleAnimation shrinkAnim;
private RecyclerView mRecyclerView;
private LinearLayoutManager mLayoutManager;
public ImageView capturedImage;
//firebase database reference
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference mDatabaseReference = database.getReference();
//get current user
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String uid = user.getUid();
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.weight_progress);
setNavDrawer(new MainNavDrawer(this));
//initialize recyclerview
mRecyclerView = (RecyclerView)findViewById(R.id.recyclerView);
shrinkAnim = new ScaleAnimation(1.15f, 0f, 1.15f, 0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
if(mRecyclerView != null){
mRecyclerView.setHasFixedSize(true);
}
//using linearlayout manager in recyclerview
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
//firebaserecycleradapter (firebase ui)
FirebaseRecyclerAdapter<ImageProgress, ImageViewHolder> adapter = new FirebaseRecyclerAdapter<ImageProgress, ImageViewHolder>(
ImageProgress.class, R.layout.weight_progress_list, ImageViewHolder.class, mDatabaseReference.child("images").child(uid).
child("Progress Images").getRef()
) {
#Override
protected void populateViewHolder(ImageViewHolder viewHolder, ImageProgress model, int position) {
viewHolder.progressDetail.setText(model.getProgressDetail());
try {
Bitmap image = decodeFromFirebaseBase64(mImageProgress.getImageUrl());
viewHolder.capturedImage.setImageBitmap(image);
}catch (IOException e){
e.printStackTrace();
}
}
};
mRecyclerView.setAdapter(adapter);
fab = (FloatingActionButton)findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container,
new AddImageFragment()).addToBackStack(null).commit();
//animation to make actionbar disappear
shrinkAnim.setDuration(400);
fab.setAnimation(shrinkAnim);
shrinkAnim.start();
shrinkAnim.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
//changing floating actionbar visibility to gone on animation end
fab.setVisibility(View.GONE);
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
}
});
}
//on back press code
#Override
public void onBackPressed() {
super.onBackPressed();
if (fab.getVisibility() == View.GONE)
fab.setVisibility(View.VISIBLE);
}
//weightViewHolder method
public static class ImageViewHolder extends RecyclerView.ViewHolder{
EditText progressDetail;
ImageView capturedImage;
public ImageViewHolder(View v){
super(v);
progressDetail = (EditText) v.findViewById(R.id.progressStatusEditText);
capturedImage = (ImageView) v.findViewById(R.id.capturedImageView);
}
}
public static Bitmap decodeFromFirebaseBase64(String image) throws IOException {
byte[] decodeByteArray = android.util.Base64.decode(image, Base64.DEFAULT);
return BitmapFactory.decodeByteArray(decodeByteArray, 0, decodeByteArray.length);
}
}

Categories

Resources