How to get the image name when user upload the image from gallery and display them in textView? - java

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+.

Related

Problem in download Imageuri in Firebase Storage Android

I'm uploading images from my app and storing the download URL in a model class but after I see the URL I copied it and paste the link but it didn't open up the image.
Here is the Firebase Realtime Database image
Here is the Firebase Storage
and here what it should be
https://firebasestorage.googleapis.com/v0/b/myapp-not-final.appspot.com/o/uploads%2F1618234721167.jpg?alt=media&token=fcac1404-87ce-4c7d-ae5f-a1ec7074bf04
Java Files
Upload_Fragment.java
public class Upload_Fragment extends Fragment {
private static final int PICK_IMAGE_REQUEST = 10;
private ImageView uploadImageView;
private Uri mImageUri;
private StorageReference storageReference;
private DatabaseReference databaseReference;
private StorageTask mUploadTask;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_upload, container, false);
Button chooseImageButton = view.findViewById(R.id.upload_image_button);
Button uploadImageButton = view.findViewById(R.id.done_button);
uploadImageView = view.findViewById(R.id.upload_image_view);
FirebaseStorage storage = FirebaseStorage.getInstance();
storageReference = storage.getReference("uploads");
databaseReference = FirebaseDatabase.getInstance().getReference("uploads");
chooseImageButton.setOnClickListener(v -> openFileChooser());
uploadImageButton.setOnClickListener(v -> {
if (mUploadTask != null && mUploadTask.isInProgress()) {
Toast.makeText(getActivity(), "Upload in Progress", Toast.LENGTH_SHORT).show();
} else {
uploadToFirebase(mImageUri);
}
});
return view;
}
private void openFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_IMAGE_REQUEST);
}
#Override
public 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) {
mImageUri = data.getData();
Picasso.get().load(mImageUri).into(uploadImageView);
}
}
private String getFileExtension(Uri uri) {
ContentResolver contentResolver = Objects.requireNonNull(getActivity()).getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(contentResolver.getType(uri));
}
private void uploadToFirebase(Uri mImageUri) {
if (mImageUri != null) {
final ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.setTitle("Uploading...");
progressDialog.show();
StorageReference reference = storageReference.child(System.currentTimeMillis()
+ "." + getFileExtension(mImageUri));
reference.putFile(mImageUri)
.addOnSuccessListener(taskSnapshot -> {
progressDialog.dismiss();
Toast.makeText(getActivity(), "Saved Succesfully", Toast.LENGTH_SHORT).show();
reference.getDownloadUrl()
.addOnSuccessListener(uri -> {
Upload upload = new Upload(mImageUri.toString());
String uploadId = databaseReference.push().getKey();
databaseReference.child(uploadId).setValue(upload);
});
})
.addOnProgressListener(snapshot -> {
double progress = (100.0 * snapshot.getBytesTransferred() / snapshot
.getTotalByteCount());
progressDialog.setMessage("Uploaded " + (int) progress + "%");
})
.addOnFailureListener(e -> {
progressDialog.dismiss();
Toast.makeText(getActivity(), "Error Ocurred" + e.getMessage(), Toast.LENGTH_SHORT).show();
});
}
}
}
Upload.java // This is the model class
public class Upload {
private String mImageUrl;
public Upload() {
}
public Upload(String imageUrl) {
mImageUrl = imageUrl;
}
public String getmImageUrl() {
return mImageUrl;
}
public void setmImageUrl(String mImageUrl) {
this.mImageUrl = mImageUrl;
}
}
in uploadToFirebase method inside
reference.getDownloadUrl().addOnSuccessListener(uri -> {.....
instead of mImageUri.toString() put uri.toString() as per bellow.So you will get actual url and will solve your problem.
private void uploadToFirebase(Uri mImageUri) {
if (mImageUri != null) {
final ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.setTitle("Uploading...");
progressDialog.show();
StorageReference reference = storageReference.child(System.currentTimeMillis()
+ "." + getFileExtension(mImageUri));
reference.putFile(mImageUri)
.addOnSuccessListener(taskSnapshot -> {
progressDialog.dismiss();
Toast.makeText(getActivity(), "Saved Succesfully", Toast.LENGTH_SHORT).show();
reference.getDownloadUrl()
.addOnSuccessListener(uri -> {
Upload upload = new Upload(uri.toString());
String uploadId = databaseReference.push().getKey();
databaseReference.child(uploadId).setValue(upload);
});
})
.addOnProgressListener(snapshot -> {
double progress = (100.0 * snapshot.getBytesTransferred() / snapshot
.getTotalByteCount());
progressDialog.setMessage("Uploaded " + (int) progress + "%");
})
.addOnFailureListener(e -> {
progressDialog.dismiss();
Toast.makeText(getActivity(), "Error Ocurred" + e.getMessage(), Toast.LENGTH_SHORT).show();
});
}
}
In your database schema, your "mImageUrl" property holds a URL similar to this:
content://com.android.externalstorage.documents...
As you probably see, those URLs are pointing to some files that are located locally on the external storage. So you cannot use such URLs and expect to read data from Firebase Storage. To check the URL of an image in the Firebase Console, please see on the right-hand side a section called "File location". If you click on the token you'll get a copy of the URL of the image that looks similar to this:
https://firebasestorage.googleapis.com/v0/b/myapp-not-final.appspot.com/...
This means that this is the correct URL that should be stored in the database and not the local one. To get the download URL please check my answer from the following post:
How to get the download url from Firebase Storage?
Once you have the correct URL, add it to Firestore so it can be later used.

Restrict selecting file above some size in Android Studio

I a beginner in android, I want to select an image or a video file. But I want to restrict the selected file size, let's assume the restriction size is 5MB. Above 5MB I want to not allow the user to select the file.
How can I do it?
Any help would be appreciated.
Button OnClick:
btnSelectFile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("*/*");
startActivityForResult(galleryIntent, 21);
}
});
OnActivityResult:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 21 && resultCode == RESULT_OK) {
// Get the Uri of the selected file
uri = data.getData();
uriString = uri.toString();
myFile = new File(uriString);
path = myFile.getAbsolutePath();
displayName = null;
if (uriString.startsWith("content://")) {
Cursor cursor = null;
try {
cursor = getActivity().getContentResolver().query(uri, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
int sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE);
Log.e("TAG","Size: "+Long.toString(cursor.getLong(sizeIndex)));
textFileSelected.setText(displayName);
fileName = textFileSelected.getText().toString();
Toast.makeText(this, "File Selected: " + fileName, Toast.LENGTH_SHORT).show();
}
} finally {
cursor.close();
}
} else if (uriString.startsWith("file://")) {
displayName = myFile.getName();
textFileSelected.setText(displayName);
fileName = textFileSelected.getText().toString();
Toast.makeText(this, "File Selected: " + fileName, Toast.LENGTH_SHORT).show();
}
}
}

ExifInterface Latitude/Longitude return null - Android

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.

Attempt to invoke virtual method 'android.os.Parcelable android.os.Bundle.getParcelable(java.lang.String)' null object reference

I am making an app in which a feature that user can upload images and video to server
it was working well on activity but now I want to use it in a fragment. I try to code effectively, efficiently and I am not getting any error during compiling and my app runs successfully but when I click on fragment it shows "unfortunately app has stopped " and in log cat I am getting this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Parcelable android.os.Bundle.getParcelable(java.lang.String)' on a null object reference
and its points this line:
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
this line ➦ fileUri = savedInstanceState.getParcelable("file_uri");
}
i don't know whats wrong
my code:
public class TabFragment4 extends Fragment implements View.OnClickListener{
View parentHolder;
private static final String TAG = MainActivity.class.getSimpleName();
int req_code = 100;
int video_code = 20;
String path;
Uri selectedImageUri;
// Camera activity request codes
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 10;
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
Context mContext;
private Uri fileUri; // file url to store image/video
private ImageButton btnCapturePicture, btnRecordVideo,gallerybtn , videobtn,b1,location;
public TabFragment4() {
// Required empty public constructor
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
parentHolder = inflater.inflate(R.layout.fragment_tab_fragment4, container, false);
final LocationManager manager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
AlertDialog.Builder mAlertDialog = new AlertDialog.Builder(getActivity());
// Setting Dialog Title
mAlertDialog.setTitle("Location not available, Open GPS?")
.setMessage("Activate GPS to use Location Service ?")
.setPositiveButton("Open Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
})
.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
}).show();
// Call your Alert message
}
btnCapturePicture = (ImageButton)parentHolder.findViewById(R.id.btnCapturePicture);
btnRecordVideo = (ImageButton)parentHolder. findViewById(R.id.btnRecordVideo);
gallerybtn=(ImageButton)parentHolder.findViewById(R.id.imagegallery);
videobtn = (ImageButton)parentHolder.findViewById(R.id.videogallery);
location=(ImageButton)parentHolder.findViewById(R.id.location);
videobtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
video();
}
});
gallerybtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// record video
galleryimage();
}
});
btnCapturePicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// record video
captureImage();
}
});
/**
* Capture image button click event
*/
btnRecordVideo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// record video
recordVideo();
}
});
/**
* Record video button click event
*/
btnRecordVideo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// record video
recordVideo();
}
});
return parentHolder;
}
public void video(){
Intent intent = new Intent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select file to upload "), video_code);
}
public void galleryimage(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select file to upload "), req_code);
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
/**
* Launching camera app to record video
*/
private void recordVideo() {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
// set video quality
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file
// name
// start the video capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
}
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on screen orientation
// changes
outState.putParcelable("file_uri", fileUri);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
fileUri = savedInstanceState.getParcelable("file_uri");
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == req_code) {
selectedImageUri = data.getData();
if (resultCode ==Activity. RESULT_OK) {
path = getPath(selectedImageUri);
launchUpload(true);
System.out.println("selectedPath1 : " + path);
}
}
if (requestCode == video_code) {
selectedImageUri = data.getData();
if (resultCode == Activity. RESULT_OK) {
path = getPath(selectedImageUri);
launchUpload(false);
System.out.println("selectedPath1 : " + path);
}
}
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
//successfully captured the image
// launching upload activity
launchUploadActivity(true);
//Intent intent = new Intent(this,UploadActivity.class);
//startActivity(intent);
} else if (resultCode ==Activity. RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getActivity(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getActivity(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
} else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
// video successfully recorded
// launching upload activity
launchUploadActivity(false);
} else if (resultCode == Activity.RESULT_CANCELED) {
// user cancelled recording
Toast.makeText(getActivity(),
"User cancelled video recording", Toast.LENGTH_SHORT)
.show();
} else {
// failed to record video
Toast.makeText(getActivity(),
"Sorry! Failed to record video", Toast.LENGTH_SHORT)
.show();
}
}
}
private void launchUploadActivity(boolean isImage) {
Intent i = new Intent(getActivity(), UploadActivity.class);
i.putExtra("filePath", fileUri.getPath());
i.putExtra("isImage", isImage);
startActivity(i);
}
private void launchUpload(boolean isImage) {
Intent i = new Intent(getActivity(), UploadActivity.class);
i.putExtra("filePath", path);
i.putExtra("isImage", isImage);
startActivity(i);
}
/**
* ------------ Helper Methods ----------------------
* */
/**
* Creating file uri to store image/video
*/
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/**
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
Config.IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(TAG, "Oops! Failed create "
+ Config.IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else if (type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "VID_" + timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
#Override
public void onClick(View v) {
}
}
Uri imageUri = data.getData();
Bitmap bitmap= null;
try {
bitmap = MediaStore.Images.Media.getBitmap(getContext().getContentResolver(), imageUri);
} catch (IOException e) {
e.printStackTrace();
}
Seems savedInstanceState == null so use something like this:
if (savedInstanceState != null) {
fileUri = savedInstanceState.getParcelable("file_uri");
} else {
fileUri = ??? - what You want do to in else case;
}

How to remember bitmap Uri

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");

Categories