I want to post image selected through camera to server using multi part .I am getting exception here
java.io.FileNotFoundException: /external/images/media/26: open failed: ENOENT (No such file or directory)
Code is given below:
//On clicking Gallery
layout_gallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loadImageFromGallery();
}
});
public void loadImageFromGallery() {
popupWindow.dismiss();
// 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);
String root = Environment.getExternalStorageDirectory().toString();
Log.e("root", root);
String directory_path = root + "/cam_intent/";
File myDir = new File(directory_path);
myDir.mkdirs();
File file = new File(myDir, "MyPhoto.jpg");
fileUri = Uri.fromFile(file);
Log.e("Uri of File", String.valueOf(fileUri));
galleryIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// Start the Intent
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
launchUploadActivity(true);
} else if (requestCode == RESULT_LOAD_IMG) {
fileUri = data.getData();
//File file = new File(getRealPathFromURI(NewGroupActivity.this,uri));
//fileUri = Uri.fromFile(file);
Log.e("FileUriImageGallery", String.valueOf(fileUri));
String[] filePathColumn = {MediaStore.Images.Media.DATA};
// Get the cursor
Cursor cursor = getContentResolver().query(fileUri,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
ImageView imgView = (ImageView) findViewById(R.id.groupPic);
// Set the Image in ImageView after decoding the String
imgView.setImageBitmap(BitmapFactory.decodeFile(imgDecodableString));
}
} else {
Toast.makeText(this, "You haven't picked Image",Toast.LENGTH_LONG).show();
}
}
Image is shown in the ImageView but is not sent to the server as it is thrown a FileNotFoundException.
private String uploadFile() {
Log.e("upload File", "called");
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
Log.e("URL", url_create_new_group);
HttpPost httppost = new HttpPost(url_create_new_group);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(new AndroidMultiPartEntity.ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
// Adding file data to http body
if (val == 0) {
if (fileUri != null) {
Log.e("val = ", String.valueOf(val));
File sourceFile = new File(fileUri.getPath());
if (sourceFile != null) {
Log.e("SoureFile", String.valueOf(sourceFile));
photosize = 0;
entity.addPart("image", new FileBody(sourceFile));
} else {
photosize = 1;
Toast.makeText(NewGroupActivity.this, "Please Upload Your Image", Toast.LENGTH_LONG).show();
}
}
} else {
File sourceFile = new File(picturePath);
if (sourceFile != null) {
photosize = 0;
entity.addPart("image", new FileBody(sourceFile));
} else {
photosize = 1;
Toast.makeText(NewGroupActivity.this, "Please Upload Your Image", Toast.LENGTH_LONG).show();
}
}
totalSize = entity.getContentLength();
Log.e("Total Size", String.valueOf(totalSize));
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: " + statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
return responseString;
}
Please check the code.
Solved
Updated Working Code:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
launchUploadActivity(true);
} else if (requestCode == RESULT_LOAD_IMG) {
Uri uri = data.getData();
//File file = new File(getRealPathFromURI(NewGroupActivity.this,uri));
//fileUri = Uri.fromFile(file);
Log.e("FileUriImageGallery", String.valueOf(uri));
String[] filePathColumn = {MediaStore.Images.Media.DATA};
// Get the cursor
Cursor cursor = getContentResolver().query(uri,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
ImageView imgView = (ImageView) findViewById(R.id.groupPic);
// Set the Image in ImageView after decoding the String
imgView.setImageBitmap(BitmapFactory
.decodeFile(imgDecodableString));
}
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
}
Related
As the title says, I am trying to upload images from both camera and gallery to firebase. But I have problems in both.
When I try to upload my image from the camera I get:
W/StorageUtil: no auth token for request
W/NetworkRequest: no auth token for request
Even though my firebase rules are:
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write;
}
}
}
But when I try using the gallery I get:
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference
at com.varroxsystems.plant.newPlant.Fileuploader(newPlant.java:192)
at com.varroxsystems.plant.newPlant.access$100(newPlant.java:57)
at com.varroxsystems.plant.newPlant$2.onClick(newPlant.java:162)
at android.view.View.performClick(View.java:7125)
at android.view.View.performClickInternal(View.java:7102)
at android.view.View.access$3500(View.java:801)
at android.view.View$PerformClick.run(View.java:27336)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
And I get no data in the firebase real time database nor in the firebase storage.
But I use this exact code on another application and it works just fine.
Does anyone know what am I doing wrong?
Code:
if (fragment3.isAdded()) {
EditText plantdetails = (EditText) fragment3.getView().findViewById(R.id.plantdetails);
if (plantdetails.getText().toString().equals("")) {
Toast.makeText(newPlant.this, "I think you forgot something.", Toast.LENGTH_LONG).show();
} else {
plants plants = new plants();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(newPlant.this);
prefs.edit().putString("pldetails", plantdetails.getText().toString()).apply();
String pname = prefs.getString("plname","null");
String pdate = prefs.getString("pldate","null");
String petails = prefs.getString("pldetails","null");
plants.setPlname(pname);
plants.setPldate(pdate);
plants.setPldetails(petails);
reference.child("Plants").child(pname).setValue(plants);
try {
Fileuploader();
}catch (FileNotFoundException e){
e.printStackTrace();
}
}
}
if (fragment4.isAdded()){
}
}
});
}
private void Fileuploader() throws FileNotFoundException {
String imageid;
progress.showProgress(newPlant.this,"Loading...",false);
DatabaseHelper databaseHelper = new DatabaseHelper(newPlant.this);
Cursor getimage = databaseHelper.GetPath();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(newPlant.this);
String plname = prefs.getString("plname","null");
int count = 0;
int count2 = 0;
if (getimage !=null){
while (getimage.moveToNext()) {
Bitmap bm = BitmapFactory.decodeFile(getimage.getString(0));
ByteArrayOutputStream out = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 35, out);
imageid = System.currentTimeMillis() + "_" + (count++) + "." + getExtension(uri);
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Plants").child(plname).child("PlantImages");
String imagekey = reference.push().getKey();
reference.child(imagekey).child("ImageID").setValue(imageid);
reference.child(imagekey).child("ID").setValue(count2++);
System.out.println("IMAGES UPLOADEDDDD: " + imageid);
byte[] data = out.toByteArray();
StorageReference Ref = mStorageRef.child(imageid);
Ref.putBytes(data)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Get a URL to the uploaded content
//Uri downloadUrl = taskSnapshot.getDownloadUrl();
//Toast.makeText(profuctadd.this,"Image uploaded",Toast.LENGTH_LONG).show();
progress.hideProgress();
Intent intent = new Intent(newPlant.this, Donenewplant.class);
startActivity(intent);
finish();
DatabaseHelper mDatabaseHelper = new DatabaseHelper(newPlant.this);
Cursor cursor2 = mDatabaseHelper.DeleteDataOfTableImagesAr();
cursor2.moveToNext();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
// ...
Toast.makeText(newPlant.this, "Failed", Toast.LENGTH_LONG).show();
}
});
}
}
}
private String getExtension(Uri uri)
{
ContentResolver cr=getContentResolver();
MimeTypeMap mimeTypeMap=MimeTypeMap.getSingleton();
return mimeTypeMap.getExtensionFromMimeType(cr.getType(uri));
}
#RequiresApi(api = Build.VERSION_CODES.M)
private void askFileReadPermission() {
if (ContextCompat.checkSelfPermission(newPlant.this,
Manifest.permission.READ_EXTERNAL_STORAGE) + ContextCompat
.checkSelfPermission(newPlant.this,
Manifest.permission.CAMERA) + ContextCompat
.checkSelfPermission(newPlant.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale
(newPlant.this, Manifest.permission.READ_EXTERNAL_STORAGE) ||
ActivityCompat.shouldShowRequestPermissionRationale
(newPlant.this, Manifest.permission.CAMERA)||ActivityCompat.shouldShowRequestPermissionRationale
(newPlant.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Snackbar.make(newPlant.this.findViewById(android.R.id.content),
"Please Grant Permissions to upload plant photo",
Snackbar.LENGTH_INDEFINITE).setAction("ENABLE",
new View.OnClickListener() {
#Override
public void onClick(View v) {
requestPermissions(
new String[]{Manifest.permission
.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE},
PERMISSIONS_MULTIPLE_REQUEST);
}
}).show();
} else {
requestPermissions(
new String[]{Manifest.permission
.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE},
PERMISSIONS_MULTIPLE_REQUEST);
}
} else {
alert();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case PERMISSIONS_MULTIPLE_REQUEST:
if (grantResults.length > 0) {
boolean cameraPermission = grantResults[1] == PackageManager.PERMISSION_GRANTED;
boolean readExternalFile = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean writeExternalFile = grantResults[0] == PackageManager.PERMISSION_GRANTED;
if(cameraPermission && readExternalFile && writeExternalFile)
{
alert();
} else {
Snackbar.make(newPlant.this.findViewById(android.R.id.content),
"Please Grant Permissions to upload plant photo",
Snackbar.LENGTH_INDEFINITE).setAction("ENABLE",
new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(View v) {
requestPermissions(
new String[]{Manifest.permission
.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE},
PERMISSIONS_MULTIPLE_REQUEST);
}
}).show();
}
}
break;
}
}
private void alert() {
new androidx.appcompat.app.AlertDialog.Builder(newPlant.this)
.setTitle(null)
.setMessage("Where would you like to get your picture from?")
// Specifying a listener allows you to take an action before dismissing the dialog.
// The dialog is automatically dismissed when a dialog button is clicked.
.setPositiveButton("Open Camera", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dispatchTakePictureIntent();
}
})
// A null listener allows the button to dismiss the dialog and take no further action.
.setNegativeButton("Open Gallery", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent gallery = new Intent();
gallery.setType("image/*");
gallery.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
gallery.setAction(Intent.ACTION_PICK);
startActivityForResult(Intent.createChooser(gallery,"Select Picture"), GALLERY_REQUEST_CODE);
}
})
.setIcon(android.R.drawable.ic_menu_camera)
.show();
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
File f = new File(currentPhotoPath);
Log.d("tag", "ABsolute Url of Image is " + Uri.fromFile(f));
DatabaseHelper databaseHelper = new DatabaseHelper(newPlant.this);
databaseHelper.SavingimagepathAR(Uri.fromFile(f).getPath());
plantimage.setScaleType(ImageView.ScaleType.CENTER_CROP);
plantimage.setBackground(getResources().getDrawable(R.drawable.imageproadd));
plantimage.setClipToOutline(true);
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(f);
uri = Uri.fromFile(f);
mediaScanIntent.setData(uri);
this.sendBroadcast(mediaScanIntent);
System.out.println(databaseHelper.getProfilesCount());
//uri = Uri.parse(cursor22.getString(0));
plantimage.setImageURI(uri);
}
}
if (requestCode == GALLERY_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
if (data != null){
if (data.getClipData() != null) {
ClipData mClipData = data.getClipData();
for (int i = 0; i < mClipData.getItemCount(); i++) {
ClipData.Item item = mClipData.getItemAt(i);
Uri curi = item.getUri();
uri = item.getUri();
File imageFile = new File(getRealPathFromURI(newPlant.this, curi));
//mArrayUri.add();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "." + getFileExt(curi);
DatabaseHelper databaseHelper = new DatabaseHelper(newPlant.this);
databaseHelper.SavingimagepathAR(Uri.fromFile(imageFile).getPath());
Log.d("tag", "onActivityResult: Gallery Image Uri: " + Uri.fromFile(imageFile));
// DatabaseHelper mDatabaseHelper = new DatabaseHelper(profuctadd.this);
// Cursor cursor22 = mDatabaseHelper.GetPath();
// while (cursor22.moveToNext()){
// System.out.println("SELECTED " + cursor22.getString(i));
// }
plantimage.setScaleType(ImageView.ScaleType.CENTER_CROP);
plantimage.setBackground(getResources().getDrawable(R.drawable.imageproadd));
plantimage.setClipToOutline(true);
//uri = Uri.parse(cursor22.getString(0));
plantimage.setImageURI(uri);
}
Log.v("LOG_TAG", "Selected Images ");
}else {
//Toast.makeText(profuctadd.this,"NO IMAGE EXCEPTION",Toast.LENGTH_LONG).show();
System.out.println(data.getData());
if (data.getData()!=null){
Uri contentUri = data.getData();
uri = data.getData();
System.out.println("CONTENT URI "+contentUri);
File imageFile = new File(getRealPathFromURI(newPlant.this, uri));
System.out.println("FILE "+imageFile);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "." + getFileExt(uri);
DatabaseHelper databaseHelper = new DatabaseHelper(newPlant.this);
databaseHelper.SavingimagepathAR(Uri.fromFile(imageFile).getPath());
Log.d("tag", "onActivityResult: Gallery Image Uri: " + Uri.fromFile(imageFile));
//DatabaseHelper mDatabaseHelper = new DatabaseHelper(profuctadd.this);
//Cursor cursor22 = mDatabaseHelper.GetPath();
plantimage.setScaleType(ImageView.ScaleType.CENTER_CROP);
plantimage.setBackground(getResources().getDrawable(R.drawable.imageproadd));
plantimage.setClipToOutline(true);
//uri = Uri.parse(cursor22.getString(0));
plantimage.setImageURI(uri);
}
}
// }
}
}
}
}
private String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = {MediaStore.Images.Media.DATA};
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} catch (Exception e) {
Log.e(TAG, "getRealPathFromURI Exception : " + e.toString());
return "";
} finally {
if (cursor != null) {
cursor.close();
}
}
}
private String getFileExt(Uri contentUri) {
ContentResolver c = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(c.getType(contentUri));
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
// File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = image.getAbsolutePath();
return image;
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
ex.printStackTrace();
Toast.makeText(newPlant.this,ex.getMessage(),Toast.LENGTH_LONG).show();
return;
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.varroxsystems.plant.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
}
}
}
I created my OwnCloud server with Oracle VirtualBox Debian. I want my Android application to upload image to the cloud. So i created intent to get image from the Gallery and to upload it with the OwnCloud Android library from GitHub: https://github.com/owncloud/android-library
. I followed the steps from the sample but every time when i start uploading, the result is 404 - FILE_NOT_FOUND
Here is a snippet of my code:
floatingActionButton.setOnClickListener(v -> {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType(IMAGE_INTENT);
startActivityForResult(photoPickerIntent, RESULT_LOAD_IMG);
});
}
#Override
protected void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
if (resultCode == RESULT_OK) {
try {
final Uri imageUri = data.getData();
final InputStream imageStream = getContentResolver().openInputStream(imageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
profilePicture.setImageBitmap(selectedImage);
File file = new File(getRealPathFromURI(imageUri));
Log.d("Image file", file.getAbsolutePath() + "\t" + file.getName());
handler = new Handler();
Uri serverUri = Uri.parse("http://192.168.1.8/remote.php/webdav/");
client = OwnCloudClientFactory.createOwnCloudClient(serverUri, this, true);
client.setCredentials(OwnCloudCredentialsFactory.newBasicCredentials("user", "bitnami"));
client.getParams().setAuthenticationPreemptive(true);
String remotePath = FileUtils.PATH_SEPARATOR + file.getName();
String mimeType = "image/png";
// Get the last modification date of the file from the file system
Long timeStampLong = file.lastModified() / 1000;
String timeStamp = timeStampLong.toString();
UploadRemoteFileOperation uploadOperation = new UploadRemoteFileOperation(file.getAbsolutePath(), remotePath, mimeType, timeStamp);
uploadOperation.addDatatransferProgressListener(this);
uploadOperation.execute(client, this, handler);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
private String getRealPathFromURI(Uri contentURI) {
String result;
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) {
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
}
#Override
public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer, String fileAbsoluteName) {
final long percentage = (totalToTransfer > 0 ? totalTransferredSoFar * 100 / totalToTransfer : 0);
handler.post(() -> Log.d("Progress", "progressRate " + percentage));
}
#Override
public void onRemoteOperationFinish(RemoteOperation caller, RemoteOperationResult result) {
Toast.makeText(this, String.valueOf(result.getHttpCode()), Toast.LENGTH_SHORT).show();
}
I have a problem with Uri object. User should take a photo and next this is sending to Firebase Storage. But sth is wrong with onActivityResult.
I read a lot of topics (https://developer.android.com/training/camera/photobasics.html, StackOverFlow too) but nothing works with this code.
There is an error:
Attempt to invoke virtual method 'java.lang.String android.net.Uri.getLastPathSegment()' on a null object reference
Below is a code:
mUploadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, CAMERA_REQUEST_CODE);
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK && data != null) {
mProgress.setMessage("Uploading Image...");
mProgress.show();
Uri uri = data.getData();
StorageReference filepath = mStorage.child("Photos").child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
mProgress.dismiss();
Uri downloadUri = taskSnapshot.getDownloadUrl();
Picasso.with(MainActivity.this).load(downloadUri).fit().centerCrop().into(mImageView);
Toast.makeText(MainActivity.this, "Upload Done.", Toast.LENGTH_LONG).show();
}
});
}
}
}
As I checked, data (Intent) in onActivityResult is equal to NULL, so uri is null as well.
So, how can I resolve this challenge and make it usable? Should I use a Bitmap to have an access to a photo?
Could someone help me to resolve this situation?
Regards
I figured out with my question.
It works at now.
private ProgressDialog mProgress;
private Button mUploadBtn;
private ImageView mImageView;
Uri picUri;
private StorageReference mStorage;
private static final int CAMERA_REQUEST_CODE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mStorage = FirebaseStorage.getInstance().getReference();
mUploadBtn = (Button) findViewById(R.id.uploadBtn);
mImageView = (ImageView) findViewById(R.id.imageView);
mProgress = new ProgressDialog(this);
mUploadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File file=getOutputMediaFile(1);
picUri = Uri.fromFile(file); // create
i.putExtra(MediaStore.EXTRA_OUTPUT,picUri); // set the image file
startActivityForResult(i, CAMERA_REQUEST_CODE);
}
});
}
/** Create a File for saving an image */
private File getOutputMediaFile(int type){
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyApplication");
/**Create the storage directory if it does not exist*/
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
/**Create a media file name*/
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == 1){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".png");
} else {
return null;
}
return mediaFile;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK ) {
mProgress.setMessage("Uploading Image...");
mProgress.show();
Uri uri = picUri;
StorageReference filepath = mStorage.child("Photos").child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
mProgress.dismiss();
Uri downloadUri = taskSnapshot.getDownloadUrl();
Picasso.with(MainActivity.this).load(downloadUri).fit().centerCrop().into(mImageView);
Toast.makeText(MainActivity.this, "Upload Done.", Toast.LENGTH_LONG).show();
}
});
}
}
Always create your file and store the captured image using the path as follows
File photoFile = null;
mUploadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null) {
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
ex.printStackTrace();
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
}
}
});
}
private File createImageFile() throws IOException {
// Create an image mSelectedFile name
String timeStamp = new SimpleDateFormat(Constants.PHOTO_DATE_FORMAT, Locale.ENGLISH).format(new Date());
String imageFileName = "IMG_" + timeStamp;
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File file = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
return file;
}
Then use this file "photoFile" and use it as needed in onActivityResult.
I faced the same problem before so i made sure that i check everything i can check when onActivityResult is called below is my code.
First i use this intent to capture image
File photoFile;
URI uri;
mUploadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePhotoIntent.resolveActivity(getPackageManager()) != null)
{
try
{
photoFile = Create_ImageFile();
}
catch (Exception e)
{
Log.e("file", e.toString());
}
if (photoFile != null)
{
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile.getAbsoluteFile()));
}
}
startActivityForResult(takePhotoIntent, CAMERA_REQUEST_CODE);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent)
{
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case CAMERA_REQUEST_CODE:
if (resultCode == Activity.RESULT_OK)
{
try
{
Uri selectedImageURI = null;
ByteArrayOutputStream bos;
Bitmap bitmap = null;
int orientation;
ExifInterface exif = null;
FileOutputStream fos = null;
bos = new ByteArrayOutputStream();
try
{
uri=imageReturnedIntent.getData();
selectedImageURI = imageReturnedIntent.getData();
bitmap= BitmapFactory.decodeFile(GetRealPathFromURI(selectedImageURI));
exif = new ExifInterface(GetRealPathFromURI(selectedImageURI));
fos = new FileOutputStream(GetRealPathFromURI(selectedImageURI));
}
catch (Exception e)
{
e.printStackTrace();
}
if(bitmap==null)
{
uri=Uri.fromFile(photoFile.getAbsoluteFile()));
bitmap=BitmapFactory.decodeFile(photoFile.getAbsolutePath());
exif = new ExifInterface(photoFile.getAbsolutePath());
fos = new FileOutputStream(photoFile.getAbsolutePath());
}
if(bitmap==null)
{
String imagePath = getPathGalleryImage(imageReturnedIntent);
bitmap = BitmapFactory.decodeFile(imagePath);
exif = new ExifInterface(imagePath);
fos = new FileOutputStream(imagePath);
}
Log.e("PhotoFile",photoFile.getAbsolutePath());
// Bitmap bitmap =(Bitmap) imageReturnedIntent.getExtras().get("data");
//bitmap = Bitmap.createScaledBitmap(bitmap,bitmap.getWidth(),bitmap.getHeight(), false);
orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
Log.e("ExifInteface .........", "rotation ="+orientation);
//exif.setAttribute(ExifInterface.ORIENTATION_ROTATE_90, 90);
Log.e("orientation", "" + orientation);
Matrix m = new Matrix();
if ((orientation == ExifInterface.ORIENTATION_ROTATE_180)) {
m.postRotate(180);
//m.postScale((float) bm.getWidth(), (float) bm.getHeight());
// if(m.preRotate(90)){
Log.e("in orientation", "" + orientation);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),bitmap.getHeight(), m, true);
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
m.postRotate(90);
Log.e("in orientation", "" + orientation);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),bitmap.getHeight(), m, true);
}
else if (orientation == ExifInterface.ORIENTATION_ROTATE_270)
{
m.postRotate(270);
Log.e("in orientation", "" + orientation);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),bitmap.getHeight(), m, true);
}
else
{
m.postRotate(0);
Log.e("in orientation", "" + orientation);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),bitmap.getHeight(), m, true);
}
//CropImage.activity(selectedImageURI).setGuidelines(CropImageView.Guidelines.ON).start(this);
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos);
userProfileIMG.setImageBitmap(bitmap);
StorageReference filepath = mStorage.child("Photos").child(uri.getLastPathSegment());
}
catch (Exception e)
{
e.printStackTrace();
}
}
break;
}
}
private String getPathGalleryImage(Intent imageURI)
{
Uri selectedImage = imageURI.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 imagePath = cursor.getString(columnIndex);
cursor.close();
return imagePath;
}
/**
* When image is returned we get its real path
**/
private String GetRealPathFromURI(Uri contentURI)
{
String result;
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) {
// Source is Dropbox or other similar local file path
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
}
private File Create_ImageFile() throws IOException
{
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
String imageFileName = "JPEG_" + timeStamp;
File mediaStorageDir = getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = new File(mediaStorageDir.getAbsolutePath() + File.separator + imageFileName);
return image;
}
after this process i always ended having a bitmap to use it as i want.
For Get Actual Image predefined path of Captured Image using
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
this.startActivityForResult(cameraIntent, 101);
After Captured Image you can get Captured Image on path which is set in cameraIntent. If you don't Want to set predefined path then check Intent data.
if (resultCode == android.app.Activity.RESULT_OK && requestCode == 101) {
try {
path_mm = "Onsuccess_resultcode";
generateNoteOnSD("photo34.txt", path_mm);
Bitmap photo = null;
if (data == null) {
//get Bitmap here.
}
else {
Uri u1 = data.getData();
//get uri and find actual path on that uri.
}
}catch(Exception ex)
{}}
So after trying many answers for the same question, here are just two e.g;
Saving an image in android
and
Saving an image to a server using a Java applet
My app still fails in fact whatever I have done has made it worse, before it would actually save the image as "temp.jpg" in the ExtSD root folder, now when I click the tick to accept the photo nothing happens, no crashing, no nothing, I can retake the image and I can cancel the taking of a photo but nothing else happens.
What it does now:
Opens the camera (or gallery)
Takes the photo
Fails to save/set the photo
What I want it to do;
Take the photo
Store it with a unique name (timestamp)
Have the image set to CircleView
Here is my code (if you need more please ask for what you need);
CircleImageView circleImageView;
ImageButton b;
private void selectImage() {
final CharSequence[] options = { "Take a Pic", "Choose from Gallery", "Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Set Profile Pic");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take a Pic"))
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
String folder_main = "iDealer";
String sub_folder = "ProPics";
String timeStamp = new SimpleDateFormat("ddMMyyy_HHmmss").format(Calendar.getInstance().getTime());
String pro_pic_name = folder_main + "_" + timeStamp;
File f = new File(android.os.Environment.getExternalStorageDirectory() + "/" + folder_main + "/" + sub_folder + pro_pic_name);
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);
circleImageView.setImageBitmap(bitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "iDealer" + 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);
if (c != null) {
c.moveToFirst();
}
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Log.w("path from gallery = ", picturePath+"");
circleImageView.setImageBitmap(thumbnail);
}
}
}
I am new in android so, if you found any mistake please tell me.Now come to the point what i got the problem we click on image view then one popup will come and choose from where you want to upload the image so when we click on gallery then.
mProfileImageView.setOnClickListener(new View.OnClickListener() {
#TargetApi(Build.VERSION_CODES.M)
#Override
public void onClick(View v) {
new AlertDialog.Builder(ProfileActivity.this)
.setTitle("Profile Picture")
.setMessage("change your profile picture with")
.setPositiveButton(R.string.capture_image, new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// continue with delete
captureImage();
}
})
*//*.setNegativeButton(R.string.choose_image, new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// do nothing
chooseImage();
}
})*//*
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
});
public void chooseImage() {
try {
Intent i = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
i.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, IMAGE_QUALITY_LOW);
i.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, 0);
i.putExtra(MediaStore.EXTRA_SIZE_LIMIT, IMAGE_MAX_SIZE);
i.setType("image/*");
//i.setAction(Intent.ACTION_GET_CONTENT);
/*i.putExtra("crop", "true");
i.putExtra("aspectX", 0);
i.putExtra("aspectY", 0);
i.putExtra("outputX", 400);
i.putExtra("outputY", 400);
i.putExtra("return-data", true);*/
startActivityForResult(Intent.createChooser(i, "Complete action using"), GALLERY_IMAGE_ACTIVITY_REQUEST_CODE);
} catch (ActivityNotFoundException anfe) {
//display an error message
String errorMessage = "Oops - your device doesn't have gallery!";
Toast.makeText(getApplicationContext(), errorMessage,
Toast.LENGTH_LONG).show();
}
}
When we are scrollingG 10-20 gallery images and going for upload at that time it's crashing i don't know why?
try this:
java code:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final int SELECT_PICTURE = 100;
private static final String TAG = "MainActivity";
CoordinatorLayout coordinatorLayout;
FloatingActionButton btnSelectImage;
AppCompatImageView imgView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Find the views...
coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorLayout);
btnSelectImage = (FloatingActionButton) findViewById(R.id.btnSelectImage);
imgView = (AppCompatImageView) findViewById(R.id.imgView);
btnSelectImage.setOnClickListener(this);
}
/* Choose an image from Gallery */
void openImageChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
// Get the url from data
Uri selectedImageUri = data.getData();
if (null != selectedImageUri) {
// Get the path from the Uri
String path = getPathFromURI(selectedImageUri);
Log.i(TAG, "Image Path : " + path);
// Set the image in ImageView
imgView.setImageURI(selectedImageUri);
}
}
}
}
/* Get the real path from the URI */
public String getPathFromURI(Uri contentUri) {
String res = null;
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
if (cursor.moveToFirst()) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
res = cursor.getString(column_index);
}
cursor.close();
return res;
}
#Override
public void onClick(View v) {
openImageChooser();
}
}
Add Permission
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<android.support.v7.widget.AppCompatImageView
android:id="#+id/imgView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="#dimen/activity_horizontal_margin" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/btnSelectImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_menu_gallery" />
</android.support.design.widget.CoordinatorLayout>
You are receiving an OutOfMemoryException since you are talking about several images. Here are your options:
Request a larger heap from the virtual machine by adding the following line into your AndroidManifest.xml in the application section: android:largeHeap="true"
Try to use images as small as possible for your gallery. Remeber: each image is stored uncompressed into your applications heap
Recycle images that are not visible at the moment using Bitmap.recycle() to free new memory.
Try this java code it works. I used it recently in my android app
Pop up
PopupWindow popup;
private void initiatePopupWindow() {
// TODO Auto-generated method stub
try {
LayoutInflater inflater = (LayoutInflater) getBaseContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.change_profileimg, null);
popup = new PopupWindow(layout, android.view.ViewGroup.LayoutParams.MATCH_PARENT,
android.view.ViewGroup.LayoutParams.MATCH_PARENT);
Button imagefromgallery = (Button) layout
.findViewById(R.id.imagefromgallery);
RelativeLayout relPopup = (RelativeLayout) layout.findViewById(R.id.relativeLayoutMainPopup);
Button captureimage = (Button) layout
.findViewById(R.id.captureimage);
imagefromgallery.setTypeface(Typeface.createFromAsset(getAssets(),
"fonts/OpenSans-Regular.ttf"));
captureimage.setTypeface(Typeface.createFromAsset(getAssets(),
"fonts/OpenSans-Regular.ttf"));
imagefromgallery.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
galleryPick();
popup.dismiss();
}
});
captureimage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// takePhoto();
callCameraApp();
popup.dismiss();
}
});
relPopup.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
popup.dismiss();
}
});
popup.setOutsideTouchable(true);
popup.setTouchInterceptor(new OnTouchListener() {
#Override
public boolean onTouch(View arg0, MotionEvent event) {
// TODO Auto-generated method stub
if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
popup.dismiss();
return true;
}
return false;
}
});
popup.showAtLocation(layout, Gravity.BOTTOM, 0, 0);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
Gallery pick
private void galleryPick() {
try {
Intent gintent = new Intent();
gintent.setType("image/*");
gintent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(gintent, "Select Picture"), PICK_IMAGE);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(),
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
Call camera app
private void callCameraApp() {
Intent i = new Intent();
i.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
String fileName = "new-photo-name.jpg";
ContentValues values = new ContentValues();
values.put(MediaColumns.TITLE, fileName);
values.put(ImageColumns.DESCRIPTION, "Image captured by camera");
// imageUri is the current activity attribute, define and save it for
// later usage (also in onSaveInstanceState)
imageUri = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
try {
fileName = getPath(imageUri);
} catch (Exception e) {
// TODO: handle exception
}
i.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(i, PICK_Camera_IMAGE1);
}
then to get the bitmap
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"XYZ_");
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("errorrr", "Oops! Failed create "
+ "XYZ_" + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".png");
return mediaFile;
}
String filePath;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Uri selectedImageUri = null;
Uri selectedImagepicUri = null;
filePath = null;
switch (requestCode) {
case PICK_Camera_IMAGE:
if (resultCode == RESULT_OK) {
// use imageUri here to access the image
selectedImageUri = imageUri;
/*
* Bitmap mPic = (Bitmap) data.getExtras().get("data");
* selectedImageUri =
* Uri.parse(MediaStore.Images.Media.insertImage
* (getContentResolver(), mPic,
* getResources().getString(R.string.app_name),
* Long.toString(System.currentTimeMillis())));
*/
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "Picture was not taken",
Toast.LENGTH_SHORT).show();
}
break;
case PICK_Camera_IMAGE1:
if (resultCode == RESULT_OK) {
// use imageUri here to access the image
selectedImagepicUri = imageUri;
/*
* Bitmap mPic = (Bitmap) data.getExtras().get("data");
* selectedImageUri =
* Uri.parse(MediaStore.Images.Media.insertImage
* (getContentResolver(), mPic,
* getResources().getString(R.string.app_name),
* Long.toString(System.currentTimeMillis())));
*/
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "Picture was not taken",
Toast.LENGTH_SHORT).show();
}
break;
case PICK_IMAGE:
if (resultCode == Activity.RESULT_OK) {
selectedImagepicUri = data.getData();
}
}
if (selectedImagepicUri != null) {
try {
// OI FILE Manager
String filemanagerstring = selectedImagepicUri.getPath();
// MEDIA GALLERY
String selectedImagePath = getPath(selectedImagepicUri);
if (selectedImagePath != null) {
filePath = selectedImagePath;
} else if (filemanagerstring != null) {
filePath = filemanagerstring;
} else {
Toast.makeText(getApplicationContext(), "Unknown path",
Toast.LENGTH_LONG).show();
Log.e("Bitmap", "Unknown path");
}
if (filePath != null) {
decodeFile1(filePath);
} else {
bitmap = null;
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Internal error",
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
if (selectedImageUri != null) {
try {
// OI FILE Manager
String filemanagerstring = selectedImageUri.getPath();
// MEDIA GALLERY
String selectedImagePath = getPath(selectedImageUri);
if (selectedImagePath != null) {
filePath = selectedImagePath;
} else if (filemanagerstring != null) {
filePath = filemanagerstring;
} else {
Toast.makeText(getApplicationContext(), "Unknown path",
Toast.LENGTH_LONG).show();
Log.e("Bitmap", "Unknown path");
}
if (filePath != null) {
decodeFile(filePath);
} else {
bitmap = null;
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Internal error",
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaColumns.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
// HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
// THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
public void decodeFile(String filePath) {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 512;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
bitmap = BitmapFactory.decodeFile(filePath, o2);
/**Bitmap.createScaledBitmap(bitmap, 200, 200, false);*/
if (bitmap == null) {
Toast.makeText(getApplicationContext(), "Please select image",
Toast.LENGTH_SHORT).show();
} else {
ivr.setImageBitmap(bitmap);
ivrIn.setImageBitmap(bitmap);
// new ImageGalleryTask().execute();
}
}
public void decodeFile1(String filePath) {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 512;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
bitmap = BitmapFactory.decodeFile(filePath, o2);
/**Bitmap.createScaledBitmap(bitmap, 200, 200, false);*/
if (bitmap == null) {
Toast.makeText(getApplicationContext(), "Please select image",
Toast.LENGTH_SHORT).show();
} else {
ivr.setImageBitmap(bitmap);
ivrIn.setImageBitmap(bitmap);
// new ImageGalleryTask().execute();
}
}
Async task to upload image
private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
#Override
protected void onPreExecute() {
// setting progress bar to zero
progressDialog = new ProgressDialog(Profile.this);
//progressDialog.setTitle("Fetching data");
progressDialog.setMessage("Uploading profile pic, Please Wait....");
progressDialog.show();
progressDialog.setCancelable(false);
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
// Making progress bar visible
System.out.println("progress update "+progress[0]);
// progressBar.setVisibility(View.VISIBLE);
// updating progress bar value
// progressBar.setProgress(progress[0]);
// updating percentage value
// txtPercentage.setText(String.valueOf(progress[0]) + "%");
}
#Override
protected String doInBackground(Void... params) {
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
int count;
try
{
FileInputStream fileInputStream = new FileInputStream(new File(filePath));
URL url = new URL("url");
System.out.println("url "+url);
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs.
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// Set HTTP method to POST.
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
outputStream = new DataOutputStream( connection.getOutputStream() );
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"image\";filename=\"" + filePath + "\"" + lineEnd);
Log.e("chhuuuh", filePath + System.currentTimeMillis());
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
responseString = connection.getResponseMessage();
fileInputStream.close();
outputStream.flush();
outputStream.close();
InputStream is = null;
try {
is = connection.getInputStream();
int ch;
StringBuffer sb = new StringBuffer();
while ((ch = is.read()) != -1) {
sb.append((char) ch);
}
return sb.toString();
} catch (IOException e) {
throw e;
} finally {
if (is != null) {
is.close();
}
}
}
catch (Exception ex)
{
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
String result1 = result;
Log.e("respons form server", "response from server: " + result);
if(progressDialog.isShowing())
{
progressDialog.dismiss();
}
try {
JSONObject json = new JSONObject(result);
int response = json.getInt("status_code");
if(response == 1)
{
if (result1.contains("null")) {
Toast.makeText(getApplicationContext(), "You didn't change the image, please choose an image from gallery or click from the camera.", 2000).show();
} else {
JSONObject arr = json.getJSONObject("details");
String erer = arr.getString("error");
String message = arr.getString("message");
Toast.makeText(getApplicationContext(), message, 1000).show();
}
}
else
{
showAlert("Error Uploading Image, Please try again!!!");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.onPostExecute(result);
}
}
get the correct path
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
// TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] {
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* #param context The context.
* #param uri The Uri to query.
* #param selection (Optional) Filter used in the query.
* #param selectionArgs (Optional) Selection arguments used in the query.
* #return The value of the _data column, which is typically a file path.
*/
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
final int index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is ExternalStorageProvider.
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is DownloadsProvider.
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is MediaProvider.
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is Google Photos.
*/
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
Permissions for 6.0 and above versions
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
Log.d("", "Permission callback called-------");
switch (requestCode) {
case REQUEST_ID_MULTIPLE_PERMISSIONS: {
Map<String, Integer> perms = new HashMap<String, Integer>();
// Initialize the map with both permissions
perms.put(Manifest.permission.CAMERA, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.CALL_PHONE, PackageManager.PERMISSION_GRANTED);
// Fill with actual results from user
if (grantResults.length > 0) {
for (int i = 0; i < permissions.length; i++)
perms.put(permissions[i], grantResults[i]);
// Check for both permissions
if (perms.get(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
Log.d("", " permission granted");
// process the normal flow
//else any one or both the permissions are not granted
} else {
Log.d("", "Some permissions are not granted ask again ");
//permission is denied (this is the first time, when "never ask again" is not checked) so ask again explaining the usage of permission
// shouldShowRequestPermissionRationale will return true
//show the dialog or snackbar saying its necessary and try again otherwise proceed with setup.
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)
|| ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
|| ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)
|| ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CALL_PHONE)) {
showDialogOK("This app have camera functionality so Camera and Write External Storage Permission required for this app",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
checkAndRequestPermissions();
break;
case DialogInterface.BUTTON_NEGATIVE:
// proceed with logic by disabling the related features or quit the app.
Toast.makeText(getApplicationContext(), "Please go to settings and enable permissions.", 2000).show();
break;
}
}
});
}
//permission is denied (and never ask again is checked)
//shouldShowRequestPermissionRationale will return false
else {
Toast.makeText(this, "Go to settings and enable permissions", Toast.LENGTH_LONG)
.show();
// //proceed with logic by disabling the related features or quit the app.
}
}
}
}
}
}
private void showDialogOK(String message, DialogInterface.OnClickListener okListener) {
new AlertDialog.Builder(this)
.setMessage(message)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", okListener)
.create()
.show();
}
private boolean checkAndRequestPermissions() {
int permissionCamera = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
int locationPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
int permissionWriteExternal = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
int permissionCallPhone = ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE);
List<String> listPermissionsNeeded = new ArrayList<String>();
if (permissionCamera != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.CAMERA);
}
if (locationPermission != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION);
}
if (permissionWriteExternal != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
if (permissionCallPhone != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.CALL_PHONE);
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),REQUEST_ID_MULTIPLE_PERMISSIONS);
return false;
}
return true;
}
I know this code is too long to read but this is exactly what you want