Android: How to Upload Images from the SD Card - android

In my application, I want to upload the images from the SD card with restricting the user to upload only less than 2mb. How can I accomplish this?

Use following steps:
1) Use the following intent to open gallery with images:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), 101);
2) Receive the Uri of selected file in onActivityResult func.
if (requestCode == 101 && data != null) {
Uri selectedImageUri = data.getData();
} else {
Toast toast = Toast.makeText(this, "No Image is selected.",
Toast.LENGTH_LONG);
toast.show();
}
Convert the Uri into a path using following func:
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);
}
After that create a File object from the path and then check the size of file:
File mFile = new File(path);
int length = mFile.length(); // file size in bytes
After that you can simply put an if-else to check the file size restriction and then use multi-part upload process for uploading the file.
you can use this article for multipart upload.

Related

ImageView not populating from file path

I can't get my ImageViews to update from either URI or file path - they just don't show an image
Intent to capture image:
Intent photo = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(photo, 1);
On ActivityResult
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
Uri imageUri = data.getData();
filePath = getRealPathFromURI(this, imageUri);
}
GetRealPathFromURI class:
public 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);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
It then inserts 'filePath' from onActivityResult in to a db
Retrieving from db and updating ImageViews
imgfilepath[y] = cursorc.getString(cursorc.getColumnIndex("IMAGE"));
imgFile[y] = new File(imgfilepath[y]);
Uri uri = Uri.fromFile(imgFile[y]);
String path = uri.getPath();
mImage.setImageURI(uri);
I've tried so many different ways to setImageBitmap etc which haven't worked (I can't remember all of them) - Can anyone see why this is not showing the image?
The image is in emulated storage and not the SD card.
EDIT:
I've added EXTRA_OUTPUT tag but I can't see the image in DDMS anywhere & the camera does not exit after taking the picture/accepting the image
Intent photo = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
final File root = new File(Environment.getExternalStorageDirectory() + File.separator + "MyDir" + File.separator);
root.mkdirs();
final String fname = "img_"+ System.currentTimeMillis() + ".jpg";
final File sdImageMainDirectory = new File(root, fname);
mImageUri = Uri.fromFile(sdImageMainDirectory);
photo.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
startActivityForResult(photo, 1);
Uri imageUri = data.getData();
ACTION_IMAGE_CAPTURE does not return a Uri.
The image is in emulated storage
Perhaps that one camera app does, in which case that camera app has a bug, to go along with the return-a-Uri bug.
There are thousands of Android device models. These ship with hundreds of different camera apps pre-installed, and there are hundreds more available from the Play Store and elsewhere. Many will have ACTION_IMAGE_CAPTURE implementations. Most should follow the documented protocol. None should save the image for your request, because you did not tell the camera app where to save the image.
Either:
Provide a location, via EXTRA_OUTPUT, for the camera app to save the image to, then load the image from that location, or
Use data.getExtra("data") to get a Bitmap that represents a thumbnail-sized image, if you do not provide EXTRA_OUTPUT

Android how to pick up images from Lollipop / Marshmallow and save it on imageView?

I tried that code and gave me error unable to decode stream filenotfoundException. So I found that the latest versions of Android Marshmallow and lollipop doesn't have the gallery application and the images uploaded to a server.
public String getPath(Uri uri) {
// just some safety built in
if( uri == null ) {
// TODO perform some logging or show user feedback
return null;
}
// try to retrieve the image from the media store first
// this will only work for images selected from gallery
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if( cursor != null ){
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String picturePath = cursor.getString(column_index);
return picturePath;
}
// this is our fallback here
return uri.getPath();
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
ImageView imageView = (ImageView) findViewById(R.id.profile_picture);
imageView.setImageBitmap(BitmapFactory.decodeFile(getPath(selectedImageUri)));
}
}
}
My intent code:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);
Step #1: Get rid of getPath().
Step #2: Use an image-loading library, such as Picasso. Pass it the Uri you get from the Intent passed into onActivityResult(), and your ImageView. It will handle loading the image into the ImageView for you.
If you would prefer to load the image yourself, you will need to:
Use a ContentResolver and openInputStream() to get an InputStream for the data represented by the Uri
Use BitmapFactory.decodeStream() to load the data off the InputStream and decode it into a Bitmap
Do the above steps in a background thread, so you do not tie up the main application thread while doing that I/O (e.g., doInBackground() of an AsyncTask)
When the Bitmap is ready, put it in the ImageView while running on the main application thread (e.g., onPostExecute() of an AsyncTask)

Android Picking Sound File Path - Full Path Not Returned

I am trying to get the full path of a sound file on the SD card.
This launches sound picker - I then use the Play Music app to select a file
Intent intent = new Intent();
intent.setAction(Intent.ACTION_PICK);
intent.setData(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RESULT_SOUNDPICKER);
On activity result I am trying to get the full path
case RESULT_SOUNDPICKER: {
Log.d("TAG", "onActivityResult "+requestCode+" "+resultCode);
if (resultCode == RESULT_OK)
{
Uri uri = data.getData();
String filePath = uri.getPath();
Log.d("TAG", "FilePath: "+filePath);
// A song was picked.
Log.d("TAG", "PickSongActivity.onActivityResult: "+data.getDataString());
}
}
But this returns a path like
//media/external/audio/media/13085
Rather than a proper path of where the file is held.
I need to get the full path back as I then want to use it to play the file.
Thank you.
Solution
This method can be used to get the full path.
private String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
CursorLoader loader = new CursorLoader(getApplicationContext(), contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
I need to get the full path back as I then want to use it to play the file.
There may not be a path (as it does not have to be a file), let alone a path that you can reach (as the file does not have to be on storage that is accessible to you).
MediaPlayer can use a Uri directly, so I suggest going that route.

How to get file name in android emulator from default music player?

I want to know how to get the file name of the selected file in music player,In my coding ,i was selected the mp3 file from music player and getting the data from intent and assign it to uri,where i only get the selected position in music player playlist,like Path/1 or Path/2 ,where i was not able to get the FileName of the Mp3 File .kindly help me to solve this one.Here bis my code for Reference
//for opening the file
Intent intent = new Intent();
intent.setType("audio/mp3");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, "Complete action using"),
PICK_FROM_FILE);
//Get FileName
String mPath = null;
Uri mToneCaptureUri;
mToneCaptureUri = data.getData();
mPath = mToneCaptureUri.getPath(); // from File ManagerF
setPath(mPath);
Getting full path and file name
public String getPath(Uri uri) {
String[] projection = { MediaStore.Audio.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
use this on onActivityResult
mpath = getPath(data.getData());

How to get the file path from URI? [duplicate]

This question already has answers here:
Get filename and path from URI from mediastore
(32 answers)
Closed 10 years ago.
Please find my code below. I need to get the file path of the pdf document, selected by the user from SDcard. The issue is that the URI.getPath() returns:
/file:///mnt/sdcard/my%20Report.pdf/my Report.pdf
The correct path is:
/sdcard/my Report.pdf
Please note that i searched on stackoverflow but found the example of getting the filePath of image or video, there is no example of how to get the filepath in case of PDF?
My code , NOT all the code but only the pdf part:
public void openPDF(View v)
{
Intent intent = new Intent();
//intent.setType("pdf/*");
intent.setType("application/pdf");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Pdf"), SELECT_PDF_DIALOG);
}
public void onActivityResult(int requestCode, int resultCode, Intent result)
{
if (resultCode == RESULT_OK)
{
if (requestCode == SELECT_PDF_DIALOG)
{
Uri data = result.getData();
if(data.getLastPathSegment().endsWith("pdf"))
{
String pdfPath = data.getPath();
}
else
{
CommonMethods.ShowMessageBox(CraneTrackActivity.this, "Invalid file type");
}
}
}
}
Can some please help me how to get the correct path from URI?
File myFile = new File(uri.toString());
myFile.getAbsolutePath()
should return u the correct path
EDIT
As #Tron suggested the working code is
File myFile = new File(uri.getPath());
myFile.getAbsolutePath()
Here is the answer to the question
here
Actually we have to get it from the sharable ContentProvider of Camera Application.
EDIT . Copying answer that worked for me
private String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
CursorLoader loader = new CursorLoader(mContext, contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;
}

Categories

Resources