Adding different two images to firebase realtime database - java

I want to add two different photos to the database via Android app. however, when I select a photo for the first photo, it places the same photo for both and saves it in the same way. My code's down there. I've defined two separate imageview for two different photos, but it doesn't work. What can I do?
mDenemeImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, 1);
}
});
mDenemeImage2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK);
i.setType("image/*");
startActivityForResult(i, 1);
}
});
private void getUserInfo(){
mDriverDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists() && dataSnapshot.getChildrenCount()>0){
Map<String, Object> map = (Map<String, Object>) dataSnapshot.getValue();
if(map.get("profileDenemeUrl")!=null){
mprofileDenemeUrl = map.get("profileDenemeUrl").toString();
Glide.with(getApplication()).load(mprofileDenemeUrl).into(mDenemeImage);
}
if(map.get("profileDenemeUrl2")!=null){
mprofileDenemeUrl2 = map.get("profileDenemeUrl2").toString();
Glide.with(getApplication()).load(mprofileDenemeUrl2).into(mDenemeImage2);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void saveUserInformation() {
Map userInfo = new HashMap();
mDriverDatabase.updateChildren(userInfo);
if(resultUri != null) {
final StorageReference filePath = FirebaseStorage.getInstance().getReference().child("profile_arac").child(userID);
final StorageReference filePath2 = FirebaseStorage.getInstance().getReference().child("profile_arac2").child(userID);
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(getApplication().getContentResolver(), resultUri);
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 20, baos);
byte[] data = baos.toByteArray();
UploadTask uploadTask = filePath.putBytes(data);
UploadTask uploadTask2 = filePath2.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
finish();
return;
}
});
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Map newImage = new HashMap();
newImage.put("profileDenemeUrl", uri.toString());
mDriverDatabase.updateChildren(newImage);
finish();
return;
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
finish();
return;
}
});
}
}); uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
finish();
return;
}
});
uploadTask2.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
filePath2.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Map newImage2 = new HashMap();
newImage2.put("profileDenemeUrl2", uri.toString());
mDriverDatabase.updateChildren(newImage2);
finish();
return;
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
finish();
return;
}
});
}
}); uploadTask2.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
finish();
return;
}
});
}
else{
finish();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1 && resultCode == Activity.RESULT_OK){
final Uri imageUri = data.getData();
resultUri = imageUri;
mDenemeImage.setImageURI(resultUri);
mDenemeImage2.setImageURI(resultUri);
}
}

mDenemeImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, 1);
}
});
mDenemeImage2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK);
intent.setType("image/*"); startActivityForResult(i, 2);
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1 && resultCode == RESULT_OK){
Uri imageUri1 = data.getData();
resultUri1 = imageUri1;
mDenemeImage.setImageURI(resultUri1);
}
if (requestCode == 2 && resultCode == RESULT_OK)
{
Uri imageUri2 = data.getData();
resultUri2 = imageUri2;
mDenemeImage2.setImageURI(resultUri2);
}
}

Related

The image I downloaded does not appear on the screen in my app

here is my code:
public class Account_settings extends AppCompatActivity implements View.OnClickListener {
Button cprofile, cstatus, cinfo;
ImageView back;
CircleImageView profile_official;
TextView username, status, info, birth;
FirebaseDatabase database;
DatabaseReference myref;
String uid;
Dialog loading;
private StorageReference imagestorage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_account_settings);
cprofile = findViewById(R.id.change_pic);
cstatus = findViewById(R.id.change_status);
cinfo = findViewById(R.id.change_info);
back = findViewById(R.id.back58);
profile_official=findViewById(R.id.profile_image);
username = findViewById(R.id.display_name);
status = findViewById(R.id.status);
info = findViewById(R.id.about);
birth = findViewById(R.id.birth1);
uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
database = FirebaseDatabase.getInstance();
myref = database.getReference("User_details");
imagestorage = FirebaseStorage.getInstance().getReference();
loading = new Dialog(this);
loading.setContentView(R.layout.custom_dialog);
loading.setCancelable(true);
loading.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
loading.show();
myref.child(uid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
Userdetails userdetails = snapshot.getValue(Userdetails.class);
if (userdetails != null) {
birth.setText(userdetails.getBirth());
username.setText(userdetails.getName());
info.setText(userdetails.getInfo_about_me());
status.setText(userdetails.getStatus());
Picasso.with(Account_settings.this).load(userdetails.getProfile()).into(profile_official);
}
loading.dismiss();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
cprofile.setOnClickListener(this);
cstatus.setOnClickListener(this);
cinfo.setOnClickListener(this);
back.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v == back) {
startActivity(new Intent(getApplicationContext(), Main_page.class));
}
if (v == cstatus) {
String status1 = status.getText().toString();
Intent intent = new Intent(this, Status_Activity.class);
intent.putExtra("status_value", status1);
startActivity(intent);
finish();
}
if (v == cinfo) {
Intent intent1 = new Intent(this, my_info.class);
startActivity(intent1);
finish();
}
if (v == cprofile) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Selecting image"), 1);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK) {
Uri imageUri = data.getData();
CropImage.activity(imageUri).start(this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
loading.show();
Uri resultUri = result.getUri();
StorageReference file_path = imagestorage.child("profile_images").child(uid + ".jpg");
file_path.putFile(resultUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(#NonNull UploadTask.TaskSnapshot taskSnapshot) {
final Task<Uri> firebaseUri = taskSnapshot.getStorage().getDownloadUrl();
Toast.makeText(Account_settings.this, "Uploaded", Toast.LENGTH_SHORT).show();
firebaseUri.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String downloadUrl = uri.toString();
myref.child("profile").setValue(downloadUrl);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
loading.dismiss();
Toast.makeText(Account_settings.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
});}
else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
Toast.makeText(this, "Error! " + error, Toast.LENGTH_SHORT).show();
}
.
.
.
.
.
.
.
.
.
.
...........................................................................................................................................................................................................................................................................................................................
I have no idea why does it happen,so if someone know please help me.Hope you understand my code.
if you have a video about storage photos and show their on a screen please send me.

Uploading images to different folder in firebase

I'm creating an application were users get to upload two type of image which is their profile picture and their profile cover picture. But I'm having issues defining the different process without interference from each other as I'm unable to call two onActivityResult.
this is the code I'm currently using to upload profile picture to firebase storage
coverbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(galleryIntent, "SELECT IMAGE"), GALLERY_PICKER);
}
});
mImagebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(galleryIntent, "SELECT IMAGE"), GALLERY_PICK);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_PICK && resultCode == RESULT_OK) {
mPdialog = new ProgressDialog(SettingsActivity.this);
mPdialog.setTitle("Uploading");
mPdialog.setMessage("please wait....");
mPdialog.show();
Uri imageUri = data.getData();
CropImage.activity(imageUri)
.setAspectRatio(1, 1)
.setMinCropWindowSize(500,500)
.start(SettingsActivity.this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result.getUri();
File file_thumb = new File(resultUri.getPath());
String current_uid = mCurrentuser.getUid();
Bitmap thumb_bitmap = new Compressor(this)
.setMaxWidth(200)
.setMaxHeight(200)
.setQuality(75)
.compressToBitmap(file_thumb);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
thumb_bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
final byte[] thumb_byte = baos.toByteArray();
StorageReference filepath = mImageReference.child("profile_images").child(current_uid + ".jpg");
final StorageReference thumb_path = mImageReference.child("profile_images").child("thumbs").child(current_uid + ".jpg");
filepath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()){
final String download_url = task.getResult().getDownloadUrl().toString();
UploadTask uploadTask = thumb_path.putBytes(thumb_byte);
uploadTask.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> thumb_task) {
String thumb_downloadurl = thumb_task.getResult().getDownloadUrl().toString();
if (thumb_task.isSuccessful()){
Map update_hashmap = new HashMap();
update_hashmap.put("image",download_url);
update_hashmap.put("thumb_image", thumb_downloadurl);
mDatabase.updateChildren(update_hashmap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
mPdialog.dismiss();
Toast.makeText(SettingsActivity.this,"success",Toast.LENGTH_LONG).show();
}
}
});
}else {
Toast.makeText(SettingsActivity.this,"failed",Toast.LENGTH_LONG).show();
mPdialog.dismiss();
}
}
});
}else {
Toast.makeText(SettingsActivity.this,"failed",Toast.LENGTH_LONG).show();
mPdialog.dismiss();
}
}
});
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
Try this
Move startActivityForResult & intent outside
Set intent requestCode according to which button was clicked
Intent galleryIntent = new Intent();
coverbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
}
});
mImagebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
}
});
}
startActivityForResult(Intent.createChooser(galleryIntent, "SELECT IMAGE"), GALLERY_PICKER);

How do I store downloadUrl of multiple images to the Firebase Firestore ? Unable to create and store inside multiple fields inside Firestore document

Here's what I have been able to get so far. After selecting the images
selectImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mUploadTask != null && mUploadTask.isInProgress()){
Toast.makeText(MainActivity.this, "Upload In Progress", Toast.LENGTH_SHORT).show();
}
else {
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), RESULT_LOAD_IMAGE);
}
}
});
Inside the OnActivityResult, I am uploading my selected Images to the Firebase Storage and at the same time I want to store my download Urls of those multiple images to the Firebase Firestore
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
String fileName;
final String[] downloadUrl = new String[1];
if(requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK){
if(data.getClipData() != null){
int totalItemsSelected = data.getClipData().getItemCount();
for(int i =0;i<totalItemsSelected;i++){
Uri fileUri = data.getClipData().getItemAt(i).getUri();
fileName = getFileName(fileUri);
fileNameList.add(fileName);
fileDoneList.add("uploading");
uploadListAdapter.notifyDataSetChanged();
final StorageReference fileToUpload = storageReference.child("Images").child(fileName);
final int finalI = i;
final int totalCount = totalItemsSelected;
mUploadTask = fileToUpload.putFile(fileUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
fileToUpload.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String url = String.valueOf(uri);
storeLink(url,totalCount);//Method To Store the Url
}
});
// Toast.makeText(add_for_sale.this, "Uploading works", Toast.LENGTH_SHORT).show();
fileDoneList.remove(finalI);
fileDoneList.add(finalI,"done");
uploadListAdapter.notifyDataSetChanged();
}
});
// ImageUploadInfo imageUploadInfo = new ImageUploadInfo(downloadUrl[0],fileName);
}
Toast.makeText(this, "Upload in Progress", Toast.LENGTH_SHORT).show();
}
else if(data.getData() != null){
Toast.makeText(this, "Selected Single", Toast.LENGTH_SHORT).show();
}
}
}
In the method storeLink(url,totalCount), I am creating a map object to create field "imageUrl" inside the document,where "29t0Boxm0fa8UNkomuo5xPLwkx13" is a user id.
private void storeLink(final String url,final int totalCount) {
FirebaseFirestore storeUrl = FirebaseFirestore.getInstance();
Toast.makeText(MainActivity.this, url, Toast.LENGTH_LONG).show();
for (int i=0;i<totalCount;i++) {
final Map<String, Object> image = new HashMap<>();
image.put("imageUrl"+i, url);
DocumentReference documentReference = storeUrl.collection("users").document("29t0Boxm0fa8UNkomuo5xPLwkx13");
documentReference.set(image).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "" +
"OnSuccess : Image Link Saved ");
// startActivity(new Intent(Register.this,LoginActivity.class));
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG, "OnFailure : " + e.toString());
}
});
}
}
Storage Rules
rules_version = '2'
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if true;
}
}
Firestore Rules
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if true;
}
}
}
Make sure you have made final to Map<String,Object> user = new HashMap<>();
And add user.put("key","value") inside the loop.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
final DocumentReference documentReference = db.collection("users").document("multi_image");
final Map<String, Object> user = new HashMap<>();
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK) {
if (data.getClipData() != null) {
final int totalItemsSelected = data.getClipData().getItemCount();
for (int i = 0; i < totalItemsSelected; i++) {
Uri fileUri = data.getClipData().getItemAt(i).getUri();
final int x = i;
final StorageReference fileToUpload = mStorageRef.child("Images").child("" + x);
fileToUpload.putFile(fileUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(final UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> DownloadURL = taskSnapshot.getStorage().getDownloadUrl();
DownloadURL.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
user.put("image_" + x, uri.toString());
Log.v("users", "" + user);
documentReference.update(user)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.v("task", "Success");
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.v("failed", "" + e);
}
});
}
});
}
});
}
Toast.makeText(this, "Upload in Progress", Toast.LENGTH_SHORT).show();
} else if (data.getData() != null) {
Toast.makeText(this, "Selected Single", Toast.LENGTH_SHORT).show();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
Firebase Storage https://i.stack.imgur.com/HeYvh.png
Firebase Database https://i.stack.imgur.com/3t2aN.png
Here's what worked out for me finally :
Create an ArrayList variable globally
ArrayList<String> imageList;
Then initialize this ArrayList inside the
onActivityResult as imageList = new ArrayList<>(totalItemsSelected); as mentioned inside the code below
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
String fileName;
if(requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK){
if(data.getClipData() != null){
progressBar.setVisibility(View.VISIBLE);
final int totalItemsSelected = data.getClipData().getItemCount();
count = totalItemsSelected;
imageList = new ArrayList<>(totalItemsSelected);
StorageReference ImageFolder = FirebaseStorage.getInstance().getReference().child("ImageFolder");
for(int i =0;i<totalItemsSelected;i++){
Uri fileUri = data.getClipData().getItemAt(i).getUri();
fileName = getFileName(fileUri);
fileNameList.add(fileName);
fileDoneList.add("uploading");
uploadListAdapter.notifyDataSetChanged();
final StorageReference fileToUpload = ImageFolder.child(fileName);
final int finalI = i;
mUploadTask = fileToUpload.putFile(fileUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressBar.setVisibility(View.INVISIBLE);
fileToUpload.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String url = String.valueOf(uri);
imageList.add(url);
// Toast.makeText(add_for_sale.this, imageList.get(finalI), Toast.LENGTH_SHORT).show();
Log.i(TAG,"Added To List");
}
});
fileDoneList.remove(finalI);
fileDoneList.add(finalI,"done");
uploadListAdapter.notifyDataSetChanged();
}
});
}
Toast.makeText(this, "Upload in Progress", Toast.LENGTH_SHORT).show();
}
else if(data.getData() != null){
Toast.makeText(this, "Select Two or More Images", Toast.LENGTH_SHORT).show();
}
}
}
Now to Save the Url Links to the Firebase Firestore Add the links to the ArrayList as imageList.add(url;)
and upload this list imageList to the FireStore as
Map<String,Object> imageUrl = new HashMap<>();
imageUrl.put("ImageUrl", imageList);
String userId;
userId = firebaseUser.getUid();
firebaseFirestore.collection("ImageDetails").document(userId)
.set(imageUrl,SetOptions.merge());
This will create an array of ImageUrl inside your firestore document

How to create a tinder/bumble like "Edit Profile Images" page in android studio with firebase?

I'm trying to create an app where you can add profile images from your mobile device, then save it to firebase, and retrieve it from firebase as well, as efficiently as possible.
A few questions:
1: How do these big dating apps such as bumble/tinder create the edit profile image UI where you upload your profile images and rearrange them? Do they place cardviews into a gridview, seeing as how these cards have the ability to be dragged to rearrange the position? Also they normally have a small x button attached to delete the image, so it would be a cardview, right?
I'm currently using ImageViews for testing and wanted to incorporate the ability to add more, but my code is horrible and it overwrites the images in the firebase DB if I return to the page and add a new image.
LinearLayout 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=".SettingsActivity"
android:orientation="vertical">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/back"
android:text="Back"
android:layout_marginBottom="20sp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20sp"
android:orientation="horizontal">
<ImageView
android:layout_width="100sp"
android:layout_height="100sp"
android:id="#+id/image1"
android:src="#mipmap/ic_launcher"
android:layout_margin="20sp"
android:layout_gravity="start"
/>
<ImageView
android:layout_width="100sp"
android:layout_height="100sp"
android:id="#+id/image2"
android:src="#mipmap/ic_launcher"
android:layout_margin="20sp"
android:layout_gravity="center_horizontal"
/>
<ImageView
android:layout_width="100sp"
android:layout_height="100sp"
android:id="#+id/image3"
android:src="#mipmap/ic_launcher"
android:layout_margin="20sp"
android:layout_gravity="end"
/>
</LinearLayout>
public class SettingsActivity extends AppCompatActivity {
private Button mBack;
private ImageView mImage1, mImage2, mImage3;
private FirebaseAuth mAuth;
private DatabaseReference mUserDb, mTagsDb;
private String userId, phone, image1Url, image2Url, image3Url, userSex;
private Uri resultUri1, resultUri2, resultUri3;
private ArrayList<Uri> resultUri = new ArrayList<Uri>();
private ArrayList<ImageView> imageViewsList = new ArrayList<ImageView>();
final int MaxTags = 5;
final int MaxImages = 3;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
mImage1 = findViewById(R.id.image1);
mImage2 = findViewById(R.id.image2);
mImage3 = findViewById(R.id.image3);
mBack = findViewById(R.id.back);
mAuth = FirebaseAuth.getInstance();
userId = mAuth.getCurrentUser().getUid();
mUserDb = FirebaseDatabase.getInstance().getReference().child("Users").child(userId);
getUserInfo();
mImage1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, 1);
}
});
mImage2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, 2);
}
});
mImage3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, 3);
}
});
mBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveUserInformation();
finish();
}
});
private void saveUserInformation() {
phone = mPhoneField.getText().toString();
Map userInfo = new HashMap();
userInfo.put("phone", phone);
mUserDb.updateChildren(userInfo);
if(resultUri != null){
for(int i = 0; i < resultUri.size(); i++)
{ String num = String.valueOf(i);
final StorageReference filePath = FirebaseStorage.getInstance().getReference().child("profileImages").child(userId).child(num);
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(getApplication().getContentResolver(), resultUri.get(i));
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 20, baos);
byte[] data = baos.toByteArray();
UploadTask uploadTask = filePath.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
finish();
}
});
final int finalI = i+1;
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Map newImage = new HashMap();
newImage.put("image"+ finalI +"Url", uri.toString());
mUserDb.updateChildren(newImage);
finish();
return;
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
finish();
return;
}
});
}
});
}
}else{
finish();
}
}
ArrayAdapter<String> values;
private void getUserInfo() {
mUserDb.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists() && dataSnapshot.getChildrenCount()>0){
Map<String, Object> map = (Map<String, Object>) dataSnapshot.getValue();
if(map.get("phone") != null){
phone = map.get("phone").toString();
mPhoneField.setText(phone);
}
if(map.get("sex") != null){
userSex = map.get("sex").toString();
}
Glide.clear(mImage1);
Glide.clear(mImage2);
Glide.clear(mImage3);
if(MaxImages == 3) {
imageViewsList.add(mImage1);
imageViewsList.add(mImage2);
imageViewsList.add(mImage3);
}
for(int i = 0; i < MaxImages; i ++)
{
int b = i+1;
if(map.get("image"+b+"Url") != null){
String url = map.get("image"+b+"Url").toString();
switch(url){
case "default":
imageViewsList.get(i).setImageResource(R.mipmap.ic_launcher);
//Glide.with(getApplication()).load(R.mipmap.ic_launcher).into(mImage1);
break;
default:
Glide.with(getApplication()).load(url).into(imageViewsList.get(i));
break;
}
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1 && resultCode == Activity.RESULT_OK){
final Uri imageUri = data.getData();
resultUri1 = imageUri;
mImage1.setImageURI(resultUri1);
resultUri.add(resultUri1);
}
if(requestCode == 2 && resultCode == Activity.RESULT_OK){
final Uri imageUri = data.getData();
resultUri2 = imageUri;
mImage2.setImageURI(resultUri2);
resultUri.add(resultUri2);
}
if(requestCode == 3 && resultCode == Activity.RESULT_OK){
final Uri imageUri = data.getData();
resultUri3 = imageUri;
mImage3.setImageURI(resultUri3);
resultUri.add(resultUri3);
}
}
}
Currently I can upload images to the imageviews fine and save them to firebase, but for example if I upload 2 images, then save and return to upload a 3rd image, that image overwrites image 1. Does anyone have a simpler way of doing this?
So after looking at the other apps at my disposal again, I've realized that it seems they upload the image to firebase after the onResultActivity of the image selection of your phone gallery. So i've simplified my code to do the same and it works much better. Code now works but I just need to resize the images to fit the imageviews properly, other than that no complaints.
If you have a better and more efficient way of writing this code, please comment, efficiency is key and I would appreciate your input.
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
mImage1 = findViewById(R.id.image1);
mImage2 = findViewById(R.id.image2);
mImage3 = findViewById(R.id.image3);
mAuth = FirebaseAuth.getInstance();
userId = mAuth.getCurrentUser().getUid();
mUserDb = FirebaseDatabase.getInstance().getReference().child("Users").child(userId);
getUserInfo();
getUserTags();
mImage1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, 1);
}
});
mImage2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, 2);
}
});
mImage3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, 3);
}
});
private void getUserInfo() {
mUserDb.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists() && dataSnapshot.getChildrenCount()>0){
Glide.clear(mImage1);
if(map.get("image1Url") != null){
image1Url = map.get("image1Url").toString();
switch(image1Url){
case "default":
mImage1.setImageResource(R.mipmap.ic_launcher);
//Glide.with(getApplication()).load(R.mipmap.ic_launcher).into(mImage1);
break;
default:
Glide.with(getApplication()).load(image1Url).into(mImage1);
break;
}
}
if(map.get("image2Url") != null){
image2Url = map.get("image2Url").toString();
switch(image2Url){
case "default":
mImage2.setImageResource(R.mipmap.ic_launcher);
//Glide.with(getApplication()).load(R.mipmap.ic_launcher).into(mImage1);
break;
default:
Glide.with(getApplication()).load(image2Url).into(mImage2);
break;
}
}
if(map.get("image3Url") != null){
image3Url = map.get("image3Url").toString();
switch(image3Url){
case "default":
mImage3.setImageResource(R.mipmap.ic_launcher);
//Glide.with(getApplication()).load(R.mipmap.ic_launcher).into(mImage1);
break;
default:
Glide.with(getApplication()).load(image3Url).into(mImage3);
break;
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1 && resultCode == Activity.RESULT_OK){
final Uri imageUri = data.getData();
final Uri resultUri = imageUri;
if(resultUri != null){
final StorageReference filePath = FirebaseStorage.getInstance().getReference().child("profileImages").child(userId).child("image1");
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(getApplication().getContentResolver(), resultUri);
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 20, baos);
byte[] databytes = baos.toByteArray();
UploadTask uploadTask = filePath.putBytes(databytes);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast toast = Toast.makeText(SettingsActivity.this, "Upload Failed! Please try again", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
});
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Map newImage = new HashMap();
newImage.put("image1Url", uri.toString());
mUserDb.updateChildren(newImage);
mImage1.setImageURI(resultUri);
Toast toast = Toast.makeText(SettingsActivity.this, "Upload Successful!", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Toast toast = Toast.makeText(SettingsActivity.this, "Upload Failed! Please try again", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
});
}
});
}else{
finish();
}
}
if(requestCode == 2 && resultCode == Activity.RESULT_OK){
final Uri imageUri = data.getData();
final Uri resultUri = imageUri;
if(resultUri != null){
final StorageReference filePath = FirebaseStorage.getInstance().getReference().child("profileImages").child(userId).child("image2");
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(getApplication().getContentResolver(), resultUri);
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 20, baos);
byte[] databytes = baos.toByteArray();
UploadTask uploadTask = filePath.putBytes(databytes);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast toast = Toast.makeText(SettingsActivity.this, "Upload Failed! Please try again", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
});
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Map newImage = new HashMap();
newImage.put("image2Url", uri.toString());
mUserDb.updateChildren(newImage);
mImage2.setImageURI(resultUri);
Toast toast = Toast.makeText(SettingsActivity.this, "Upload Successful!", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Toast toast = Toast.makeText(SettingsActivity.this, "Upload Failed! Please try again", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
});
}
});
}else{
finish();
}
}
if(requestCode == 3 && resultCode == Activity.RESULT_OK){
final Uri imageUri = data.getData();
final Uri resultUri = imageUri;
if(resultUri != null){
final StorageReference filePath = FirebaseStorage.getInstance().getReference().child("profileImages").child(userId).child("image3");
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(getApplication().getContentResolver(), resultUri);
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 20, baos);
byte[] databytes = baos.toByteArray();
UploadTask uploadTask = filePath.putBytes(databytes);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast toast = Toast.makeText(SettingsActivity.this, "Upload Failed! Please try again", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
});
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Map newImage = new HashMap();
newImage.put("image3Url", uri.toString());
mUserDb.updateChildren(newImage);
mImage3.setImageURI(resultUri);
Toast toast = Toast.makeText(SettingsActivity.this, "Upload Successful!", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Toast toast = Toast.makeText(SettingsActivity.this, "Upload Failed! Please try again", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
});
}
});
}else{
finish();
}
}
}

Uploading image to firebase

I have created a profile for my app. I want the user to be able to select an image from stored images on phone which then also updates profile pic into firebase. I am able to change to the profile pic and place into imageView, however when i close profile and then return the image has not saved onto the profile but uploaded to firebase.
Code for updating profile pic:
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);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CHOOSE_IMAGE && resultCode == RESULT_OK && data != null && data.getData() != null) {
uriProfileImage = data.getData();
//try {
//Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uriProfileImage);
//imageView.setImageBitmap(bitmap);
Glide.with(this)
.load(uriProfileImage)
.apply(new RequestOptions()
.placeholder(R.drawable.icon_camera))
.into(imageView);
uploadImageToFirebaseStorage();
//} catch (IOException e) {
// e.printStackTrace();
}
}
private void uploadImageToFirebaseStorage() {
StorageReference profileImageRef =
FirebaseStorage.getInstance().getReference("profilepics/" + System.currentTimeMillis() + ".jpg");
if (uriProfileImage != null) {
progressBar.setVisibility(View.VISIBLE);
profileImageRef.putFile(uriProfileImage)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressBar.setVisibility(View.GONE);
profileImageUrl = taskSnapshot.getMetadata().getReference().getDownloadUrl().toString();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressBar.setVisibility(View.GONE);
Toast.makeText(ProfileActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
Upload user information:
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showImageChooser();
}
});
loadUserInformation();
findViewById(R.id.buttonSave).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
saveUserInformation();
}
});
Load user information
private void loadUserInformation() {
final FirebaseUser user = mAuth.getCurrentUser();
if (user != null) {
if (user.getPhotoUrl() != null) {
Glide.with(this)
.load(user.getPhotoUrl().toString())
.into(imageView);
}
if (user.getDisplayName() != null) {
editText.setText(user.getDisplayName());
}
if (user.isEmailVerified()) {
textView.setText("Email Verified");
} else {
textView.setText("Email Not Verified (Click to Verify)");
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
user.sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(ProfileActivity.this, "Verification Email Sent", Toast.LENGTH_SHORT).show();
}
});
}
});
}
}
}

Categories

Resources