intent camera crashes after back press - java

I am trying to use intent camera to capture video in my app,when i take a video and i am redirected to the Main activity it works all fine,however after i press back button in the intent camera mode it crashes
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
protected void onActivityResult(int reqCode, int resCode, Intent data) {
if (reqCode == REQUEST_CODE_UPDATE_PIC) {
if (resCode == RESULT_OK) {
String imagePath = data.getStringExtra(GOTOConstants.IntentExtras.IMAGE_PATH);
showCroppedImage(imagePath);
Bitmap bitmap;
bitmap = BitmapFactory.decodeFile(imagePath);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 50, stream);
byte[] image = stream.toByteArray();
// Create the ParseFile
ParseFile file = new ParseFile("profilepic.png", image);
// Upload the image into Parse Cloud
file.saveInBackground();
// Create a column named "ImageFile" and insert the image
user.put("profilepictures", file);
user.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
Toast.makeText(getApplicationContext(), "Saved Successfully",
Toast.LENGTH_SHORT).show();
}
});
// Show a simple toast message
Toast.makeText(MainActivity.this, "Image Uploaded",
Toast.LENGTH_SHORT).show();
} else if (resCode == RESULT_CANCELED) {
//TODO : Handle case
} else {
String errorMsg = data.getStringExtra(ImageCropActivity.ERROR_MSG);
Toast.makeText(this, errorMsg, Toast.LENGTH_LONG).show();
}
}
if (mediaFile != null) {
compress();
}
if (resCode == Activity.RESULT_OK && data != null) {
uri = data.getData();
if (uri == null) {
Toast.makeText(getApplicationContext(), "uri blank", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "uri full", Toast.LENGTH_LONG).show();
}
//proceedbutton.setVisibility(View.VISIBLE);
if (resCode == RESULT_CODE_COMPRESS_VIDEO) {
if (uri != null) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null, null);
try {
if (cursor != null && cursor.moveToFirst()) {
String displayName = cursor.getString(
cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
Log.i(TAG, "Display Name: " + displayName);
int sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE);
String size = null;
if (!cursor.isNull(sizeIndex)) {
size = cursor.getString(sizeIndex);
} else {
size = "Unknown";
}
Log.i(TAG, "Size: " + size);
tempFile = FileUtils.saveTempFile(displayName, this, uri);
editText.setText(mediaFile.getPath());
}
} finally {
if (cursor != null) {
cursor.close();
}
}
}
}
}
}

I am guessing if your Camera Video Intent CODE = RESULT_CODE_COMPRESS_VIDEO. Then replace your code as below to
First Thing change resCode == RESULT_CODE_COMPRESS_VIDEO.to reqCOde and use the following code
if (reqCode == RESULT_CODE_COMPRESS_VIDEO) {
if(resCode == RESULT_OK) {
if (uri != null) {
compress();
}
}
else if(resCode == RESULT_CANCELED && data!=null){
Toast.makeText(MainActivity.this,"No Video Recorded",Toast.LENGTH_SHORT).show();
}
}
This won't crash your application on backpressed from the intent camera.

Hope this helps !
if (reqCode == RESULT_CODE_COMPRESS_VIDEO) {
if(resCode == RESULT_OK) {
if (uri != null) {
compress();
}
}
else if(resCode == RESULT_CANCELED && data!=null){
Toast.makeText(MainActivity.this,"Error !",Toast.LENGTH_LONG).show();
else return true;
}
}

if (requestCode == 1) {
if(data !=null){
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
//String path = saveImage(thumbnail);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] byteArray = stream.toByteArray();
Glide.with(eventPreview.getContext()).load(byteArray).into(eventPreview);
int width = eventPreview.getMeasuredWidth();
eventPreview.getLayoutParams().height = width/2;
eventPreview.setScaleType(ImageView.ScaleType.FIT_XY);
postData = byteArray;
PreviewTXT.setVisibility(View.GONE);}
}

Related

How to convert multiple photos into video using jcodec

I have three photos that are entered by the user
using a camera or gallery I have saved the photos that the user takes with this code
private void openImageIntent(int type) {
// Determine Uri of camera image to save.
final File root = new File(
Environment.getExternalStorageDirectory() + File.separator + "myapp" + File.separator);
boolean success = root.exists() || root.mkdir();
if (success) {
final String fName = "img_" + System.currentTimeMillis() + ".jpg";
outputFileUri = Uri.fromFile(new File(root, fName));
// Camera.
final List<Intent> cameraIntents = new ArrayList<>();
final Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
final PackageManager packageManager = getPackageManager();
final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
for (ResolveInfo res : listCam) {
final String packageName = res.activityInfo.packageName;
final Intent intent = new Intent(captureIntent);
intent.setComponent(new ComponentName(packageName, res.activityInfo.name));
intent.setPackage(packageName);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
cameraIntents.add(intent);
}
// Filesystem.
Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.addCategory(Intent.CATEGORY_OPENABLE);
// Chooser of filesystem options.
Intent chooserIntent = Intent.createChooser(galleryIntent, getString(R.string.Select_image));
// Add the camera options.
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[cameraIntents.size()]));
startActivityForResult(chooserIntent, type);
} else {
// Filesystem.
Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.addCategory(Intent.CATEGORY_OPENABLE);
// Chooser of filesystem options.
Intent chooserIntent = Intent.createChooser(galleryIntent, getString(R.string.Select_image));
startActivityForResult(chooserIntent, type);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (resultCode == RESULT_OK) {
// Select Image from Camera Or Gallery
if (requestCode == 1) {
final boolean isCamera;
if (data == null) {
// Camera
isCamera = true;
} else {
String action = data.getAction();
if (action == null) {
// Gallery
isCamera = false;
} else {
// Camera OR Gallery
isCamera = action.equals(MediaStore.ACTION_IMAGE_CAPTURE);
}
}
Uri selectedImageUri = isCamera ? outputFileUri : data.getData();
if (selectedImageUri != null) {
// Start Cropping Image Calendar.getInstance().getTime()
String destinationFileName = "SampleCropImage_" + System.currentTimeMillis() + ".png";
Uri outputCropImageUri = Uri.fromFile(new File(getCacheDir(), destinationFileName));
UCrop uCrop = UCrop.of(selectedImageUri, outputCropImageUri);
uCrop.withOptions(getUCropOptions(this));
uCrop.start(this);
} else
ShowMessage("ERORR");
} else if (requestCode == 2) {
final boolean isCamera;
if (data == null) {
// Camera
isCamera = true;
} else {
String action = data.getAction();
if (action == null) {
// Gallery
isCamera = false;
} else {
// Camera OR Gallery
isCamera = action.equals(MediaStore.ACTION_IMAGE_CAPTURE);
}
}
Uri selectedImageUri = isCamera ? outputFileUri : data.getData();
if (selectedImageUri != null) {
// Start Cropping Image Calendar.getInstance().getTime()
String destinationFileName = "SampleCropImage_" + System.currentTimeMillis() + ".png";
Uri outputCropImageUri = Uri.fromFile(new File(getCacheDir(), destinationFileName));
UCrop uCrop = UCrop.of(selectedImageUri, outputCropImageUri);
uCrop.withOptions(getUCropOptions(this));
uCrop.start(this);
} else
ShowMessage("ERORR");
} else if (requestCode == 3) {
final boolean isCamera;
if (data == null) {
// Camera
isCamera = true;
} else {
String action = data.getAction();
if (action == null) {
// Gallery
isCamera = false;
} else {
// Camera OR Gallery
isCamera = action.equals(MediaStore.ACTION_IMAGE_CAPTURE);
}
}
Uri selectedImageUri = isCamera ? outputFileUri : data.getData();
if (selectedImageUri != null) {
// Start Cropping Image Calendar.getInstance().getTime()
String destinationFileName = "SampleCropImage_" + System.currentTimeMillis() + ".png";
Uri outputCropImageUri = Uri.fromFile(new File(getCacheDir(), destinationFileName));
UCrop uCrop = UCrop.of(selectedImageUri, outputCropImageUri);
uCrop.withOptions(getUCropOptions(this));
uCrop.start(this);
} else
ShowMessage("ERORR");
}
// Crop Result
if (requestCode == UCrop.REQUEST_CROP && type == 1) {
Uri resultUri = UCrop.getOutput(data);
if (resultUri != null) {
byte[] imageByte = ImageUtils.compressImage(this, resultUri);
Bitmap bitmap = ImageUtils.getBitmapFromByte(imageByte);
Image1.setImageBitmap(bitmap);
} else
ShowMessage("ERORR");
} else if (requestCode == UCrop.REQUEST_CROP && type == 2) {
Uri resultUri = UCrop.getOutput(data);
if (resultUri != null) {
byte[] imageByte = ImageUtils.compressImage(this, resultUri);
Bitmap bitmap = ImageUtils.getBitmapFromByte(imageByte);
Image2.setImageBitmap(bitmap);
} else
ShowMessage("ERORR");
} else if (requestCode == UCrop.REQUEST_CROP && type == 3) {
Uri resultUri = UCrop.getOutput(data);
if (resultUri != null) {
byte[] imageByte = ImageUtils.compressImage(this, resultUri);
Bitmap bitmap = ImageUtils.getBitmapFromByte(imageByte);
Image3.setImageBitmap(bitmap);
} else
ShowMessage("ERORR");
}
}
if (resultCode == UCrop.RESULT_ERROR) {
final Throwable cropError = UCrop.getError(data);
if (cropError != null)
Toast.makeText(this, cropError.getMessage(), Toast.LENGTH_LONG).show();
else
ShowMessage("Erorr");
}
} catch (Exception e) {
e.printStackTrace();
}
}
How do I make these images that were entered by the user turn into a video using jcodec library ?
Please, I need a code that matches my code When I paste it works I am a beginner, I searched a lot and found many solutions but it is not at all clear to me
How do I make these images that were entered by the user turn into a video using jcodec library ?
Thanks <3.

Webview camera giving an error, creating picture of 0 bytes before taking picture

Those are variables
private static final int FILECHOOSER_RESULTCODE = 1;
private ValueCallback<Uri> mUploadMessage;
private Uri mCapturedImageURI = null;
// the same for Android 5.0 methods only
private ValueCallback<Uri[]> mFilePathCallback;
private String mCameraPhotoPath;
This is the file chooser code
Usually it should create a image after taking the image, but it is creating a blank image before opening the camera intent, and then it is showing an error icon instead of showing the Image.
Please help me to fix the problem
public boolean onShowFileChooser(
WebView webView, ValueCallback<Uri[]> filePathCallback,
WebChromeClient.FileChooserParams fileChooserParams) {
if (mFilePathCallback != null) {
mFilePathCallback.onReceiveValue(null);
}
mFilePathCallback = filePathCallback;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// create the file where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
} catch (IOException ex) {
// Error occurred while creating the File
Log.e(TAG, "Unable to create Image File", ex);
}
// continue only if the file was successfully created
if (photoFile != null) {
mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
} else {
takePictureIntent = null;
}
}
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("image/*");
Intent[] intentArray;
if (takePictureIntent != null) {
intentArray = new Intent[]{takePictureIntent};
} else {
intentArray = new Intent[0];
}
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, getString(R.string.image_chooser));
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
return true;
}
// creating image files (Lollipop only)
private File createImageFile() throws IOException {
// Create an image file name
Log.d(TAG, "createImageFile: creating Image");
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, // prefix
".jpg", // suffix
storageDir // directory
);
// Save a file: path for use with ACTION_VIEW intents
mCameraPhotoPath = "file:" + image.getAbsolutePath();
return image;enter code here
}
On Activity Result code given below
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// code for all versions except of Lollipop
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == this.mUploadMessage) {
return;
}
Uri result = null;
try {
if (resultCode != RESULT_OK) {
result = null;
} else {
// retrieve from the private variable if the intent is null
result = data == null ? mCapturedImageURI : data.getData();
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "activity :" + e, Toast.LENGTH_LONG).show();
}
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
} // end of code for all versions except of Lollipop
// start of code for Lollipop only
if (requestCode != FILECHOOSER_RESULTCODE || mFilePathCallback == null) {
super.onActivityResult(requestCode, resultCode, data);
return;
}
Uri[] results = null;
// check that the response is a good one
if (resultCode == Activity.RESULT_OK) {
if (data == null || data.getData() == null) {
// if there is not data, then we may have taken a photo
if (mCameraPhotoPath != null) {
results = new Uri[]{Uri.parse(mCameraPhotoPath)};
}
} else {
String dataString = data.getDataString();
if (dataString != null) {
results = new Uri[]{Uri.parse(dataString)};
}
}
}
mFilePathCallback.onReceiveValue(results);
mFilePathCallback = null;
}
Remove this
return File.createTempFile(imageFileName,".jpg",storageDir);
Add this
File image = new File(storageDir.toString()+"/"+imageFileName+".jpg");
return image;
No exercise needed you came here for an answer i presume.

Capturing an image and uploading it to a database

I want to upload image from camera into database. I already solved the problem from gallery image from gallery already uploaded to database but it wont work on from camera or capture image, i tried to code the same with gallery but i having a error.
Here is my code.
Here is my Android Manifest.xml code
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-feature android:name="android.hardware.camera"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
MainActivity
This is my submit button
reportsubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ImageUploadToServerFunction();
}
});
}
This is my code to upload image into database
public void ImageUploadToServerFunction(){
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, bytes);
byte[] byteArrayVar = bytes.toByteArray();
final String ConvertImage = Base64.encodeToString(byteArrayVar, Base64.DEFAULT);
}
This is my code to open open the Camera
private void openCamera() {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
This is my OnActivityResult code
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (attachment >= 1 && attachment <= 8) {
if (resultCode == RESULT_OK && requestCode == 1 && data != null && data.getData() != null) {
Uri uri = data.getData();
try {
if (attachment == 1) {
dynamic = (ImageView) findViewById(R.id.imgview);
} else if (attachment == 2) {
dynamic = (ImageView) findViewById(R.id.imgview1);
} else if (attachment == 3) {
dynamic = (ImageView) findViewById(R.id.imgview2);
} else if (attachment == 4) {
dynamic = (ImageView) findViewById(R.id.imgview3);
} else if (attachment == 5) {
dynamic = (ImageView) findViewById(R.id.imgview4);
} else if (attachment == 6) {
dynamic = (ImageView) findViewById(R.id.imgview5);
} else if (attachment == 7) {
dynamic = (ImageView) findViewById(R.id.imgview6);
} else if (attachment == 8) {
dynamic = (ImageView) findViewById(R.id.imgview7);
}
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
dynamic.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
} else if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
if (attachment == 1) {
dynamic = (ImageView) findViewById(R.id.imgview);
} else if (attachment == 2) {
dynamic = (ImageView) findViewById(R.id.imgview1);
} else if (attachment == 3) {
dynamic = (ImageView) findViewById(R.id.imgview2);
} else if (attachment == 4) {
dynamic = (ImageView) findViewById(R.id.imgview3);
} else if (attachment == 5) {
dynamic = (ImageView) findViewById(R.id.imgview4);
} else if (attachment == 6) {
dynamic = (ImageView) findViewById(R.id.imgview5);
} else if (attachment == 7) {
dynamic = (ImageView) findViewById(R.id.imgview6);
} else if (attachment == 8) {
dynamic = (ImageView) findViewById(R.id.imgview7);
}
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
dynamic.setImageBitmap(imageBitmap);
// CALL THIS METHOD TO GET THE URI FROM THE BITMAP
Uri tempUri = getImageUri(getApplicationContext(), imageBitmap);
// CALL THIS METHOD TO GET THE ACTUAL PATH
Toast.makeText(report.this,"Here "+ getRealPathFromURI(tempUri),Toast.LENGTH_LONG).show();
}
System.out.print(resultCode);
}
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
public String getRealPathFromURI(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}

Android app crop photo

I have a question.
This is the code that my application already have and it works like this : takes photo >crop > upload.
I don't want to crop the photo .How can I do this? Just deleting the dispatchCropImageIntent method?
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(this.getClass().getSimpleName(), "onActivityResult");
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_IMAGE_CAPTURE) {
File imageFile = new File(mCurrentPhotoPath);
if (imageFile.exists()) {
dispatchCropImageIntent(Uri.fromFile(imageFile));
}
} else if (requestCode == REQUEST_IMAGE_FROM_GALLERY_SELECT) {
dispatchCropImageIntent(data.getData());
} else if (requestCode == REQUEST_PICTURE_CROP) {
String filePath = Environment.getExternalStorageDirectory()
+ "/temporary_holder.jpg";
setCurrentBitmap(BitmapFactory.decodeFile(filePath));
} else if(requestCode == CAMERA_ACTIVITY_CODE){
// Get path
String path = data.getStringExtra(CustomCamera.OUT_PATH);
// Read file
byte[] imgData = AppFS.readFileFromPath(path);
if (imgData != null) {
Bitmap bitmap = BitmapFactory.decodeByteArray(imgData , 0, imgData.length);
// TODO: Do something with the image, it should be okay
//((ImageView)findViewById(R.id.img)).setImageBitmap(bitmap);
} else {
Log.e("Main", "Data is null");
}
}
}
else{
onBackPressed();
}
}
And :
private void dispatchCropImageIntent(Uri uri) {
Intent cropImageIntent = new Intent("com.android.camera.action.CROP");
cropImageIntent.setDataAndType(uri, "image/*");
cropImageIntent.putExtra("crop", "true");
cropImageIntent.putExtra("noFaceDetection", true);
cropImageIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
// retrieve data on return
cropImageIntent.putExtra("return-data", true);
File f = new File(Environment.getExternalStorageDirectory(),
"/temporary_holder.jpg");
try {
f.createNewFile();
} catch (IOException ex) {
Log.e("io", ex.getMessage());
}
uri = Uri.fromFile(f);
cropImageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(cropImageIntent, REQUEST_PICTURE_CROP);
}
If I understand you correctly,you want to make your app working like this: takes photo > upload. So, you need to replace dispatchCropImageIntent() with setCurrentBitmap() or upload methond.

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