Change an image that is store in parse through android - java

I am trying to update an image that is saved in parse through the android app, I am able o retrieve it and load it to the app but I am not able to save the new image that I selected to replace the old one. This is how I tried to do it and it only saves the file on the current state and not to parse. This is the code that I have currently and it is not working the way I want it to. Kindly assist.
Code is as follows
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == LOAD_IMAGE_RESULTS) {
Uri pickedImage = data.getData();
InputStream inputStream;
try {
inputStream = getContentResolver().openInputStream(pickedImage);
Bitmap selectedImages = BitmapFactory.decodeStream(inputStream);
imageSelected.setImageBitmap(selectedImages);
selectedImages = ((BitmapDrawable) imageSelected.getDrawable()).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
selectedImages.compress(Bitmap.CompressFormat.PNG, 5, stream);
byte[] imageRec = stream.toByteArray();
file = new ParseFile("profileUpdate.png", imageRec);
file.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (null == e)
currentUser.put("ProfilePicture", file);
}
});
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Unable to load image",
Toast.LENGTH_LONG).show();
}
}
}
}

I just added the currentUser.saveInBackground(); line after currentUser.put("ProfilePicture", file); and added a currentUser.remove("ProfilePicture"); before it and it worked.

Related

How to upload a video to parse server?

#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Uri selected = data.getData();
File file = new File(String.valueOf(selected));
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[(int) file.length()];
try {
for (int readnum; (readnum = fis.read(buf)) != -1; ) {
bos.write(buf, 0, readnum);
}
} catch (Exception e) {
e.printStackTrace();
}
byte[] bytes = bos.toByteArray();
ParseFile parseFile =new ParseFile("video.mp4",bytes);
ParseObject parseObject = new ParseObject("video2");
parseObject.put("video2", parseFile);
parseObject.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Toast.makeText(userlist.this, "video has been uploaded successfully :)", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(userlist.this, "sorry we could't upload the video ", Toast.LENGTH_SHORT).show();
}
}
});
}
This is my current code. I managed to access the phone gallery and then I convert the video to byte array to be able to upload it to Parse but i guess the problem is that any video i choose returns null i access the gallery using this code :
public class userlist extends AppCompatActivity {
public void getphoto() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 1);
}
here is my stack trace
java.io.FileNotFoundException: content:/media/external/video/media/14146 (No such file or directory)
2020-07-05 17:28:03.965 31930-31930/com.parse.starter W/System.err: at com.parse.starter.userlist.onActivityResult(userlist.java:85)
2020-07-05 17:28:03.967 31930-31930/com.parse.starter W/System.err: at com.parse.starter.userlist.onActivityResult(userlist.java:92)
2020-07-05 17:28:03.981 31930-32065/com.parse.starter W/System: Ignoring header Content-Type because its value was null.

compressing selected image file/taken from camera

trying to let users add profile pictures, but I want to compress the image file before sending it to the server.
How can i compress the:
File imageFile = new File(resultUri.getPath());
Tried and searched but couldn't get to work
#Override
public void onActivityResult(int requestCode, int resultCode, 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) {
Uri resultUri = result.getUri();
btnConfirm.setVisibility(View.VISIBLE);
btnConfirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
File imageFile = new File(resultUri.getPath());
progressDialog.show();
AndroidNetworking.upload("https://myweb.com/uploadImg.php")
.addMultipartFile("image", imageFile)
Would love to get some advice, Thanks in advance.
Check this
Uri selectedImage = imageReturnedIntent.getData();
InputStream imageStream = null;
try {
imageStream = getContentResolver().openInputStream(
selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap bmp = BitmapFactory.decodeStream(imageStream);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
try {
stream.close();
stream = null;
} catch (IOException e) {
e.printStackTrace();
}

Opening a downloaded file and copying it

I am trying to open a file I demand from my user to download so I can use it so I am trying to copy it to my internal storage.
I tried using this code:
Intent myIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
myIntent.setType("text/*");
myIntent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(myIntent, 100);
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 100) {
if(resultCode == Activity.RESULT_OK){
Uri result= data.getData();
Log.e("fag", result.getPath());
copyFile(result);
}
if (resultCode == Activity.RESULT_CANCELED) {
Log.e("", "canceled");
}
}
Intent a = new Intent(getApplicationContext(), MainActivity.class);
startActivity(a);
}
private void copyFile(Uri inputFile) {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream(inputFile.getPath());
out = openFileOutput(NAME , MODE_PRIVATE);
byte[] buffer = new byte[1024];
while ( in.read(buffer) != -1) {
out.write(buffer);
}
in.close();
in = null;
out.close();
out = null;
} catch (FileNotFoundException fnfe1) {
Log.e("tag", fnfe1.getMessage());
fnfe1.printStackTrace();
}
catch (Exception e) {
Log.e("tag", e.getMessage());
}
}
But when I run this code, I got a File Not Found Exception. so I checked what URI I get from the intent and it isn't the path to the file but this path
/document/primary:Download/5643_05072018-13-48.csv
and I don't know how to use this URI.
I got a simmmilar resualt using the ACTION_GET_CONTENT intent.
So my question is can I use this code and the URI that I got to copy that file or I need to do it in an other way? and how in both cases?
in = new FileInputStream(inputFile.getPath());
Change to:
InputStream is = getContentResolver().openInputStream(inputFile);
And dont name that inputFile but uri.

Android Rotates Camera captured photo by itself

I would like to launch the native Android camera and save captured image at a specified location, but when I do that and i try to reach the photo later ,saved imaged is 90 degree rotated by itself. i am using a LG cellphone to run the program. I have been already tried a solution that i found here, but they did not work. I put my code for you here... please correct me or give me a new solution.
Thank you a lot
private void cameraIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra("photo", true);
intent.putExtra("android.intent.extras.CAMERA_FACING", android.hardware.Camera.CameraInfo.CAMERA_FACING_FRONT);
intent.putExtra("android.intent.extras.LENS_FACING_FRONT", 1);
intent.putExtra("android.intent.extra.USE_FRONT_CAMERA", true);
startActivityForResult(intent, REQUEST_CAMERA);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
private void onCaptureImageResult(Intent data) {
ByteArrayOutputStream bytes = null;
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(getExternalStorageDirectory(),
File.separator + "profile.jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String address = getExternalStorageDirectory().getAbsolutePath();
ExifInterface exif = null;
try {
if(destination.exists()) {
exif = new ExifInterface(address+File.separator+"profile.jpg");
Log.d("EXIF value", exif.getAttribute(ExifInterface.TAG_ORIENTATION));
}
} catch (IOException e) {
e.printStackTrace();
}
if(exif.getAttribute(ExifInterface.TAG_ORIENTATION).equalsIgnoreCase("6")){
thumbnail= rotate(thumbnail, 90);
}else if(exif.getAttribute(ExifInterface.TAG_ORIENTATION).equalsIgnoreCase("8")){
thumbnail= rotate(thumbnail, 270);
}else if(exif.getAttribute(ExifInterface.TAG_ORIENTATION).equalsIgnoreCase("3")){
thumbnail= rotate(thumbnail, 270);
}
resized = Bitmap.createScaledBitmap(thumbnail, navUserImage.getWidth(), navUserImage.getHeight(), true);
navUserImage.setImageBitmap(resized);
}
It does not rotate in all devices. You can try this solution. I have worked on something similar, and it suited me well.

Uploading/saving selected image with Parse as backend

Ok guys, so after spending one day trying to figure out how to upload an image to parse servers i finally decided to ask for your help. I didn't find any full example on how to do this.
What i want to be able to do is:
select image from gallery (already did that)
load into inageView (already did that)
at onClick event upload the selected picture to Parse servers (my problem)
Here you have my code snippet so far, but it's not working.
private static int RESULT_LOAD_IMAGE = 1;
mSubmitJobBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
createJob(); //this method will send data to Parse
}
});
private void addJob(final String mUsernameText, String mJobNameText,
String mJobDescriptionText, String mJobPriceText) {
/*Bitmap bitmap = BitmapFactory.decodeFile("picturePath");
// Convert it to byte
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// Compress image to lower quality scale 1 - 100
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] image = stream.toByteArray();
try {
image = readInFile(path);
} catch (Exception e) {
e.printStackTrace();
}*/
ParseUser user = ParseUser.getCurrentUser();
anunt.put("username", "andrei");
anunt.put("jobName", mJobNameText);
anunt.put("jobDescription", mJobDescriptionText);
anunt.put("jobPrice", mJobPriceText);
/*// Create a column named "jobPicture" and set the string
anunt.put("jobPicture", "picturePath");
// Create the ParseFile
ParseFile file = new ParseFile("picturePath", image);
// Upload the image into Parse Cloud
file.saveInBackground();
// Create a column named "ImageFile" and insert the image
anunt.put("ImageFile", file);*/
anunt.saveInBackground(new SaveCallback() {
public void done(ParseException e) {
if (e == null) {
Toast.makeText(getApplicationContext(),
"Job succesfully posted!", Toast.LENGTH_LONG)
.show();
Intent in = new Intent(getApplicationContext(),
JobsListActivity.class);
in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(in);
finish();
} else {
Toast.makeText(getApplicationContext(),
"Sign up error, please check all the fields",
Toast.LENGTH_LONG).show();
}
}
});
}
public byte[] readInFile(String path) throws IOException {
byte[] data = null;
File file = new File(path);
InputStream input_stream = new BufferedInputStream(new FileInputStream(
file));
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
data = new byte[16384]; // 16K
int bytes_read;
while ((bytes_read = input_stream.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, bytes_read);
}
input_stream.close();
return buffer.toByteArray();
}***strong text***
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
PreferenceManager.getDefaultSharedPreferences(this).edit()
.putString("picturePath", picturePath).commit();
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.addJob_imageView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
You should use PHP or any server script to upload image from android to the server. Try the URL given below,
Upload Image to Server PHP Android
this is the answer!
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// Compress image to lower quality scale 1 - 100
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] imagez = stream.toByteArray();
ParseFile filez = new ParseFile("androidbegin.png",
imagez);
filez.saveInBackground();
imgupload = new ParseObject("Anunturi");
imgupload.put("JobPictureName", "AndroidBegin Logo");
imgupload.put("jobPicture", filez);
imgupload.put("jobPictureName", picturePath);
imgupload.put("username", mUsernameText);
imgupload.put("jobName", mJobNameText);
imgupload.put("jobDescription", mJobDescriptionText);
imgupload.put("jobPrice", mJobPriceText);
imgupload.saveInBackground(new SaveCallback() {
public void done(ParseException e) {
if (e == null) {
Toast.makeText(getApplicationContext(),
"Job succesfully posted!",
Toast.LENGTH_LONG).show();
Intent in = new Intent(
getApplicationContext(),
JobsListActivity.class);
in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(in);
finish();
} else {
mGoogleNow
.setVisibility(mGoogleNow.INVISIBLE);
Toast.makeText(getApplicationContext(),
"An error occured",
Toast.LENGTH_LONG).show();
}
}
});
} else {
bitmap = null;
imgupload = new ParseObject("Anunturi");
imgupload.put("username", mUsernameText);
imgupload.put("jobName", mJobNameText);
imgupload.put("jobDescription", mJobDescriptionText);
imgupload.put("jobPrice", mJobPriceText);
imgupload.put("jobPictureName", "null");
imgupload.saveInBackground(new SaveCallback() {
public void done(ParseException e) {
if (e == null) {
Toast.makeText(
getApplicationContext(),
"Job succesfully posted!",
Toast.LENGTH_LONG).show();
Intent in = new Intent(
getApplicationContext(),
JobsListActivity.class);
in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(in);
finish();
} else {
Toast.makeText(
getApplicationContext(),
"Error while posting job...",
Toast.LENGTH_LONG).show();
}
}
});

Categories