Deleting/Removing a ParseFile from ParseUser (Android) - android

I am trying to remove a ParseFile from a ParseUser. The ParseFile is a profile picture that was created, and I would like to provide my users will the ability to change there profile picture when convenient to them.
I am looking for a way to delete the old ParseFile associated with the profile picture, and just store a new one.
I cannot seem to get the .remove("photo"); method to work properly, and am not sure if I am going about this the wrong way. What would be the best method to do something like this?
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) {
return;
}
if (requestCode == RESULT_LOAD_IMAGE) {
Bundle extras2 = data.getExtras();
if (extras2 != null) {
Bitmap bitmap = extras2.getParcelable("data");
ivProfilePic.setImageBitmap(bitmap);
final ParseUser currentUser = ParseUser.getCurrentUser();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] bitmapByte = stream.toByteArray();
final ParseFile profilePicture = new ParseFile(
"profilePicture", bitmapByte);
profilePicture.saveInBackground(new SaveCallback() {
public void done(ParseException e) {
if (e != null) {
} else {
// check to see if ParseFile exists, if it does
// delete it and set new ParseFile
currentUser.remove("photo");
currentUser.put("photo", profilePicture);
currentUser.saveInBackground();
updateViewsWithProfileInfo();
}
}
});
}
}
}

if (resultCode != RESULT_OK) {
return;
}
This line of code stops everything from working properly. If you remove this the ParseFile is removed / updated properly.

Related

Android Photo Take and Send Server

I'm trying to take a photo and upload it to the server, but I'm outputting a thumbnail photo. How can I get it in Full-Size?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setTitle("Set");
SharedPreferences sharedPreferences = getSharedPreferences("Userınfo",0);
email = sharedPreferences.getString("deneme",email);
setContentView(R.layout.tamir_islem);
qrcode=findViewById(R.id.qrcode);
arizaPhoto = findViewById(R.id.arizafoto);
imageShow = findViewById(R.id.arizafotoshow);
arizaPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if(intent1.resolveActivity(getPackageManager()) != null){
startActivityForResult(intent1,CAMERA_ACTION_CODE);
}else{
Toast.makeText(tester.this,"There is no app that support this action",Toast.LENGTH_SHORT).show();
}
}
});
I use this code for taking pictures and string operations.
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data){
super.onActivityResult(requestCode,resultCode,data);
if(requestCode == CAMERA_ACTION_CODE && resultCode == RESULT_OK && data != null) {
Bundle bundle = data.getExtras();
finalPhoto = (Bitmap) bundle.get("data");
System.out.println(bundle);
System.out.println(finalPhoto);
imageShow.setImageBitmap(finalPhoto);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
finalPhoto.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream.toByteArray();
System.out.println(Arrays.toString(byteArray));
encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
}
I use this to send..
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String,String> param = new HashMap<>();
param.put("encoded",encoded);
return param;
}
Thank you for your attention. :)
From the docs at MediaStore
The caller may pass an extra EXTRA_OUTPUT to control where this image will be written. If the EXTRA_OUTPUT is not present, then a small sized image is returned as a Bitmap object in the extra field. This is useful for applications that only need a small image.
To retrieve a full image you need to write it to a file. If you don't want to save this image then create a temporary file and delete it after sending it to the server.

Saving a picture at a certain storage location and storing its path into a SQLite Database Table

I'm working on an app with SQLite and I want to be able to select a profile picture for an user (that will be saved locally). Basically I have a crop activity and I want to select a picture, crop it and compress it, then I want to save it in the phone at a certain storage path that will not be deleted by cleaning the cache and will also not be visible in the Gallery of the phone (important). In the mean time, I want the new path to be saved in my SQLite database so it can be used to rapidly load the image in an ImageView where it's necessary.
This is the code where I load, crop, compress and also preview the picture in a test ImageView.
public void chooseProfilePicture(){
CropImage.activity().setGuidelines(CropImageView.Guidelines.ON).setAspectRatio(1,1).start(this);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE)
{
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if(resultCode == RESULT_OK)
{
assert result != null;
profileImageURI = result.getUri();
File thumbnailURI = new File(Objects.requireNonNull(profileImageURI.getPath()));
try
{
compressedImageFile = new Compressor(activity_user_data.this)
.setMaxHeight(400)
.setMaxWidth(400)
.setQuality(90)
.compressToBitmap(thumbnailURI);
}
catch (IOException e)
{
e.printStackTrace();
}
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
compressedImageFile.compress(Bitmap.CompressFormat.JPEG, 90, byteArrayOutputStream);
profilePicker.setImageBitmap(compressedImageFile);
isImageSelected = true;
}
else
if(resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE)
{
assert result != null;
Exception error = result.getError();
}
}
}

Cannot resolve symbol - Bitmap image compress and upload to Firebase

I'm trying to select an image, compress it and then upload it to the firebase Storage. I'm trying the following code but getting an error that Cannot resolve symbol 'data2'.
This is my activity:
private void openFileChooserOne() {
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 void uploadFile() {
FirebaseUser user = mAuth.getCurrentUser();
String userID = user.getUid();
if (mImageUri != null && mImageMedicalUri != null) {
StorageReference fileReference = mStorageRef.child(userID).child("image.jpg");
try {
Bitmap bmp = MediaStore.Images.Media.getBitmap(getContentResolver(), mImageUri);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 25, baos);
byte[] data2 = baos.toByteArray();
} catch (IOException ioEx) {
ioEx.printStackTrace()
}
mUploadTask = fileReference.putBytes(data2) //Getting error here
.addOnSuccessListener(new OnSuccessListener < UploadTask.TaskSnapshot > () {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//
});
}
})
}
I'm new in Java and trying to understand the problem. Will very much appreciate your help to know what I'm doing wrong here.
When you are using the following line of code:
mUploadTask = fileReference.putBytes(data2)
Your data2 variable is outside the scope where it was declared. To solve this, you should either move this line inside the try-catch block or make the data2 variable as a global variable.

How to save bitmap to Firebase

I created a simple application which crop the image . Now I want to save this image to the Fire base .
photo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Intent imageDownload = new
Intent(Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
Intent imageDownload=new Intent();
imageDownload.setAction(Intent.ACTION_GET_CONTENT);
imageDownload.setType("image/*");
imageDownload.putExtra("crop", "true");
imageDownload.putExtra("aspectX", 1);
imageDownload.putExtra("aspectY", 1);
imageDownload.putExtra("outputX", 200);
imageDownload.putExtra("outputY", 200);
imageDownload.putExtra("return-data", true);
startActivityForResult(imageDownload, GALLERY_REQUEST_CODE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GALLERY_REQUEST_CODE && resultCode == RESULT_OK &&
data != null) {
Bundle extras = data.getExtras();
image = extras.getParcelable("data");
photo.setImageBitmap(image);
}
}
How to save this image to the Firebase . I tried many tutorial but could not succeed . Please verify with simple code .
you must first add the dependencies for Firebase Storage to your build.gradle file:
compile 'com.google.firebase:firebase-storage:10.0.1'
compile 'com.google.firebase:firebase-auth:10.0.1'
then create an instance of FirebaseStorage:
FirebaseStorage storage = FirebaseStorage.getInstance();
To upload a file to Firebase Storage, you first create a reference to the full path of the file, including the file name.
// Create a storage reference from our app
StorageReference storageRef = storage.getReferenceFromUrl("gs://<your-bucket-name>");
// Create a reference to "mountains.jpg"
StorageReference mountainsRef = storageRef.child("mountains.jpg");
// Create a reference to 'images/mountains.jpg'
StorageReference mountainImagesRef = storageRef.child("images/mountains.jpg");
// While the file names are the same, the references point to different files
mountainsRef.getName().equals(mountainImagesRef.getName()); // true
mountainsRef.getPath().equals(mountainImagesRef.getPath()); // false
Once you've created an appropriate reference, you then call the putBytes(), putFile(), or putStream() method to upload the file to Firebase Storage.
The putBytes() method is the simplest way to upload a file to Firebase Storage. putBytes() takes a byte[] and returns an UploadTask that you can use to manage and monitor the status of the upload.
// Get the data from an ImageView as bytes
imageView.setDrawingCacheEnabled(true);
imageView.buildDrawingCache();
Bitmap bitmap = imageView.getDrawingCache();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data = baos.toByteArray();
UploadTask uploadTask = mountainsRef.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
Uri downloadUrl = taskSnapshot.getDownloadUrl();
}
});
Firebase does not support binary data, so you need to convert the image data to base64 or use Firebase Storage
Method 1 ( Recommended )
sref = FirebaseStorage.getInstance().getReference(); // please go to above link and setup firebase storage for android
public void uploadFile(Uri imagUri) {
if (imagUri != null) {
final StorageReference imageRef = sref.child("android/media") // folder path in firebase storage
.child(imagUri.getLastPathSegment());
photoRef.putFile(imagUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot snapshot) {
// Get the download URL
Uri downloadUri = snapshot.getMetadata().getDownloadUrl();
// use this download url with imageview for viewing & store this linke to firebase message data
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// show message on failure may be network/disk ?
}
});
}
}
Method 2
for small images we can still go with this solution, there is firebase field value
limitations(1MB field value)
check official doc for details
public void getImageData(Bitmap bmp) {
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, bao); // bmp is bitmap from user image file
bmp.recycle();
byte[] byteArray = bao.toByteArray();
String imageB64 = Base64.encodeToString(byteArray, Base64.URL_SAFE);
// store & retrieve this string which is URL safe(can be used to store in FBDB) to firebase
// Use either Realtime Database or Firestore
}
"firebase-storage 16.0.1"
task.getDowloadUrl() not defined. You can use this i check , working perfectly.
private void firebaseUploadBitmap(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] data = stream.toByteArray();
StorageReference imageStorage = storage.getReference();
StorageReference imageRef = imageStorage.child("images/" + "imageName");
Task<Uri> urlTask = imageRef.putBytes(data).continueWithTask(task -> {
if (!task.isSuccessful()) {
throw task.getException();
}
// Continue with the task to get the download URL
return imageRef.getDownloadUrl();
}).addOnCompleteListener(task -> {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
String uri = downloadUri.toString();
sendMessageWithFile(uri);
} else {
// Handle failures
// ...
}
progressBar.setVisibility(View.GONE);
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE && resultCode == Activity.RESULT_OK) {
// Bitmap imageBitmap = data.getData() ;
Bitmap photo = (Bitmap) data.getExtras().get("data");
if (photo != null)
firebaseUploadBitmap(photo);
} else if (requestCode == SELECT_IMAGE && resultCode == Activity.RESULT_OK) {
Uri uri = data.getData();
if (uri != null)
firebaseUploadImage(uri);
}
}

how can I upload a photo from the gallery to parse.com?

I am trying to upload a photo from the gallery into my parse cloud but I can't figure it out here's my code and what I've done so far .
I've looked everywhere still can't find a solution , can't upload the photo :\
help me please.
public void loadImagefromGallery(View view) {
// Create intent to Open Image applications like Gallery, Google Photos
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start the Intent
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
// When an Image is picked
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
&& null != data) {
// Get the Image from data
Uri selectedImage = data.getData();
myBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
byte[] scaledData = bos.toByteArray();
photoFile = new ParseFile("my_photo.jpg", scaledData);
photoFile.saveInBackground(new SaveCallback() {
public void done(ParseException e) {
if (e != null) {
Toast.makeText(getApplicationContext(),
"Error saving: " + e.getMessage(),
Toast.LENGTH_LONG).show();
} else {
// do something
}
}
});
Save ParseObject in the background
// Create the ParseFile
ParseFile file = new ParseFile("androidbegin.png", image);
// Upload the image into Parse Cloud
file.saveInBackground();
// ParseObject
ParseObject pObject = new ParseObject("ExampleObject");
// Create a column named "ImageName" and set the string
pObject.put("ImageName", "image name here");
// Create a column named "ImageFile" and insert the image
pObject.put("ImageFile", file);
pObject.saveInBackground(); // asynchronous, no callback
Save in the background with callback
pObject.saveInBackground(new SaveCallback () {
#Override
public void done(ParseException ex) {
if (ex == null) {
isSaved = true;
} else {
// Failed
isSaved = false;
}
}
});

Categories

Resources