Uploading images to different folder in firebase - java

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

Related

Unable to share images in android project chat applicaton

I tried to share the image in my chat application. But was not able to successfully share it. It's selecting the image from the gallery but not appearing in the Userchat screen and not getting upload in the firebase also.
I am not able to find the solution for it. I would very much appreciate if someone can help me out.
attachment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CharSequence options[] = new CharSequence[]
{
"Image", "Documents"
};
AlertDialog.Builder builder = new AlertDialog.Builder(UserChatActivity.this);
builder.setTitle("Select File");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if(i == 0)
{
checker = "image";
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent.createChooser(intent, "Select Image"), 438);
}
if (i == 1)
{
checker = "pdf";
}
}
});
builder.show();
}
});
StorageReference
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 438 && requestCode == RESULT_OK && data != null && data.getData() != null)
{
fileUri = data.getData();
if (!checker.equals("image"))
{
}
else if (checker.equals("image"))
{
StorageReference storageReference = FirebaseStorage.getInstance().getReference().child("Image Files").child(fAuth.getUid());;
}
else
{
Toast.makeText(this, "Nothing Selected", Toast.LENGTH_SHORT).show();
}
}
}
Store that image URL in your chat.
You can do something like this, I am giving you an example for firebase realtime database:
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 438 && resultCode == RESULT_OK && data != null && data.getData() != null) {
// you should show some progress dialog or progress bar here for better user experience.
progressDialog.show()
fileUri = data.getData();
if (checker.equals("image")) {
StorageReference storageReference = FirebaseStorage.getInstance().getReference().child("Image files");
final String messgSenderRef = "Messages/" + mAuth.getCurrentUser().getUid() + "/" + userId;
final String messgReceiverRf = "Messages/" + userId + "/" + mAuth.getCurrentUser().getUid();
DatabaseReference messageRef = databaseReference.child("Messages").child(mAuth.getCurrentUser().getUid()).child(userId).push();
final String messagePushId = messageRef.getKey();
final StorageReference filepath = storageReference.child(messagePushId + "." + "jpg");
filepath.putFile(fileUri).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot taskSnapshot) {
// you can show progress of upload here, let suppose you have a progressDialog then:-
double p = ((double) 100 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
progressDialog.setMessage((int) p + "%" + " Uploading....");
}
}).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 filepath.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
progressDialog.dismiss();
// Now you have Uri of your image
downloadUri = task.getResult().toString();
Map<String, Object> messageTextBody = new HashMap<>();
messageTextBody.put("message", downloadUri);
messageTextBody.put("name", fileUri.getLastPathSegment());
messageTextBody.put("type", fileStatus);
messageTextBody.put("from", mAuth.getCurrentUser().getUid());
messageTextBody.put("to", userId);
messageTextBody.put("messageId", messagePushId);
messageTextBody.put("time", saveCurrentTime);
messageTextBody.put("date", saveCurrentDate);
Map<String, Object> messageBodydetails = new HashMap<>();
// add message to sender and receiver's
messageBodydetails.put(messgSenderRef + "/" + messagePushId, messageTextBody);
messageBodydetails.put(messgReceiverRf + "/" + messagePushId, messageTextBody);
databaseReference.updateChildren(messageBodydetails).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
editText.setText("");
}
}
});
} else {
Toast.makeText(ChatActivity.this, "Error: " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}
});
} else {
}
}
}
Then in the chat you can check for the changes in the database in realtime and update your chat's recycler view in realtime. Just specify the chat message type to identify and display the view accordingly. If the chat type is text, show the text message. If the chat type is an image, load an image from the URL you have stored.

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.

Error when cropping an image and using getDownloadURL()

I am trying to utilise an image cropper (from ArthurHub GitHub) getting an error when typing getDownloadURL() i have put getStorage() in front using the getStorage() gets rid of the red line under getDownloadUrl however when I press crop I get the error message I have coded down the very end of this piece of code 'image cannot be cropped'. Does anyone know how to fix this
/*...*/ {
ProfileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, Gallery_Pick);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==Gallery_Pick && resultCode==RESULT_OK && data!= null)
{
Uri ImageUri = data.getData();
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1,1)
.start(this);
}
if(requestCode==CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE)
{
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if(requestCode == RESULT_OK)
{
loadingBar.setTitle("Profile Image");
loadingBar.setMessage("Please wait while we are updating your profile image");
loadingBar.show();
loadingBar.setCanceledOnTouchOutside(true);
Uri resultUri = result.getUri();
StorageReference filePath = UserProfileImageRef.child(currentUserID + ".jpg");
filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task)
{
if(task.isSuccessful())
{
Toast.makeText(SetupActivity.this, "Profile image stored successfully to firebase storage", Toast.LENGTH_SHORT).show();
final String downloadUrl = task.getResult().getStorage().getDownloadUrl().toString();
UsersRef.child("profileimage").setValue(downloadUrl)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task)
{
if(task.isSuccessful())
{
Intent selfIntent = new Intent(SetupActivity.this, SetupActivity.class);
startActivity(selfIntent);
Toast.makeText(SetupActivity.this, "Profile Image stored to firebase database successfully", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
else
{
String message = task.getException().getMessage();
Toast.makeText(SetupActivity.this, "Error occurred:" + message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
}
});
}
else
{
Toast.makeText(this, "Error Occurred: Image can't be cropped try again", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
}

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

Adding different two images to firebase realtime database

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

Categories

Resources