Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(
Intent.createChooser(intent, "Select a File to Copy"),
FILE_SELECT_CODE);
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(this, "Please install a File Manager.",
Toast.LENGTH_SHORT).show();
}
}
this code lead me to select file and i want take uri of selected file,
Hi once you get your image you need to trigger and retrieve image data using onActivityResult like this, have a dedicated result code for this operation. rough example below to give u idea
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == Activity.RESULT_OK) {
Uri uri = data.getData(); // ur raw file data convert to anything u want
try {
//for images
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
imageView.set(bitmap) //example , you can choose what you want to with bitmap
//for files
InputStream inputStream;
File file = null;
try {
inputStream = getContentResolver().openInputStream(Uri.parse(your URI));
file = new File(String.valueOf(inputStream));
}catch (Exception e){
}
}catch (IOException e) {
e.printStackTrace();
}
Related
my app is working fine below the 10 version but android 11 and higher versions do not support external storage. my picker is not picking any document file. but after giving manage_external_storage permission in manifest google play store did not approve my app. please help if you know any alternate solution for all file access permission.
Try like below. Create global variable as needed or refactor as per your need. This is tested upto Android 11.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
private void OpenCamera() {
try {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File photoFile = null;
try {
photoFile = createFile();
} catch (Exception ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(getActivity().getApplicationContext(), getActivity().getApplicationContext().getPackageName() + ".fileprovider", photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, 3);
}
// }
} catch (Exception e) {
}
}
private File createFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(imageFileName, /* prefix */".jpg", /* suffix */storageDir /* directory */);
// Save a file: path for use with ACTION_VIEW intents
ImageLoc = image.getAbsolutePath();
return image;
}
// Open Gallery
private void OpenGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Image"), 1);
}
// onActivityResult handles gallery pics, camera pics and pdf.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if (resultCode == Activity.RESULT_OK) {
if (data.getData() != null) {
try {
Uri imageUri = data.getData();
File file = new File(Path_from_Uri.getPath(getActivity(), imageUri));
} catch (Exception e) {
Toast.makeText(getActivity(), "Please Select Image from Gallery", Toast.LENGTH_LONG).show();
}
}
}
} else if (requestCode == 3) {
try {
File file = new File(ImageLoc);
} catch (Exception e) {
Log.d("TAG", e.toString());
}
}
}
How can i upload images from camera to my web server ,
I was able to upload using image chooser like in this tuto
https://www.simplifiedcoding.net/android-upload-image-to-server/
, but i would like to choose images from camera and galery instead
public void uploadMultipart() {
//getting the actual path of the image
String path = getPath(filePath);
//Uploading code
try {
String uploadId = UUID.randomUUID().toString();
//Creating a multi part request
new MultipartUploadRequest(this, uploadId, Constants.UPLOAD_URL)
.addFileToUpload(path, "image") //Adding file
.addParameter("name", name) //Adding text parameter to the request
.setNotificationConfig(new UploadNotificationConfig())
.setMaxRetries(2)
.startUpload(); //Starting the upload
} catch (Exception exc) {
Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
}
}
//method to show file chooser
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
//handling the image chooser activity result
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
I also found this method , but it didn't work for me
How can replace the file chooser method in the above code properly to get the image path and name , and then upload it as in the tuto
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(UploadImageTest.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo"))
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
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();
}
For Uploading a captured image to the server the whole your code remains the same you just need to pass your captured image file path into your uploadMultipart function.
You will get captured image file path in your onActivityResult.
I'm trying to copy a file from download folder to another directory.
i used this code to get the file path
int PICKFILE_RESULT_CODE=1;
Intent chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
chooseFile.setType("*/*");
chooseFile = Intent.createChooser(chooseFile, "Choose a file");
startActivityForResult( chooseFile,PICKFILE_RESULT_CODE);
I also used
#Override
public void onActivityResult(int requestCode, int resultCode,
Intent returnIntent) {
// If the selection didn't work
if (resultCode != RESULT_OK) {
// Exit without doing anything else
return;
} else {
returnUri = returnIntent.getData();
String src = returnUri.getPath();
Toast.makeText(this, src, Toast.LENGTH_SHORT).show();
}
}
The code works fine if the file is outside the download directory, when in it the path which i get is in the form of number not the actual name of the file like:
/document/2399
this gives an error of file not found
while the path from the root is:
/storage/emulated/0/myDB.db3
this works fine
pls help me to fix this
The code works fine if the file is outside the download directory
No, it does not. It works fine if the scheme of the Uri happens to be file. Most of the time, it will be content.
I'm trying to copy a file from download folder to another directory.
Use openInputStream() on a ContentResolver to get an InputStream on the content identified by the Uri. This works for both file and content schemes. Then, use standard Java I/O to copy the content from the InputStream to your desired location.
Here is the new code:
int PICKFILE_RESULT_CODE=1;
Intent chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
chooseFile.setType("*/*");
chooseFile = Intent.createChooser(chooseFile, "Choose a file");
startActivityForResult( chooseFile,PICKFILE_RESULT_CODE);
And used:
#Override
public void onActivityResult(int requestCode, int resultCode,
Intent returnIntent) {
InputStream is = null;
// If the selection didn't work
if (resultCode != RESULT_OK) {
// Exit without doing anything else
return;
} else {
// Get the file's content URI from the incoming Intent
Uri returnUri = returnIntent.getData();
try {
is = getContentResolver().openInputStream(returnUri);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
BackUpHelper.importDB(is);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void importDB(InputStream is) throws IOException {
OutputStream os = null;
try {
String currentDBPath = DataBaseHelper2.DB_PATH+DataBaseHelper2.DB_NAME;
File outPut = new File(currentDBPath);
os = new FileOutputStream(outPut);
byte[] buffer = new byte[1024];
while (is.read(buffer) > 0) {
os.write(buffer);
}
Toast.makeText(context, R.string.export_successful,
Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(context, R.string.export_failed, Toast.LENGTH_SHORT)
.show();
}finally {
os.flush();
os.close();
is.close();
}
}
The reason why I am asking this is because the callback of the file chooser Intent returns an Uri.
Open file chooser via Intent:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), CHOOSE_IMAGE_REQUEST);
Callback:
#Override
public void onActivityResult(int requestCode, int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CHOOSE_IMAGE_REQUEST && resultCode == Activity.RESULT_OK) {
if (data == null) {
// Error
return;
}
Uri fileUri = data.getData();
InputStream in = getContentResolver().openInputStream(fileUri);
// How to determine image orientation through Exif data here?
}
}
One way would be to write the InputStream to an actual File, but this seems like a bad workaround for me.
After the 25.1.0 support library was introduced, now is possible to read exif data from URI contents (content:// or file://) through an InputStream.
Example:
First add this line to your gradle file:
compile 'com.android.support:exifinterface:25.1.0'
Uri uri; // the URI you've received from the other app
InputStream in;
try {
in = getContentResolver().openInputStream(uri);
ExifInterface exifInterface = new ExifInterface(in);
// Now you can extract any Exif tag you want
// Assuming the image is a JPEG or supported raw format
} catch (IOException e) {
// Handle any errors
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ignored) {}
}
}
For more information check: Introducing the ExifInterface Support Library, ExifInterface.
I'm completely news on android thing and unfortunately with little few time to learn it by the right way, I have a work to release.
The problem is: I need to take a picture and process her with an algorithm that I made.
I did it by the easiest way that I could find, I know it looks like really trahsie for those who really get android (sorry)
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
takePic();
protected void takePic(){
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePictureIntent, 100);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Bundle extras = data.getExtras();
mImageBitmap = (Bitmap) extras.get("data");
Algorithm(mImageBitmap)
But it doesn't process, it takes a photo, ask to save or cancell and leaves the application, I have already made by different ways (creating a new activity), but nothing seems to work
Heres how I did it
To go to the camera:
Somewhere, declaire a fileUri variable and hold onto it
Uri fileUri;
final int TAKE_PICTURE=100;//this can be any int, really
public void goToCamera(){
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
File photo;
try
{
// place where to store camera taken picture
photo = this.createTemporaryFile("picture", ".jpg");
Log.v(TAG, "Here(after createTempFile)");
photo.delete();
}
catch(Exception e)
{
Log.v(TAG, "Can't create file to take picture!" + e.getMessage());
Toast.makeText(context, "Please check SD card!", Toast.LENGTH_SHORT).show();
return;
}
fileUri = Uri.fromFile(photo);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
//Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, TAKE_PICTURE);
}
Then to retreive the image
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if (requestCode == TAKE_PICTURE && resultCode == RESULT_OK){
this.getContentResolver().notifyChange(uri, null);
ContentResolver cr = this.getContentResolver();
Bitmap bitmap;
try
{
BitmapFactory.Options ops = new BitmapFactory.Options();
ops.inSampleSize = 4;
bitmap = BitmapFactory.decodeFile(uri.getPath().toString(), ops);
}
catch (Exception e)
{
Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT).show();
Log.d(TAG, "Failed to load", e);
}
}
}
The create temp file mentioned above:
private File createTemporaryFile(String part, String ext) throws Exception
{
File tempDir= Environment.getExternalStorageDirectory();
tempDir=new File(tempDir.getAbsolutePath()+"/.temp/");
Log.i(TAG, tempDir.toString());
if(!tempDir.exists())
{
Log.i(TAG, "Dir doesnt exist");
tempDir.mkdirs();
}
return File.createTempFile(part, ext, tempDir);
}
I realize this isn't probably as simple as you were hoping for, but this approach seemed to be as flexible and compatible as possible. Let me know if I left anything else out