Can any ony give me guidelines on how to find the directory my Android device stores its images takem from a camera;
In the following code snippet, I intend to get a list of files in prior to launching the camera app. When returning from the camera app get a list of all the files in the same directory and process the newly added ones.
public void onBtnTakePhoto(final View view) {
existingfiles = UploadImageService.getFiles(<IMAGE_LOCATION>);
final Intent intent = new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA);
startActivityForResult(intent, TAKE_PICTURE);
}
public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case TAKE_PICTURE:
List<String> newFies = UploadImageService.getFiles(<IMAGE_LOCATION>);
newFies.removeAll(existingfiles);
for (String newFile : newFies) {
File file = new File(newFile);
addImage( Uri.fromFile(file), PictureSource.CAMERA);
}
break;
}
// regardless of which activity, check that files exist:
verifyFilesExist(images);
}
As far as I understand it, you actually would have to launch your intent with the ACTION_IMAGE_CAPTURE action (instead of INTENT_ACTION_STILL_IMAGE_CAMERA). Then, in onActivityResult you have to get the data from the Intent: there you will find the reference to the image.
Look at the examples given here.
But as I look at your answer, you probably would find this more useful:
String[] projection = {
MediaStore.Images.ImageColumns._ID, MediaStore.Images.ImageColumns.DATA
};
String selection = "";
String[] selectionArgs = null;
mImageExternalCursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, selection, selectionArgs, null);
mImageInternalCursor =
managedQuery(MediaStore.Images.Media.INTERNAL_CONTENT_URI, projection,
selection, selectionArgs, null);
then
String filePath =
mImageExternalCursor.getString(mImageExternalCursor.getColumnIndexOrThrow(
MediaStore.Images.ImageColumns.DATA));
(since you don't actually want to take a new picture).
Related
I am trying to create a personal chatting app which has a button. When click of that button the frame becomes visible which have buttons on click chooser is been created like this. When the image button is clicked it creates the chooser activity after selecting the file I have saved it in imagefile Uri.
But when I try to get the path of the file by using the data.getdata().getpath() method it gives doument/236 as the output but didn't give the actual path of the file. When I try to use fileutlis to get the path then it says "can't resolve fileutils". Please help me so that I can get the path of my file.
imagesend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
checker = "image";
Intent imageIntent = new Intent();
imageIntent.setAction(Intent.ACTION_GET_CONTENT);
imageIntent.setType("image/*");
startActivityForResult(Intent.createChooser(imageIntent,"Select Image"),438);
}
});
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 438 && resultCode == RESULT_OK && data!=null && data.getData()!=null){
loadingBar.setTitle("Sending Message");
loadingBar.setMessage("Please wait...");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
imagefile = data.getData();
String filepath = data.getData().getPath();
if(checker.equals("pdf")){
pdfFilemessage();
}else if(checker.equals("image")){
//imagefilemessage();
Toast.makeText(personalChat.this,filepath,Toast.LENGTH_SHORT).show();
}
}
}
This line returns the Uri of the file.
imagefile = data.getData();
What you have to do is,
public String getRealPathFromURI(Uri contentUri) {
String[] proj = {
MediaStore.Audio.Media.DATA
};
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
Add this to your code.
String filePath = this.getRealPathFromURI(imagefile);
Refer this: https://stackoverflow.com/a/13209514
You can try this:
Uri fileUri = intent.getData();
Now from this you can use the below gist file to generate the file path from the URI
https://gist.github.com/tatocaster/32aad15f6e0c50311626
With Android 10 you won't by default be able to access the file directly by path as Google are forcing people to use Storage Access Framework and or MediaStore to access files.
With Android 11 their plan is to make this the only way to access files.
See https://developer.android.com/training/data-storage/files/external-scoped for details.
You will need to use ContentResolver#openFileDescriptor(Uri, String)
and ParcelFileDescriptor#getFileDescriptor() to get something usable
e.g.
ParcelFileDescriptor pfd =
this.getContentResolver().
openFileDescriptor(Uri, "r");
FileInputStream fileInputStream =
new FileInputStream(
pfd.getFileDescriptor());
If you want to get other info about the file you can do that with a contentResolver Query on the URI for DISPLAY_NAME or MIME_TYPE for type of file.
e.g.
// useful name to display to user
Cursor cursor = this.getContentResolver()
.query(Uri, new String[] { MediaStore.Files.FileColumns.DISPLAY_NAME},
null, null, null);
cursor.moveToFirst();
filename = cursor.getString(0);
cursor.close();
For instance, when I want to attach an image to a text message in the stock Messages app, I get a familiar system dialog presenting the Camera, Gallery, and other image Content Providers.
I want to use this in my own app. I see plenty of libraries that allow the user to choose between Gallery and Camera, but I want all of the user's installed Image source to appear.
Is the system dialog from Messages (and other stock apps, such as Mail) really custom for those apps? Do we really need to build our own? Storage Access Framework does not appear to be the right solution since it bypasses the camera (or other image sources that I haven't thought of but may be present on a user's device).
I would suggest Intent.ACTION_PICK
private void selectFileFromGallery() {
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent,
"Select Picture"), requestGallery);
}
It will open a dialog like this that contains all of users app that can be used as an image picker :
And then when user chosses image:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == requestGallery) {
onSelectFromGalleryResult(data);
}
}
#SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
Uri uri = data.getData();
if (!uri.toString().contains("file")) {
if (uri.toString().contains("external")) {//chosen from external storage
photoUri = Uri.parse("file://" + getRealPathFromURI(uri));
} else {
photoUri = Uri.parse("file://" + (Build.VERSION.SDK_INT <= 18
? getRealPathFromURI_API11to18(getActivity(), uri) :
getRealPathFromURI_API19(getActivity(), uri)));
}
}
#SuppressLint("NewApi")
private String getRealPathFromURI_API19(Context context, Uri uri) {
return RealPathUtil.INSTANCE.getRealPathFromURI_API19(context, uri);
}
public String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().managedQuery(contentUri, proj, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
#SuppressLint("NewApi")
private String getRealPathFromURI_API11to18(Context context, Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
String result = null;
CursorLoader cursorLoader = new CursorLoader(
context,
contentUri, proj, null, null, null);
Cursor cursor = cursorLoader.loadInBackground();
if (cursor != null) {
int column_index =
cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
result = cursor.getString(column_index);
}
return result;
}
The thing you are asking for can be done using System Access Frame work.
Add Storage Permissions inside the manifest file, and then check if the permission is accepted or not. Then you can open open document choose to let the user choose the image.
Code
Inside some onClick
Intent i = new Intent(Intent.ACTION_OPEN_DOCUMENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
startActivityForResult(i, 41);
This will open file chooser activity for image files only.
Then you can get back the results inside:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK){
if (requestCode == 41) {
if (data != null) {
Uri uri = data.getData();
//This is the uri to the file
//To get the file use the uri
}
}
}
}
Still you have to create the BottomSheetDialog on your own, but your job will be drastically reduced as there will be only 2 options : 1. Camera app ,2. File chooser. You will have to handle the camera event on your own and get the image uri.
I suggest using android image Android-Image-Cropper by ArthurHub
It gives you all the options you are looking for
Team
My question is, how do I read the result from the startAtcivityForResult.
When the button is pressed, it calls bStock(), which makes a URL call and retrieves data. I have verified the URL call is correct and that I do get data.
I have used finishActivity(1) to not display the actual content or result. For the sake of this message here is what I get when not using finishActivity(1)
My goal is to read the result and only display certain values like name and last price. Here is my code
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//setContentView(R.layout.content_layout_id);
final Button buttonStock = findViewById(R.id.buttonS);
buttonStock.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
bStock();
}
});
}
static final int REQUEST_CODE = 1;
protected void bStock() {
String url = "http://dev.markitondemand.com/Api/v2/Quote/jsonp?symbol=AG";
Uri uri = Uri.parse(url);
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
i.setPackage("com.android.chrome");
startActivityForResult(i, REQUEST_CODE);
finishActivity(1);
}
#Override
protected void onActivityResult ( int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE) {
// Make sure the request was successful
//if (resultCode == RESULT_OK) { // 0 -1
// Get the URI that points to the selected contact
Uri o = data.getData();
Toast.makeText(MainActivity.this, "Name ", Toast.LENGTH_LONG).show();});
}
}
I am using a Toast (for now) just to display the name, but I do not know how to read data. Any help would be appreciated.
Jesse
That does not work as you expect, because the activity you are trying to start (chrome browser) is not prepared to return the result you want, to you. The intent (VIEW) tells the browser, to do just that -- view the given URL.
For activities that are not your own, you have to carecully check their description to see if they support any calls for results, and how they return it -- e.g. there is a 'take a picture' intent, that will return the picture taken to you via some uri data.
Most of the time, startActivityForResult is used to start your own activities, which you want to return data to the calling activity. In that case, you can define yourself, on how to pass the results back to the calling activity.
you may need to iterate through a cursor
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request it is that we're responding to
if (requestCode == PICK_CONTACT_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// Get the URI that points to the selected contact
Uri contactUri = data.getData();
// We only need the NUMBER column, because there will be only one row in the result
String[] projection = {Phone.NUMBER};
// Perform the query on the contact to get the NUMBER column
// We don't need a selection or sort order (there's only one result for the given URI)
// CAUTION: The query() method should be called from a separate thread to avoid blocking
// your app's UI thread. (For simplicity of the sample, this code doesn't do that.)
// Consider using CursorLoader to perform the query.
Cursor cursor = getContentResolver()
.query(contactUri, projection, null, null, null);
cursor.moveToFirst();
// Retrieve the phone number from the NUMBER column
int column = cursor.getColumnIndex(Phone.NUMBER);
String number = cursor.getString(column);
// Do something with the phone number...
}
}
}
First time I post a question, so here it goes.
I want to push on a button, so it opens the gallery, pick a picture, then shows it somewhere on the screen (layout).
I got this far by now:
public void FotoKiezen(View v) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 1:
{
if (resultCode == RESULT_OK)
{
Uri photoUri = data.getData();
if (photoUri != null)
{
try {
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(photoUri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
Bitmap bMap = BitmapFactory.decodeFile(filePath);
ImageView.setImageBitmap(bMap);
}catch(Exception e)
{}
}
}// resultCode
}// case 1
}// switch, request code
}// public void onActivityResult
There is some other code above it too, but here somewhere is the problem.
I get an error on the line ImageView.setImageBitmap(bMap);
The error:
Cannot make a static reference to the non-static method setImageBitmap(Bitmap) from the type ImageView
I searched a lot on the internet, and tried many things, but I can't resolve it.
Maybe it is really easy and I just don't see it.
I am beginner at Java android programming, used to program in C++.
So also some explanation about the error would be very nice :D
I think this line cause error..
ImageView.setImageBitmap(bMap);
Here ImageView is a class, instead of this you have to create a object of it then use setImageBitmap to it.,
ImageVIew mImageView = new ImageView(this)
mImageView.setImageBitmap(bMap);
Or if you have already defined ImageView object in your activity then just use that..
You must create the object of ImageView class? For example:
ImageView img = new ImageView(this);
img.setImageBitmap(bMap);
or
ImageView img = (ImageView)findViewById(R.id.<your image view id>);
img.setImageBitmap(bMap);
I am new to Android. I have just created an AVD with 256 MB android-SDcard in it in Android 2.1. And I have inserted two images into it. I have done this using the DDMS perspective. And the images are now stored into a folder 100ANDRO in the DCIM folder of SDcard. Now I want to create an application that allows the user to select the images through browsing the folders and need to save the corresponding image to the database android-sqlite.
Can someone help me to find an appropriate method for this? Thanks in advance.
I have found one method for this.
I have created a button for UPLOAD and on the click action I have set like this.
upload.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1);
}
});
And I have overrided this method along with the same class as below.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 1:
{
if (resultCode == RESULT_OK)
{
Uri photoUri = data.getData();
if (photoUri != null)
{
try {
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(photoUri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
Bitmap bitmap = BitmapFactory.decodeFile(filePath);
imgView.setImageBitmap(bitmap);
int size = bitmap.getWidth() * bitmap.getHeight();
ByteArrayOutputStream out = new ByteArrayOutputStream(size);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();}
String bb = out.toString();
byte[] x = out.toByteArray();
image_value.setTag(x);
image_value.setText(filePath);
}catch(Exception e)
{}
}
}
}
Here image_value represents a hidden text view in the xml file.
I have passed the value of the image location and bytes as text view's value and tag.
And later on I have saved this bytes into the database for later display. Its working fine.
Thanks to all.