Good afternoon everyone,
I'm developing a really simple app for Android that's suppose to get a picture from gallery, displays it and show its coordinates in a TextView (latitude and longitude).
I have an ExifInterface object, but the tags (such as TAG_GPS_LATITUDE and TAG_GPS_LONGITUDE) return null.
I've tried many different solutions found on StackOverflow but none of them worked, so I thought of making a new question showing my code.
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private static int RESULT_LOAD_IMAGE = 1;
TextView textView;
ImageView imageView;
Uri imgUri;
String realPath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.txtView);
imageView = (ImageView) findViewById(R.id.imgView);
Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadPicture);
buttonLoadImage.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View arg0){
openGallery(arg0);
}
});
}
public void openGallery(View view){
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK){
imgUri = data.getData();
imageView.setImageURI(imgUri);
realPath = getRealPathFromURI(this, imgUri);
try {
ExifInterface ei = new ExifInterface(realPath);
textView.append("Latitude: " + ei.getAttribute(ExifInterface.TAG_GPS_LATITUDE) + " Longitude: " + ei.getAttribute(ExifInterface.TAG_GPS_LONGITUDE));
} catch (IOException e) {
e.printStackTrace();
}
}
}
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();
}
}
}
}
Thank you.
Related
I'm trying to retrieve the actual image name of the image selected by user in gallery(Ex. IMG_2020).
I tried using getAbsolutePath() and getName() but these 2 methods display something like "image$3A75" instead of the actual image file name.
Other than that, I also tried using some cursor method which I don't know really how it works, but it still doesn't work or maybe it's because I do not know how to use it.
Any help please?
This is my onActivityResult() method
fileName is the textView I want to place my imageName
bitMap object is not used yet because I'm following a tutorial online and I'm halfway copying, I think it will be used later in the tutorial
public class createCharity extends AppCompatActivity {
private static final int PICK_IMAGE_REQUEST = 1;
Button uploadButton;
Button createCharityButton;
TextView charityTitle;
TextView fileName;
TextView charityDescription;
Uri charityImage;
private StorageReference mStorageRef;
private DatabaseReference mDatabaseRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_charity);
uploadButton = findViewById(R.id.uploadButton);
charityTitle = findViewById(R.id.charityTitle);
fileName = findViewById(R.id.fileName);
charityDescription = findViewById(R.id.charityDescription);
createCharityButton = findViewById(R.id.createCharityButton);
mStorageRef = FirebaseStorage.getInstance().getReference("charityUploads");
mDatabaseRef = FirebaseDatabase.getInstance().getReference("charityUploads");
uploadButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFileChooser();
}
});
}
private void openFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_IMAGE_REQUEST);
System.out.println("----------------------c1");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
charityImage = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), charityImage);
File file = new File(String.valueOf(charityImage));
System.out.println("Image name: " + file.getName());
fileName.setText(file.getName());
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Something like:
String projection [] = {
MediaStore.Images.Media.DATA
, MediaStore.Images.Media.DISPLAY_NAME
, MediaStore.Images.Media.SIZE};
Cursor cursor = getContentResolver().query(data.getData(), projection, null, null, null);
if ( cursor==null)
{
Toast.makeText(context, "cursor==null\n\ncould not query content resolver for\n\n" + path, Toast.LENGTH_LONG).show();
return;
}
cursor.moveToFirst();
String data = cursor.getString(0);
String displayName = cursor.getString(1);
String size = cursor.getString(2);
Toast.makeText(context, "getContentResolver().openInputStream() ok\n\n" + path
+ "\n\nDISPLAY_NAME: " + displayName
+ "\nDATA: " + data
+ "\nSIZE: " + size
, Toast.LENGTH_LONG).show();
cursor.close();
DATA not available on Android Q+.
i was building my app on API level 23 ,then i have changed API level to 25 the same code is not working now , here's my code :
public class expert extends Activity implements View.OnClickListener {
Button btnsetwall;
ImageButton imgbtntakeph;
ImageView Imview;
static final int REQUEST_IMAGE_CAPTURE = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_expert);
Imview = (ImageView) findViewById(R.id.imageView22);
btnsetwall = (Button) findViewById(R.id.button2);
btnsetwall.setOnClickListener(this);
}
#Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
Imview.setImageBitmap(imageBitmap);
// CALL THIS METHOD TO GET THE URI FROM THE BITMAP
Uri tempUri = getImageUri(getApplicationContext(), imageBitmap);
// CALL THIS METHOD TO GET THE ACTUAL PATH
Toast.makeText(getBaseContext(),"Here "+ getRealPathFromURI(tempUri), Toast.LENGTH_LONG).show();
}
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
public String getRealPathFromURI(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
when i try to pick image from gallery or to get captured image my app crashes and i get UriString Exception
can any one tell the reason ?? and how to solve !
thanks in advance
I'm open gallery from one of my fragment but after i select image from gallery
the image doesn't show to me in view.
in the onActivityResult I have error in the rootview in this line:
ImageView imgView = (ImageView) rootview.findViewById(R.id.imgView);
and I test with toast to show me the selected image path but
it doesnt show me the path.
here is my fragment code:
public class Share_Page extends Fragment implements View.OnClickListener {
private static final int RESULT_OK = 1;
String path="";
String imgPath, fileName;
private Button home_page,search_page;
private static int RESULT_LOAD_IMG = 1;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.share, container, false);
home_page = (Button) rootview.findViewById(R.id.home_page);
search_page = (Button) rootview.findViewById(R.id.search_page);
rootview.findViewById(R.id.buttonLoadPicture).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loadImagefromGallery();
}
});
btn_click();
return rootview;
}
public void loadImagefromGallery() {
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 {
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgPath = cursor.getString(columnIndex);
cursor.close();
//ImageView imgView = (ImageView) findViewById(R.id.imgView);
ImageView imgView = (ImageView) rootview.findViewById(R.id.imgView);
imgView.setImageBitmap(BitmapFactory
.decodeFile(imgPath));
String fileNameSegments[] = imgPath.split("/");
fileName = fileNameSegments[fileNameSegments.length - 1];
path=imgPath;
} else {
Toast.makeText(getActivity(), "image not select",
Toast.LENGTH_LONG).show();
imgPath="2";
}
} catch (Exception e) {
Toast.makeText(getActivity(), "error`enter code here`...!", Toast.LENGTH_LONG)
.show();
}
}
This method is for intent to open gallery and pick image:
public void loadImagefromGallery(View view) {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityIfNeeded(galleryIntent, RESULT_LOAD_IMG);
}
And here is result after a image picked. As u see i use image to change a background, u can put it into imageView or what ever u wanted
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
assert cursor != null;
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String imgDecodableString = cursor.getString(columnIndex);
cursor.close();
Drawable d = new BitmapDrawable(getResources(), imgDecodableString);
relativeLayout.setBackground(d);
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
Also please remember to add a permissions in Manifest
Example how to use a permissions runtime, paste it into Activity
private static final int REQUEST_CODE_EXTERNAL_STORAGE = 1;
private static final int REQUEST_CODE_CAMERA = 2;
private static int RESULT_LOAD_IMG = 1;
#TargetApi(23)
public void checkCameraPermission(){
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.M){
return;
}
if (this.checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[] {Manifest.permission.CAMERA}, REQUEST_CODE_CAMERA);
}
}
#TargetApi(23)
public void checkStoragePermission() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return;
}
if (this.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager
.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_CODE_EXTERNAL_STORAGE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[]
grantResults) {
switch (requestCode) {
case REQUEST_CODE_EXTERNAL_STORAGE:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Thanks for your permission", LENGTH_SHORT).show();
} else {
Toast.makeText(this, "We need your permission to save image",
LENGTH_SHORT).show();
}
break;
case REQUEST_CODE_CAMERA:
if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
Toast.makeText(this, "Thanks for your permission", LENGTH_SHORT).show();
} else {
Toast.makeText(this, "We need your permission to start SOS",
LENGTH_SHORT).show();
}
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
break;
}
}
And if u want to check permissions on fragment u should do like this:
((Activity) getContext()).checkAnyPermission();
u should check this after u open a gallery
I found a program on this page to fetch image from sd card and show it on an imageView. I am getting issue at this line -
bitmap = BitmapFactory.decodeFile(picturePath);
I am getting correct value of picturePath variable but in the above line it is setting bitmap value as null. I had visited various threads and almost everyone is using this same line. I am not getting what is wrong with my code
Here is my complete code -
private Button upload;
ImageView imgView;
EditText caption;
Bitmap bitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgView = (ImageView) findViewById(R.id.imageView);
upload = (Button) findViewById(R.id.Upload);
caption = (EditText) findViewById(R.id.caption);
imgView.setImageResource(R.drawable.ic_menu_gallery);
upload.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, 2);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 2 && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.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 picturePath = cursor.getString(columnIndex);
cursor.close();
bitmap = BitmapFactory.decodeFile(picturePath);
imgView.setImageBitmap(bitmap);
caption.setText("Hello");
}
}
Try putting this in your AndroidManifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
After that, make sure you have the permission enabled in the App Info screen on your device.
i'm trying to do an activity which can show picture from gallery. But my Activity needs to remember bitmap uri for another time so it can always open that picture.
here is my .java
edited
i added something else to convert uri to string then string to uri but it doesn't work. Can someone help?
public class DersProgram extends Activity { private static int RESULT_LOAD_IMAGE = 1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dersprogrami);
Button buttonLoadImage = (Button) findViewById(R.id.button1);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri uri = data.getData();
String BitmapURI;
BitmapURI = uri.toString();
uri = Uri.parse(BitmapURI);
SharedPreferences sharedPreferences = getSharedPreferences("BitmapURI", Context.MODE_PRIVATE);
sharedPreferences.edit().putString("BitmapURI", "your URI as a String").apply();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.resim);
Bitmap bmp = null;
try {
bmp = getBitmapFromUri(uri);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
imageView.setImageBitmap(bmp);
}
}
private Bitmap getBitmapFromUri(Uri uri) throws IOException {
ParcelFileDescriptor parcelFileDescriptor =
getContentResolver().openFileDescriptor(uri, "r");
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
return image;
}
}
I want to open picture which is called before. Please help me(also i am a beginner) sorry for my English.
As said, use SharedPreferences.
store your bitmapURI as a String in your Activity:
SharedPreferences sharedPreferences = getSharedPreferences("some string", Context.MODE_PRIVATE);
sharedPreferences.edit().putString("BitmapURI", "your URI as a String").apply();
and retrieve it whenever your want:
String bitmapURI = sharedPreferences.getString("BitmapURI", "default string if BitmapURI is not set");