Hi I want to add an image on firebase storage with android studio but firebase doesn't accept my upload. I changed the rule to allow the write and read and my match folder allows all path.Thus I am confused. Here is the part of my code who should put the image in my database.
If you know how to resolve this problem i would be glad to ear a solution
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == PICK_IMAGE){
image_uri = data.getData();
uploadPicture();
ProfileImage.setImageURI(image_uri);
}
}
private void uploadPicture() {
final ProgressDialog pd = new ProgressDialog(this);
pd.setTitle("Uploading Image...");
pd.show();
final String randomKey = UUID.randomUUID().toString();
StorageReference riversRef = storageReference.child(("images/" + randomKey + ".jpg"));
Toast.makeText(Create_Profile.this, "Upload success", Toast.LENGTH_SHORT).show();
riversRef.putFile(image_uri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
pd.dismiss();
name = riversRef.getDownloadUrl().toString();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot snapshot) {
double progressPercent = (100.00 * snapshot.getBytesTransferred() / snapshot.getTotalByteCount());
pd.setMessage("Percentage: " + (int) progressPercent + "%");
}
});
}
if you don't getting error compare with this simple code
thank you
firebase storage dependency
implementation 'com.google.firebase:firebase-storage:19.1.0'
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context=".MainActivity">
<!--Linear Layout with horizontal orientation
and other properties-->
<LinearLayout
android:id="#+id/layout_button"
android:orientation="horizontal"
android:layout_alignParentTop="true"
android:weightSum="2"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<!--Button for choosing image from gallery-->
<Button
android:id="#+id/btnChoose"
android:text="Choose"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content" />
<!--Button for uploading image-->
<Button
android:id="#+id/btnUpload"
android:text="Upload"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content" />
</LinearLayout>
<!--Image View for showing image choosen from gallery-->
<ImageView
android:id="#+id/imgView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
in your Activity
public class MainActivity extends AppCompatActivity {
private Button btnSelect, btnUpload;
private ImageView imageView;
private Uri filePath;
private final int PICK_IMAGE_REQUEST = 22;
FirebaseStorage storage;
StorageReference storageReference;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar;
actionBar = getSupportActionBar();
ColorDrawable colorDrawable
= new ColorDrawable(
Color.parseColor("#0F9D58"));
actionBar.setBackgroundDrawable(colorDrawable);
btnSelect = findViewById(R.id.btnChoose);
btnUpload = findViewById(R.id.btnUpload);
imageView = findViewById(R.id.imgView);
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
btnSelect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
SelectImage();
}
});
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
uploadImage();
}
});
}
private void SelectImage()
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(
intent,
"Select Image from here..."),
PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode,
int resultCode,
Intent data)
{
super.onActivityResult(requestCode,
resultCode,
data);
if (requestCode == PICK_IMAGE_REQUEST
&& resultCode == RESULT_OK
&& data != null
&& data.getData() != null) {
// Get the Uri of data
filePath = data.getData();
try {
Bitmap bitmap = MediaStore
.Images
.Media
.getBitmap(
getContentResolver(),
filePath);
imageView.setImageBitmap(bitmap);
}
catch (IOException e) {
e.printStackTrace();
}
}
}
private void uploadImage()
{
if (filePath != null) {
ProgressDialog progressDialog
= new ProgressDialog(this);
progressDialog.setTitle("Uploading...");
progressDialog.show();
StorageReference ref
= storageReference
.child(
"images/"
+ UUID.randomUUID().toString());
ref.putFile(filePath)
.addOnSuccessListener(
new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(
UploadTask.TaskSnapshot taskSnapshot)
{
progressDialog.dismiss();
Toast
.makeText(MainActivity.this,
"Image Uploaded!!",
Toast.LENGTH_SHORT)
.show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e)
{
progressDialog.dismiss();
Toast
.makeText(MainActivity.this,
"Failed " + e.getMessage(),
Toast.LENGTH_SHORT)
.show();
}
})
.addOnProgressListener(
new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(
UploadTask.TaskSnapshot taskSnapshot)
{
double progress
= (100.0
* taskSnapshot.getBytesTransferred()
/ taskSnapshot.getTotalByteCount());
progressDialog.setMessage(
"Uploaded "
+ (int)progress + "%");
}
});
}
}
}
I found a solution by modifying my firebase Rules to match with the bucket directly and not with the ref of my firebase storage
Related
I am recording a video with MediaStore and I am trying to limit the duration of the video to 30 seconds but I have a problem.
As soon as I click on the record icon the video starts at 30 and then it ends. Does anyone know the problem ?
activity_record_video:
<VideoView
android:id="#+id/video_view"
android:layout_width="300dp"
android:layout_height="300dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="recordVideo"
android:backgroundTint="#color/teal_200"
android:text="Record Video"
app:layout_constraintBottom_toTopOf="#+id/video_view"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
RecordVideo.java:
public class RecordVideo extends Activity {
VideoView videoView;
int REQUEST_CODE_VIDEO_CAPTURE = 2607;
private ListView filter_list;
protected GPUCameraRecorder GPUCameraRecorder;
Button selectVideo, uploadVideo;
ProgressDialog progressDialog;
public static Uri videoUri;
public static final int EXTRA_DURATION_LIMIT = 3;
PostActivity postActivity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_record_video);
videoView = findViewById(R.id.video_view);
MediaController mediaController = new MediaController(this);
mediaController.setAnchorView(videoView);
videoView.setMediaController(mediaController);
filter_list = findViewById(R.id.filter_list);
uploadVideo = findViewById(R.id.uploadVideo);
selectVideo = findViewById(R.id.selectVideo);
selectVideo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressDialog = new ProgressDialog(RecordVideo.this);
chooseVideo();
}
});
uploadVideo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Code for showing progressDialog while uploading
progressDialog = new ProgressDialog(RecordVideo.this);
uploadUserVideo(videoUri);
}
});
}
public void recordVideo(View view) {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
//if (intent.resolveActivity(getPackageManager()) != null ) {
intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT,30); //30Seconds
//intent.putExtra("android.intent.extra.durationLimit", 300000);
intent.putExtra("EXTRA_VIDEO_QUALITY", 0);
startActivityForResult(intent, REQUEST_CODE_VIDEO_CAPTURE);
//}
}
// choose a video from phone storage
private void chooseVideo() {
Intent intent = new Intent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
startActivityForResult(intent, 5);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == REQUEST_CODE_VIDEO_CAPTURE && resultCode == RESULT_OK && data.getData() != null) {
if (requestCode > EXTRA_DURATION_LIMIT) {
videoUri = data.getData();
videoView.setVideoURI(videoUri);
videoView.pause();
}
videoUri = data.getData();
videoView.setVideoURI(videoUri);
videoView.start();
} else if (requestCode == 5 && resultCode == RESULT_OK && data != null && data.getData() != null) {
videoUri = data.getData();
videoView.setVideoURI(videoUri);
videoView.start();
}
super.onActivityResult(requestCode, resultCode, data);
}
When submitting to Firebase, only photos are sent, without text and database as such.
I do according to the guide, but I don’t understand what is the reason.
The guide probably uses the deprecated getDownloadUrl() method, but the photo does not suffer from this. I do not understand the reason for this, since I am still new in this area, please help, I no longer understand what to do. To understand something, look at Maineenter image description here
public class MainActivity extends AppCompatActivity {
private static final int PICK_IMAGE_REQUEST = 1;
private Button mButtonChooseImage;
private Button mButtonUpload;
private TextView mTextViewShowUploads;
private EditText mEditTextFileName;
private ImageView mImageView;
private ProgressBar mProgressBar;
private Uri mImageUri;
private StorageReference mStorageRef;
private DatabaseReference mDatabaseRef;
private StorageTask mUploadTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButtonChooseImage = findViewById(R.id.button_choose_im);
mButtonUpload = findViewById(R.id.button_upload);
mTextViewShowUploads = findViewById(R.id.text_view_show);
mEditTextFileName = findViewById(R.id.edit_text_file_name);
mImageView = findViewById(R.id.image_view);
mProgressBar = findViewById(R.id.progress_bar);
mStorageRef = FirebaseStorage.getInstance().getReference("uploads");
mDatabaseRef = FirebaseDatabase.getInstance().getReference("uploads");
mButtonChooseImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFileChooser();
}
});
mButtonUpload.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 {
uploadFile();
}
}
});
mTextViewShowUploads.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
private void openFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& data != null && data.getData() != null) {
mImageUri = data.getData();
Picasso.get().load(mImageUri).into(mImageView);
}
}
private String getFileExtension(Uri uri) {
ContentResolver cR = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
}
private void uploadFile() {
if (mImageUri != null) {
StorageReference fileReference = mStorageRef.child(System.currentTimeMillis()
+ "." + getFileExtension(mImageUri));
mUploadTask = fileReference.putFile(mImageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
mProgressBar.setProgress(0);
}
}, 500);
Toast.makeText(MainActivity.this, "Upload successful", Toast.LENGTH_LONG).show();
Upload upload = new Upload(mEditTextFileName.getText().toString().trim(),
taskSnapshot.getMetadata().getReference().getDownloadUrl().toString());
String uploadId = mDatabaseRef.push().getKey();
mDatabaseRef.child(uploadId).setValue(upload);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
mProgressBar.setProgress((int) progress);
}
});
} else {
Toast.makeText(this, "No file selected", Toast.LENGTH_SHORT).show();
}
}
}
Класс Upload
public class Upload {
private String mName;
private String mImageUrl;
public Upload(){
}
public Upload(String name, String imageUrl) {
this.mName = name;
this.mImageUrl = imageUrl;
}
public String getName() {
return mName;
}
public void setName(String name) {
this.mName = mName;
}
public String getImageUrl() {
return mImageUrl;
}
public void setImageUrl(String imageUrl) {
this.mImageUrl = mImageUrl;
}
}
activity_main
<RelativeLayout 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"
android:padding="16dp"
tools:context=".MainActivity">
<Button
android:id="#+id/button_choose_im"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Choose" />
<EditText
android:id="#+id/edit_text_file_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_toEndOf="#+id/button_choose_im"
android:hint="Enter"
android:minHeight="48dp" />
<ImageView
android:id="#+id/image_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/progress_bar"
android:layout_below="#id/edit_text_file_name"
android:layout_marginTop="16dp" />
<ProgressBar
android:id="#+id/progress_bar"
style="#style/Widget.AppCompat.ProgressBar.Horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#id/button_upload"
android:layout_alignParentStart="true"
android:layout_marginBottom="16dp" />
<Button
android:id="#+id/button_upload"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="16dp"
android:text="Upload" />
<TextView
android:id="#+id/text_view_show"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/button_upload"
android:layout_alignBottom="#+id/button_upload"
android:layout_marginStart="25dp"
android:layout_toEndOf="#+id/button_upload"
android:gravity="center"
android:text="Show"
android:textSize="16sp" />
</RelativeLayout>
I am making an android application which is sort of a social media app
but when I am trying to put image from gallery or from camera for profile or cover this problem occurs.
I want the user to select a photo from his gallery or take a new picture using camera and then upload the image to Firebase Storage.
User does not have permission to access this object using Firebase Storage.
There are my permissions ..
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
My Java Code:
FirebaseAuth firebaseAuth;
FirebaseUser user;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
StorageReference storageReference;
String storagePath = "Uers_Profile_Cover_Imgs/";
ImageView avatartv, coverTv;
TextView nameTv, emailTv, phoneTv;
FloatingActionButton fab;
ProgressDialog pd;
private static final int CAMERA_REQUEST_CODE = 100;
private static final int STORAGE_REQUEST_CODE = 200;
private static final int IMAGE_PICK_GALLERY_CODE = 300;
private static final int IMAGE_PICK_CAMERA_CODE = 400;
String cameraPermissions[];
String storagePermission[];
Uri image_uri;
String profileOrCoverPhoto;
public ProfileFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_profile, container, false);
firebaseAuth = FirebaseAuth.getInstance();
user = firebaseAuth.getCurrentUser();
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference("Users");
storageReference = getInstance().getReference();
cameraPermissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
storagePermission = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
avatartv = view.findViewById(R.id.avatarTv);
coverTv = view.findViewById(R.id.coverTv);
nameTv = view.findViewById(R.id.name);
emailTv = view.findViewById(R.id.category);
phoneTv = view.findViewById(R.id.location);
fab = view.findViewById(R.id.fab);
pd = new ProgressDialog(getActivity());
Query query = databaseReference.orderByChild("email").equalTo(user.getEmail());
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String name = "" + ds.child("name").getValue();
String image = "" + ds.child("image").getValue();
String email = "" + ds.child("email").getValue();
String phone = "" + ds.child("phone").getValue();
String cover = "" + ds.child("cover").getValue();
nameTv.setText(name);
emailTv.setText(email);
phoneTv.setText(phone);
try {
Picasso.get().load(image).into(avatartv);
} catch (Exception e) {
Picasso.get().load(R.drawable.ic_add_a_photo_black_24dp).into(avatartv);
}
try {
Picasso.get().load(cover).into(coverTv);
} catch (Exception e) {
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showEditProfileDialog();
}
});
return view;
}
private boolean checkStoragePermission() {
boolean result = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
== (PackageManager.PERMISSION_GRANTED);
return result;
}
private void requestStoragePermission() {
requestPermissions(storagePermission, STORAGE_REQUEST_CODE);
}
private boolean checkCameraPermission() {
boolean result = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA)
== (PackageManager.PERMISSION_GRANTED);
boolean result1 = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
== (PackageManager.PERMISSION_GRANTED);
return result && result1;
}
private void requestCameraPermission() {
requestPermissions(cameraPermissions, CAMERA_REQUEST_CODE);
}
private void showEditProfileDialog() {
String options[] = {"Edit Profile Picture", "Edit Cover Photo", "Edit Name", "Edit Phone"};
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Choose Action");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
pd.setMessage("Updating Profile Picture");
profileOrCoverPhoto = "image";
showImagePicDialog();
} else if (which == 1) {
pd.setMessage("Updating Cover Picture");
profileOrCoverPhoto = "cover";
showImagePicDialog();
} else if (which == 2) {
pd.setMessage("Updating Name");
showNamePhoneUpdateDialog("name");
} else if (which == 3) {
pd.setMessage("Updating Phone");
showNamePhoneUpdateDialog("phone");
}
}
});
builder.create().show();
}
private void showNamePhoneUpdateDialog(String Key) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Updated " + Key);
LinearLayout linearLayout = new LinearLayout(getActivity());
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setPadding(10, 10, 10, 10);
EditText editText = new EditText(getActivity());
editText.setHint("Enter " + Key);
linearLayout.addView(editText);
builder.setView(linearLayout);
builder.setPositiveButton("Update", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String value = editText.getText().toString().trim();
if (!TextUtils.isEmpty(value)) {
pd.show();
HashMap<String, Object> result = new HashMap<>();
result.put(Key, value);
databaseReference.child(user.getUid()).updateChildren(result)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
pd.dismiss();
Toast.makeText(getActivity(), "Updated...", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
pd.dismiss();
Toast.makeText(getActivity(), "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(getActivity(), "Please enter " + Key, Toast.LENGTH_SHORT).show();
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.create().show();
}
private void showImagePicDialog() {
String options[] = {"Camera", "Gallery"};
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Pick Image From");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
if (!checkCameraPermission()) {
requestCameraPermission();
} else {
pickFromCamera();
}
} else if (which == 1) {
if (!checkStoragePermission()) {
requestStoragePermission();
} else {
pickFromGallery();
}
}
}
});
builder.create().show();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case CAMERA_REQUEST_CODE: {
if (grantResults.length > 0) {
boolean cameraAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean writeStorageAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if (cameraAccepted && writeStorageAccepted) {
pickFromCamera();
} else {
Toast.makeText(getActivity(), "Please Enable Camera & Storage Permission", Toast.LENGTH_SHORT).show();
}
}
}
break;
case STORAGE_REQUEST_CODE: {
if (grantResults.length > 0) {
boolean writeStorageAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if (writeStorageAccepted) {
pickFromGallery();
} else {
Toast.makeText(getActivity(), "Please Enable Storage Permission", Toast.LENGTH_SHORT).show();
}break;
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == IMAGE_PICK_GALLERY_CODE) {
image_uri = data.getData();
uploadProfileCoverPhoto(image_uri);
}
if (requestCode == IMAGE_PICK_CAMERA_CODE) {
uploadProfileCoverPhoto(image_uri);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void uploadProfileCoverPhoto(Uri uri) {
String filePathAndName = storagePath + "" + profileOrCoverPhoto + "_" + user.getUid();
StorageReference storageReference2nd = storageReference.child(filePathAndName);
storageReference2nd.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl();
while (!uriTask.isSuccessful()) ;
Uri downloadUri = uriTask.getResult();
if (uriTask.isSuccessful()) {
HashMap<String, Object> results = new HashMap<>();
results.put(profileOrCoverPhoto, downloadUri.toString());
databaseReference.child(user.getUid()).updateChildren(results)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
pd.dismiss();
Toast.makeText(getActivity(), "Image Updated ...", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
pd.dismiss();
Toast.makeText(getActivity(), "Error Updating Image ...", Toast.LENGTH_SHORT).show();
}
});
} else {
pd.dismiss();
Toast.makeText(getActivity(), "Some error occurred", Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
pd.dismiss();
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void pickFromCamera() {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "Temp Pic");
values.put(MediaStore.Images.Media.DESCRIPTION, "Temp Description");
image_uri = getActivity().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
startActivityForResult(cameraIntent, IMAGE_PICK_CAMERA_CODE);
}
private void pickFromGallery() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, IMAGE_PICK_GALLERY_CODE);
}
XML Codes:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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=".ProfileFragment">
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/coverTv"
android:layout_width="match_parent"
android:layout_height="180dp"
android:background="#FFA117">
</ImageView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="120dp"
android:layout_marginTop="90dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/avatarTv"
android:layout_width="120dp"
android:layout_height="120dp"
android:layout_marginStart="20dp"
android:layout_marginLeft="20dp"
android:background="#color/colorPrimaryDark"
android:scaleType="fitXY"
app:srcCompat="#drawable/face" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#B67310"
android:orientation="vertical">
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:textColor="#fff"
android:textSize="25sp" />
<TextView
android:id="#+id/category"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:textColor="#fff"
android:textSize="15dp" />
<TextView
android:id="#+id/location"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_marginLeft="5dp"
android:textColor="#fff"
android:textSize="15dp" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>
</ScrollView>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:layout_margin="10dp"
android:src="#drawable/editpen"
app:backgroundTint="#FFA117" />
</RelativeLayout>
FIrebase Security Rules:
service firebase.storage {
match /b/learno-fc8fc.appspot.com/o {
// Allow access by all users
allow read, write;
}
Screenshot of the issue.
Can you please cross check your bucket name if it correct.
After searching i found solution ..
My rules in Firebase was not right ..
we should make it like that ..
service firebase.storage
{ match /b/learno-fc8fc.appspot.com/o
{ match /{allPaths=**}
{ // Allow access by all users
allow read, write; }
So i have a SettingsActivity/layout with ImageViews, and can upload images from my phone gallery to these ImageViews which also then upload to firebase. There are currently 3 edit views and everything works fine until i wanted to try the following:
Now i wanted to have the ability to increase the amount of ImageViews upon certain criteria being met. For this i decided to move the ImageViews from this activity to a fragment activity and I created another activity with double the ImageViews. All the code for the upload/download of these ImageViews happen in the SettingsActivity. What's the best way to go about this? I've tried moving all the code over to the fragment activity but I end up with too much issues. What's the best way to go about using these imagesviews in the fragments(I have onclick listeners and other stuff that need the imageviews) in the SettingsActivity:
SettingsActivity.Java
public class SettingsActivity extends AppCompatActivity {
private ImageView mImage1, mImage2, mImage3;
private String image1Url, image2Url, image3Url;
public static FragmentManager fragmentManager;
final int MaxTags = 5;
private int MaxImages = 3;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
fragmentManager = getSupportFragmentManager();
if(findViewById(R.id.profileImageContainer) != null){
if(savedInstanceState!=null)
return;
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
SettingsDefault settingsDefault = new SettingsDefault();
fragmentTransaction.add(R.id.profileImageContainer, settingsDefault, null);
fragmentTransaction.commit();
}
getUserInfo();
mImage1 = findViewById(R.id.image1);
mImage2 = findViewById(R.id.image2);
mImage3 = findViewById(R.id.image3);
mUserDb = FirebaseDatabase.getInstance().getReference().child("Users").child(userId);
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);
}
});
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);
if(map.get("image1Url") != null){
image1Url = map.get("image1Url").toString();
switch(image1Url){
case "default":
mImage1.setImageResource(R.mipmap.ic_launcher);
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);
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);
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();
}
}
}
}
SettingsDefault.Java (Fragment)
public class SettingsDefault extends Fragment {
ImageView mImageView1;
ImageView mImageView2;
ImageView mImageView3;
public SettingsDefault() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_settings_default, container, false);
mImageView1 = view.findViewById(R.id.image1);
mImageView2 = view.findViewById(R.id.image2);
mImageView3 = view.findViewById(R.id.image3);
return view;
}
public ImageView getImageView1(){
return mImageView1;
}
public ImageView getImageView2(){
return mImageView2;
}
public ImageView getImageView3(){
return mImageView3;
}
Fragment's Layout(Moved the ImageViews from SettingsActivity to here)
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".Fragments.ProfileImages.SettingsUpgade1">
<!-- TODO: Update blank fragment layout -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginBottom="10sp"
android:weightSum="3">
<ImageView
android:layout_weight="0.5"
android:layout_width="0dp"
android:layout_height="100dp"
android:id="#+id/image1"
android:src="#mipmap/ic_launcher"
android:layout_margin="20sp"
android:scaleType="centerCrop"
/>
<ImageView
android:layout_weight="0.5"
android:layout_width="0dp"
android:layout_height="100dp"
android:id="#+id/image2"
android:src="#mipmap/ic_launcher"
android:layout_margin="20sp"
android:scaleType="centerCrop"
/>
<ImageView
android:layout_weight="0.5"
android:layout_width="0dp"
android:layout_height="100dp"
android:id="#+id/image3"
android:src="#mipmap/ic_launcher"
android:layout_margin="20sp"
android:scaleType="centerCrop"
/>
<ImageView
android:layout_weight="0.5"
android:layout_width="0dp"
android:layout_height="100dp"
android:id="#+id/image4"
android:src="#mipmap/ic_launcher"
android:layout_margin="20sp"
android:scaleType="centerCrop"
/>
<ImageView
android:layout_weight="0.5"
android:layout_width="0dp"
android:layout_height="100dp"
android:id="#+id/image5"
android:src="#mipmap/ic_launcher"
android:layout_margin="20sp"
android:scaleType="centerCrop"
/>
<ImageView
android:layout_weight="0.5"
android:layout_width="0dp"
android:layout_height="100dp"
android:id="#+id/image6"
android:src="#mipmap/ic_launcher"
android:layout_margin="20sp"
android:scaleType="centerCrop"
/>
</LinearLayout>
</FrameLayout>
It is easy!! Just use interface between your activity and fragment!! Like this link below!!
Communicating between a fragment and an activity - best practices
thanks for the info. Had a look at using interfaces which seems useful with simply tasks, but with so much going on in the activity with the imageviews it became really confusing and difficult to understand how to incorporate the interfaces to work with this app. So to simplify my life, I successfully managed to move all of the methods that utilize the ImageViews over to the fragment activity. Now i will do the same for the other fragment(only difference is it has double the imageviews), and will use a bolean or something to flick between the fragments. Not sure if this is the best way, specifically performance wise, but i ran the app and it seemed okay.
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();
}
}
}