Android capture image and get actual path - android

I want to create an application that takes picture/video and send it to my FTP server.
Here is my onActivityResult code;
#Override
protected void onActivityResult(int requestCode, int resultCode,final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PHOTO_CAPTURE && resultCode == RESULT_OK) {
// Upload sdcard file
new AsyncTask(){
#Override
protected Object doInBackground(Object[] params) {
File f = new File(data.getData() + "");
try {
uploadFile(f);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}.execute();
// Toast.makeText(this, "Photo saved to:\n" + data.getData(), Toast.LENGTH_LONG).show();
}
if (requestCode == VIDEO_CAPTURE && resultCode == RESULT_OK) {
// Upload sdcard file
new AsyncTask(){
#Override
protected Object doInBackground(Object[] params) {
File f = new File(data.getData() + "");
try {
uploadFile(f);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}.execute();
// Toast.makeText(this, "Video saved to:\n" + data.getData(), Toast.LENGTH_LONG).show();
}
}
Error says no such file or directory. How can I get the actual path of a video or an image taken?
Thank you for your time.
EDIT - EDIT - EDIT
I have used another method to get the path
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
Now I don't get any error but when I open my ftp folder I cant see the uploaded image :S
Here is my uploadFile method;
public void uploadFile(File fileName) throws IOException {
SimpleFTP ftp = new SimpleFTP();
// Connect to an FTP server on port 21.
ftp.connect(server, port, user, pass);
// Set binary mode.
ftp.bin();
// Change to a new working directory on the FTP server.
ftp.cwd("upload");
// Upload some files.
ftp.stor(fileName.getAbsoluteFile());
// Quit from the FTP server.
ftp.disconnect();
}

you have to use getAbsolutePath() from File object it returns path of the file.

Change this code from you activity, see below:
if (requestCode == VIDEO_CAPTURE && resultCode == RESULT_OK) {
// Upload sdcard file
new AsyncTask(){
#Override
protected Object doInBackground(Object[] params) {
try {
//Create a empty file what you want...
File f = new File("Write here your path what you want");
//Open OutputStream
FileOutputStream fos = new FileOutputStream(f);
//Write file
fos.write(data);
//File is created in your path
uploadFile(f);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}.execute();
// Toast.makeText(this, "Video saved to:\n" + data.getData(), Toast.LENGTH_LONG).show();
}
Tell me if I helped you with this changes and good programming!

Related

For a camera activity, result code is -1 in onActivityResult(). How to proceed debugging?

None of the submissions here deal with negative result code. I know it means that the task failed, but I have no idea how or why it failed. The app opens the camera and I'm able to take a picture.
btnN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
captureImage(v);
}
});
The function definitions are as given below.
public void captureImage(View view) {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.resolveActivity(getPackageManager()) != null) {
File imageFile = null;
try {
imageFile = getImageFile();
} catch (IOException e) {
e.printStackTrace();
}
if (imageFile != null) {
Uri imageUri = FileProvider.getUriForFile(this, "com.example.testingproject.fileprovider", imageFile);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(cameraIntent, 1);
}
System.out.println("imageFile length:" + imageFile.length());
}
}
In the above function, I've even tried sending request code as 2. Same functionality, I'm able to click a picture, but same issue.
public File getImageFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmsss").format(new Date());
String imageName = "jpg_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File imageFile = File.createTempFile(imageName, ".jpg", storageDir);
currentImagePath = imageFile.getAbsolutePath();
System.out.println("currImPath: " + currentImagePath);
return imageFile;
}
The much needed onActivityResult() code is below
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
try {
System.out.println("reqCode: "+requestCode+" resCode: "+resultCode);
switch (requestCode) {
case 0: {
if (resultCode == RESULT_OK) {
File file = new File(currentImagePath);
Bitmap bitmap = MediaStore.Images.Media.getBitmap(MainActivity.this.getContentResolver(), Uri.fromFile(file));
if (bitmap != null) {
//...Do your stuffs
Toast.makeText(MainActivity.this, "Bitmap NOT null", Toast.LENGTH_SHORT).show();
imgView.setImageBitmap(bitmap);
}
else
{
Toast.makeText(MainActivity.this,"BitmapNull",Toast.LENGTH_SHORT).show();
}
}
break;
}
default: Toast.makeText(MainActivity.this,"result code not okay",Toast.LENGTH_SHORT).show(); break;
}
} catch (Exception error) {
error.printStackTrace();
}
}
The sysout in log is below
2020-05-01 13:52:24.644 10014-10014/com.example.testingproject I/System.out: reqCode: 1 resCode: -1
-1 is equal to RESULT_OK. It means the task completed successfully
When you look into the code. -1 is actully status code for RESULT_OK
public static final int RESULT_OK = -1;
Now you've set requestCode as 1 in this line
startActivityForResult(cameraIntent, 1);
So in your OnActivityResult which shows
reqCode: 1 resCode: -1
is Correct.

Android get filesize after take camera?

How can i get file size after take camera.
I run the code the following results:filesize is 0.I think that the Camera InputStream is writing.But how can I get the real file size?
private void takeCamera(){
file = File.createTempFile("tp_", ".jpg", dir);
filePathCamera = file.getAbsolutePath();
Uri uri = Uri.fromFile(file);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(intent, REQUEST_CODE_CAMERA);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case REQUEST_CODE_CAMERA:
final File file = new File(filePathCamera);
if (!file.exists()) {
result.append("not exists\n");
return;
}
InputStream inputStream = null;
try {
inputStream = new FileInputStream(filePathCamera);
long size = inputStream.available();
result.append("size1:" + size + "\n");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException ioe) {
ioe.printStackTrace();
// ignore
}
}
break;
}
}
}
In onActivityResult in case REQUEST_CODE_CAMERA: after checking if !file.exists() you can check in else part file.length which will give you size of file.

Saving an image file is too slow to immediately show it in an Imageview

In my app I save an image file (a pictures taken from camera phone) but sometimes I get an error if I want to show its thumbnail immediately in an Imageview. Why? Is saving process too slow? Could I use an alternative in order to save my image file?
Here I call my camera:
camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
Log.v("Crea file Immagine", "IOException");
}
// Continue only if the File was successfully created
if (photoFile != null) {
Log.v("photofile",String.valueOf(photoFile));
Uri mSelectedImageUri= Uri.fromFile(photoFile);
Log.v("mSelectedImageUri", String.valueOf(mSelectedImageUri));
intent.putExtra(MediaStore.EXTRA_OUTPUT, mSelectedImageUri);
startActivityForResult(intent, CAMERA_REQUEST);
}
}
}
});
Here I save my image file:
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
sharedPreference.save(context,"nomeFile",timeStamp);
File storageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM) + File.separator + "BottiglieDiVino");
boolean success;
if (!storageDir.exists()) {
success = storageDir.mkdir();
if (success) {
// Do something on success
Log.v("Crea /BottiglieDiVino", "Ho Creato nuova directory");
} else {
// Do something else on failure
Log.v("Crea /BottiglieDiVino", "ERRORE nel creare nuova directory");
}
}
File image = new File(storageDir, timeStamp + ".jpg");
// Save a file: path for use with ACTION_VIEW intents
percorso = image.getAbsolutePath();
sharedPreference.save(context,"percorso", percorso);
Log.v("percorso", percorso);
return image;
}
and here I get this error
java.io.FileNotFoundException: /: open failed: EISDIR (Is a directory)
libcore.io.IoBridge.open(IoBridge.java:409)
java.io.FileInputStream.<init>(FileInputStream.java:78)
java.io.FileInputStream.<init>(FileInputStream.java:105)
android.content.ContentResolver.openInputStream(ContentResolver.java:630)
com.example.android.swipetabs.FragmentTab2.decodeSampledBitmapFromUri(FragmentTab2.java:
p.s. in the last line :) is the error.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
percorso = sharedPreference.getValue(context, "percorso");
sharedPreference.save(context,"check23", "ok");
Log.v("percorso", percorso);
foto.setImageBitmap(display(percorso));
}
}
public Bitmap decodeSampledBitmapFromUri(Uri uri, int reqWidth, int reqHeight) {
try {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(getActivity().getContentResolver().openInputStream(uri), null, options);
please help me.
Note:Give these permission run time for marashmallow or above and put your code when permission granted in your other devices it's work fine
In mainfest
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
runtime
public static final int REQUEST_ID_MULTIPLE_PERMISSIONS = 10;
camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
permissions= new String[]{
Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE};
if (checkPermissions())
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(demo.this.getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
Log.v("Crea file Immagine", "IOException");
}
// Continue only if the File was successfully created
if (photoFile != null) {
Log.v("photofile",String.valueOf(photoFile));
Uri mSelectedImageUri= Uri.fromFile(photoFile);
Log.v("mSelectedImageUri", String.valueOf(mSelectedImageUri));
intent.putExtra(MediaStore.EXTRA_OUTPUT, mSelectedImageUri);
startActivityForResult(intent, CAMERA_REQUEST);
}
}
}
}
});
private boolean checkPermissions() {
int result;
List<String> listPermissionsNeeded = new ArrayList<>();
for (String p:permissions) {
result = ContextCompat.checkSelfPermission(this,p);
if (result != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(p);
}
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),REQUEST_ID_MULTIPLE_PERMISSIONS);
return false;
}
return true;
}

Android CSV Path is throwing FileNotFoundExpception

I want to import csv from external storage and then update my database but when I am selecting that csv from downloaded folder FileNotFoundExpception comes. Here is the exception System.err:
java.io.FileNotFoundException: /document/primary:Download/GuestCSV.csv: open failed: ENOENT (No such file or directory)
Here is my code. Kindly review my code and help me to find a solution.
importDatabase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("text/*");
startActivityForResult(Intent.createChooser(intent, "Open CSV"), ACTIVITY_CHOOSE_FILE);
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case ACTIVITY_CHOOSE_FILE: {
if (resultCode == RESULT_OK) {
onImport(new File(data.getData().getPath()));
Log.d(TAG, data.getData().getPath());
}
}
}
}
public void onImport(File files) {
try {
String[] nextLine;
try {
CSVReader reader = new CSVReader(new FileReader(files.getAbsolutePath()));
while ((nextLine = reader.readNext()) != null) {
// nextLine[] is an array of values from the line
String emailID = nextLine[0];
String guestName = nextLine[1];
String guestSource = nextLine[2];
String guestPhone = nextLine[3];
String guestCount = nextLine[4];
String guestCreatedDate = nextLine[5];
String guestModifiedDate = nextLine[6];
GuestDetails guestDetails = new GuestDetails();
guestDetails.setEmail(emailID);
guestDetails.setUsername(guestName);
guestDetails.setPhone(guestPhone);
guestDetails.setSource(guestSource);
guestDetails.setCount(Integer.valueOf(guestCount));
guestDetails.setCreatedDate(guestCreatedDate);
guestDetails.setModifiedDate(guestModifiedDate);
try {
helper.insertGuest(guestDetails);
} catch (SQLiteConstraintException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Data inserted into table...", Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
There is no guaranty that the URI you are receiving as result is a file (and thus that the path part is an actual filesystem path).
It may be a content: URI, in with case the path only makes sense for the corresponding ContentProvider.
This kind of URI should be read using ContentResolver.openInputStream() or queried via ContentResolver.query().
See A Uri Is Not (Necessarily) a File for more details.

Retrieve Image from google photos library after dowloading

I am launching an intent to get photos from gallery and when I am using nexus google photo app in my gallery everything works fine.
But if the image is not on the phone (on the Google Photos online service) it will download it for me. After selecting the image I am sending the image to another activity for cropping but in case of download the image sent to the crop activity is null since the download is not finished yet.
How can I know when the download is finished to send the image to the cropping activity?
Here is my code:
private void pickFromGallery()
{
Intent galleryIntent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
// When an Image is picked
if (requestCode == RESULT_LOAD_IMG && resultCode == Activity.RESULT_OK
&& null != data) {
// Get the Image from data
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
// Get the cursor
Cursor cursor = getApplicationContext().getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
// Move to first row
assert cursor != null;
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
startCrop(imgDecodableString);
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
any help would be appreciated.
I think you can't crop images when you download selected image from google photos. you can only crop your local storage images
But for checking whether selected image is downloadable or from local storage you can do like this in your onActivityResult() method.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMG && resultCode == Activity.RESULT_OK
&& null != data) {
Uri selectedImageUri = data.getData();
String tempPath = getPath(selectedImageUri, getActivity());
String url = data.getData().toString();
if (url.startsWith("content://com.google.android.apps.photos.content")){
try {
InputStream is = getActivity().getContentResolver().openInputStream(selectedImageUri);
if (is != null) {
Bitmap pictureBitmap = BitmapFactory.decodeStream(is);
//You can use this bitmap according to your purpose or Set bitmap to imageview
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else {
startCrop(tempPath);
}
}
}
Here is getPath() method which is used in onActivityResult().
public String getPath(Uri uri, Activity activity) {
Cursor cursor = null;
try {
String[] projection = {MediaStore.MediaColumns.DATA};
cursor = activity.getContentResolver().query(uri, projection, null, null, null);
if (cursor.moveToFirst()) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
return cursor.getString(column_index);
}
} catch (Exception e) {
} finally {
cursor.close();
}
return "";
}
I hope it helps you.
you can not download images from google drive below are the steps to download images or files from drive.
To download images or file from google drive you need a library
google-api-services-drive-v2-rev9-1.8.0-beta.jar()
SETTING UP THE CONSOLE
next go to Google Consol
Make a new project. Under Services, you'll need to turn on two things: DRIVE API and DRIVE SDK! They are separate, one does not automatically turn the other on, and YOU MUST TURN BOTH ON! (Figuring this out wasted at least 20 hours of my time alone.)
Still on the console, go to API Access. Create a client, make it an Android app. Give it your bundle ID. I don't think the fingerprints thing is actually important, as I'm pretty sure I used the wrong one, but try to get that right anyways (Google provides instructions for it.)
It'll generate a Client ID. You're going to need that. Hold onto it.
THE ANDROID CODE - Set Up and Uploading
First, get an auth token:
AccountManager am = AccountManager.get(activity);
am.getAuthToken(am.getAccounts())[0],
"oauth2:" + DriveScopes.DRIVE,
new Bundle(),
true,
new OnTokenAcquired(),
null);
Next, OnTokenAcquired() needs to be set up something like this:
private class OnTokenAcquired implements AccountManagerCallback<Bundle> {
#Override
public void run(AccountManagerFuture<Bundle> result) {
try {
final String token = result.getResult().getString(AccountManager.KEY_AUTHTOKEN);
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
Drive.Builder b = new Drive.Builder(httpTransport, jsonFactory, null);
b.setJsonHttpRequestInitializer(new JsonHttpRequestInitializer() {
#Override
public void initialize(JSonHttpRequest request) throws IOException {
DriveRequest driveRequest = (DriveRequest) request;
driveRequest.setPrettyPrint(true);
driveRequest.setKey(CLIENT ID YOU GOT WHEN SETTING UP THE CONSOLE BEFORE YOU STARTED CODING)
driveRequest.setOauthToken(token);
}
});
final Drive drive = b.build();
final com.google.api.services.drive.model.File body = new com.google.api.services.drive.model.File();
body.setTitle("My Test File");
body.setDescription("A Test File");
body.setMimeType("text/plain");
final FileContent mediaContent = new FileContent("text/plain", an ordinary java.io.File you'd like to upload. Make it using a FileWriter or something, that's really outside the scope of this answer.)
new Thread(new Runnable() {
public void run() {
try {
com.google.api.services.drive.model.File file = drive.files().insert(body, mediaContent).execute();
alreadyTriedAgain = false; // Global boolean to make sure you don't repeatedly try too many times when the server is down or your code is faulty... they'll block requests until the next day if you make 10 bad requests, I found.
} catch (IOException e) {
if (!alreadyTriedAgain) {
alreadyTriedAgain = true;
AccountManager am = AccountManager.get(activity);
am.invalidateAuthToken(am.getAccounts()[0].type, null); // Requires the permissions MANAGE_ACCOUNTS & USE_CREDENTIALS in the Manifest
am.getAuthToken (same as before...)
} else {
// Give up. Crash or log an error or whatever you want.
}
}
}
}).start();
Intent launch = (Intent)result.getResult().get(AccountManager.KEY_INTENT);
if (launch != null) {
startActivityForResult(launch, 3025);
return; // Not sure why... I wrote it here for some reason. Might not actually be necessary.
}
} catch (OperationCanceledException e) {
// Handle it...
} catch (AuthenticatorException e) {
// Handle it...
} catch (IOException e) {
// Handle it...
}
}
}
THE ANDROID CODE - Downloading
private java.io.File downloadGFileToJFolder(Drive drive, String token, File gFile, java.io.File jFolder) throws IOException {
if (gFile.getDownloadUrl() != null && gFile.getDownloadUrl().length() > 0 ) {
if (jFolder == null) {
jFolder = Environment.getExternalStorageDirectory();
jFolder.mkdirs();
}
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(gFile.getDownloadUrl());
get.setHeader("Authorization", "Bearer " + token);
HttpResponse response = client.execute(get);
InputStream inputStream = response.getEntity().getContent();
jFolder.mkdirs();
java.io.File jFile = new java.io.File(jFolder.getAbsolutePath() + "/" + getGFileName(gFile)); // getGFileName() is my own method... it just grabs originalFilename if it exists or title if it doesn't.
FileOutputStream fileStream = new FileOutputStream(jFile);
byte buffer[] = new byte[1024];
int length;
while ((length=inputStream.read(buffer))>0) {
fileStream.write(buffer, 0, length);
}
fileStream.close();
inputStream.close();
return jFile;
} catch (IOException e) {
// Handle IOExceptions here...
return null;
}
} else {
// Handle the case where the file on Google Drive has no length here.
return null;
}
}
You can use AsyncTask for downloading (or copying local image), then process it.
In your Activity create:
private class PictureAsyncTask extends AsyncTask<Void, Void, String> {
private Uri mUri;
public PictureAsyncTask(Uri uri) {
mUri = uri;
}
#Override
protected String doInBackground(Void... params) {
InputStream inputStream = null;
try {
inputStream = getContentResolver().openInputStream(mUri);
String path = null; // Path of downloaded image
// Download image from inputStream
return path;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null
}
#Override
protected void onPostExecute(String path) {
if (path == null) {
// Process image
// Maybe another AsyncTask or background thread?
} else {
// Download failed
}
}
}
Call it from onActivityResult:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case RESULT_LOAD_IMG:
if (resultCode == RESULT_OK) {
if (data != null) {
Uri uri = data.getData();
if (uri != null) {
new PictureAsyncTask(uri).execute();
} else {
// No data
}
} else {
// No picture selected?
}
}
break;
}
}

Categories

Resources