How to use ImageViews from fragment in my mainactivity - java

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.

Related

Upload Image on Firebase Storage

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

User does not have permission to access this object . with storage firebase

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

How to retrieve saved image from database?

I have created a profile. Now, I can save a profile pic but I don't know how to retrieve an image. I have tried but didn't get any solution?
I have made some changes now after uploading an image when I visit profile again the image view gets invisible. please review my code, where did I have mistake?
I have tried to get image from shared preferences still doesn't work properly...
Here is my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my__profile);
edt_btn = findViewById(R.id.edt_btn);
user_pname = findViewById(R.id.user_profile_name);
ButterKnife.bind(this);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//
loadProfileDefault();
ImagePicker.clearCache(this);
sharedPreferenceClass = new SharedPreferenceClass(this);
sharedPreferenceClass = new SharedPreferenceClass(My_Profile.this);
user_id = sharedPreferenceClass.getValue_string("user_id");
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
edt_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(My_Profile.this,Editprofile.class);
startActivity(intent);
}
});
sharedPreferences=getApplicationContext().getSharedPreferences("userinfo", Context.MODE_PRIVATE);
final String name=sharedPreferenceClass.getName();
user_pname.setText(name);
String profileImage = sharedPreferences.getString("profile_image", "");
bitmap = decodeToBase64(profileImage);
imgProfile.setImageBitmap(bitmap);
}
private void loadProfile(String url) {
Log.d(TAG, "Image cache path: " + url);
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(url));
imgProfile.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
Glide.with(this).load(url)
.into(imgProfile);
imgProfile.setColorFilter(ContextCompat.getColor(this, android.R.color.transparent));
upload();
}
private void upload() {
sharedPreferences = getApplicationContext().getSharedPreferences("userinfo", Context.MODE_PRIVATE);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, baos);
final byte[][] imageBytes = {baos.toByteArray()};
final String imgProfile1 = Base64.encodeToString(imageBytes[0], Base64.DEFAULT);
Log.d("converted to string",imgProfile1);
StringRequest stringRequest = new StringRequest(Request.Method.POST, "https://www.khaokamao.in/ndokan/api/profile_pic.php", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String status = jsonObject.getString("status");
String message = jsonObject.getString("msg");
Log.i("Message",message);
Toast.makeText(getApplicationContext(), status + message + " ", Toast.LENGTH_LONG).show();
if (status.equalsIgnoreCase("Success")) {
Log.i("response",response);
JSONObject jsonObject1 = jsonObject.getJSONObject("data");
imageBytes[0] = Base64.decode(imgProfile1, Base64.DEFAULT);
Bitmap decodedImage = BitmapFactory.decodeByteArray(imageBytes[0], 0, imageBytes[0].length);
imgProfile.setImageBitmap(decodedImage);
SharedPreferences sharedPreferences= PreferenceManager.getDefaultSharedPreferences(My_Profile.this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("profile_image",imgProfile1);
editor.commit();
Log.d("put_img","put_image");
editor.apply();
} else {
Toast.makeText(My_Profile.this, "Please Try Again..", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e1) {
e1.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("user_id",user_id);
params.put(KEY_PROFILE,imgProfile1);
return params;
}
};
stringRequest.setShouldCache(false);
int socketTimeout = 60000; // 30 seconds. You can change it
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
RequestQueue requestQueue = Volley.newRequestQueue(My_Profile.this);
requestQueue.add(stringRequest);
}
private void loadProfileDefault() {
Glide.with(this).load(bitmap)
.into(imgProfile);
imgProfile.setColorFilter(ContextCompat.getColor(this, R.color.profile_default_tint));
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String profileImage = sharedPreferences.getString("profile_image", "");
bitmap = decodeToBase64(profileImage);
imgProfile.setImageBitmap(bitmap);
}
#OnClick({R.id.img_profile})
void onProfileImageClick() {
Dexter.withActivity(this)
.withPermissions(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)
.withListener(new MultiplePermissionsListener() {
#Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
if (report.areAllPermissionsGranted()) {
showImagePickerOptions();
}
if (report.isAnyPermissionPermanentlyDenied()) {
showSettingsDialog();
}
}
#Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
token.continuePermissionRequest();
}
}).check();
}
private void showImagePickerOptions() {
ImagePicker.showImagePickerOptions(this, new ImagePicker.PickerOptionListener() {
#Override
public void onTakeCameraSelected() {
launchCameraIntent();
}
#Override
public void onChooseGallerySelected() {
launchGalleryIntent();
}
});
}
private void launchCameraIntent() {
Intent intent = new Intent(My_Profile.this, ImagePicker.class);
intent.putExtra(ImagePicker.INTENT_IMAGE_PICKER_OPTION, ImagePicker.REQUEST_IMAGE_CAPTURE);
// setting aspect ratio
intent.putExtra(ImagePicker.INTENT_LOCK_ASPECT_RATIO, true);
intent.putExtra(ImagePicker.INTENT_ASPECT_RATIO_X, 1); // 16x9, 1x1, 3:4, 3:2
intent.putExtra(ImagePicker.INTENT_ASPECT_RATIO_Y, 1);
// setting maximum bitmap width and height
intent.putExtra(ImagePicker.INTENT_SET_BITMAP_MAX_WIDTH_HEIGHT, true);
intent.putExtra(ImagePicker.INTENT_BITMAP_MAX_WIDTH, 1000);
intent.putExtra(ImagePicker.INTENT_BITMAP_MAX_HEIGHT, 1000);
startActivityForResult(intent, REQUEST_IMAGE);
}
private void launchGalleryIntent() {
Intent intent = new Intent(My_Profile.this, ImagePicker.class);
intent.putExtra(ImagePicker.INTENT_IMAGE_PICKER_OPTION, ImagePicker.REQUEST_GALLERY_IMAGE);
// setting aspect ratio
intent.putExtra(ImagePicker.INTENT_LOCK_ASPECT_RATIO, true);
intent.putExtra(ImagePicker.INTENT_ASPECT_RATIO_X, 1); // 16x9, 1x1, 3:4, 3:2
intent.putExtra(ImagePicker.INTENT_ASPECT_RATIO_Y, 1);
startActivityForResult(intent, REQUEST_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == REQUEST_IMAGE) {
if (resultCode == Activity.RESULT_OK) {
Uri uri = data.getParcelableExtra("path");
// You can update this bitmap to your server
// loading profile image from local cache
loadProfile(uri.toString());
}
}
}
private void showSettingsDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(My_Profile.this);
builder.setTitle(getString(R.string.dialog_permission_title));
builder.setMessage(getString(R.string.dialog_permission_message));
builder.setPositiveButton(getString(R.string.go_to_settings), (dialog, which) -> {
dialog.cancel();
openSettings();
});
builder.setNegativeButton(getString(android.R.string.cancel), (dialog, which) -> dialog.cancel());
builder.show();
}
// navigating user to app settings
private void openSettings() {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivityForResult(intent, 101);
}
here is my xml code
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/img_profile"
android:layout_width="150dp"
android:layout_height="150dp"
android:src="#drawable/useree1"
app:civ_border_width="2dp"
app:civ_border_color="#FF000000"
android:elevation="10dp"
android:scaleType="centerCrop"
android:layout_below="#+id/header_cover_image"
android:layout_centerHorizontal="true"
android:layout_marginTop="-80dp"/>
<de.hdodenhof.circleimageview.CircleImageView
try this way :
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String profileImage = sharedPreferences.getString("profile_image", "");
Bitmap bitmap = decodeToBase64(profileImage);
public static Bitmap decodeToBase64(String str) {
byte[] decodedByte = Base64.decode(str, 0);
return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
}
I'd recommend the Glide image handling library...
Makes this a lot easier...
https://github.com/bumptech/glide
ImageView imgView = findViewById(R.id.imageview);
Glide
.with(context)
.load(imageBytes)
.centerCrop()
.into(imgView);

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

Why does my Alert Dialog not open?

I have the Problem that the Dialog Box with "Take Photo", "Choose from Gallery" and Cancel isn't showing.
Below I have added the code.
Wizard.Java:
public class Wizard extends Activity {
ImageView viewImage;
Button b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b=(Button)findViewById(R.id.btnSelectPhoto);
viewImage=(ImageView)findViewById(R.id.viewImage);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds options to the action bar if it is
present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from
Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(Wizard.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo"))
{
Intent intent = new
Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new
File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(f));
startActivityForResult(intent, 1);
}
else if (options[item].equals("Choose from Gallery"))
{
Intent intent = new
Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
viewImage.setImageBitmap(bitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
f.delete();
OutputStream outFile = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Log.w("path of image from gallery......******************.........", picturePath+"");
viewImage.setImageBitmap(thumbnail);
}
}
}
}
Wizard.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="#+id/editText1"
android:layout_width="284dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="40dp"
android:ems="10"
android:singleLine="true"
android:maxLength="10">
<requestFocus />
</EditText>
<Button
android:id="#+id/btnSelectPhoto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select Photo" />
<ImageView
android:id="#+id/viewImage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="#drawable/camera"/>
</LinearLayout>
You can use custom alertdialog.
LayoutInflater inflater = getLayoutInflater();
View dialoglayout = inflater.inflate(R.layout.dialog_layout, null);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(dialoglayout);builder.show();
before you must create dialog_layout.xml
are you sure that it doesn't work? Your code is correct. It could be perfectly show on Nexus 5.

Categories

Resources