I am new to android development. I am working on images and videos in gallery. I upload the image or video from gallery. I got the cursor values return null.
First
1) Why the issue is occurred when upload image or video ?
2) How to solve this error?
I used to upload and image and video from gallery`
OpenGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mode = "sms";
gocodercamera.stopPreview();
isCameraMenuVisible = false;
CameraMenu.setVisibility(View.GONE);
Intent galleryIntent = new Intent(/*Intent.ACTION_GET_CONTENT*/Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
galleryIntent.setType("image/* video/*");
startActivityForResult(galleryIntent, 300);
}
});
`
OnActivityResult`
/**Picking file from Gallery*/
if (requestCode == 300) {
if (resultCode == RESULT_OK) {
try {
gocodercamera.setVisibility(View.VISIBLE);
gocodercamera.startPreview();
if (data != null) {
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 filepath = cursor.getString(columnIndex);
cursor.close();
if (filepath.endsWith(".jpg") || filepath.endsWith(".jpe") || filepath.endsWith(".jpeg") || filepath.endsWith(".png")) {
imagefilepath = filepath;
// uriList.add(imagefilepath);
// typesList.add("image");
Uri getCompressedUriPath = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
String getCompressedPath = compressImage(filepath, getCompressedUriPath);
if (aDetector.isConnectingToInternet()) {
sendMediaUpload(getCompressedPath, "image");
} else {
Toast.makeText(getApplicationContext(), "Please check your internet connection", Toast.LENGTH_LONG).show();
}
// ImageAdapterList myAdapter = new ImageAdapterList();
// listview.setAdapter(myAdapter);
} else {
Cursor cursor1 = MediaStore.Video.query(getContentResolver(), selectedImage, new String[]{MediaStore.Video.VideoColumns.DURATION});
cursor1.moveToFirst();
String dur = cursor1.getString(cursor1.getColumnIndex("duration"));
int duration = Integer.parseInt(dur);
duration = duration / 1000;
Log.e("dur", "dur : " + dur);
Log.e("duration", "duration : " + duration);
videofilepath = filepath;
imagefilepath = videofilepath;
sendMediaUpload(imagefilepath, "video");
// ImageAdapterList myAdapter = new ImageAdapterList();
// listview.setAdapter(myAdapter);
}
} else {
// Toast.makeText(getApplicationContext(),"Sorry! Failed to select File from gallery", Toast.LENGTH_SHORT).show();
}
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} else if (resultCode == RESULT_CANCELED) {
gocodercamera.setVisibility(View.VISIBLE);
gocodercamera.startPreview();
// Toast.makeText(getApplicationContext(),"User cancelled to select File", Toast.LENGTH_SHORT).show();
} else {
gocodercamera.setVisibility(View.VISIBLE);
gocodercamera.startPreview();
// Toast.makeText(getApplicationContext(),"Sorry! Failed to select File", Toast.LENGTH_SHORT).show();
}
}`
Since you have mentioned Android 6.0, just check if you have the permissions given to read and write the disk storage before you try it. Starting from Marshmallow, Android has started runtime permissions which means by default most of the permissions provided in the Android Manifest does not actually work unless you provide it at runtime
https://developer.android.com/training/permissions/requesting.html
Related
basically I am creating an app where users can upload his/her files on drive by creating folders. Here I have been Successfully created a folder now the issue wt I am facing is how to upload files on that folder which the user just created.where the user can select multiple images, videos, docs, etc. For the select purpose, I have chosen intent but am not able to get how to upload it. Here's the code wt I have done till now.
For Creating Folder I used this method now I want to upload files in this folder please let me know
if (mDriveServiceHelper == null) {
return;
}
mDriveServiceHelper.createFolder("FolderNew", null)
.addOnSuccessListener(new OnSuccessListener<GoogleDriveFileHolder>() {
#Override
public void onSuccess(GoogleDriveFileHolder googleDriveFileHolder) {
Gson gson = new Gson();
Log.d(TAG, "onSuccess: " + gson.toJson(googleDriveFileHolder));
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG, "onFailure: " + e.getMessage());
}
});
For Picking Up Images And Videos
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), PICK_IMAGE_MULTIPLE);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
try {
// When an Image is picked
if (requestCode == PICK_IMAGE_MULTIPLE && resultCode == RESULT_OK
&& null != data) {
// Get the Image from data
String[] filePathColumn = { MediaStore.Images.Media.DATA };
imagesEncodedList = new ArrayList<String>();
if(data.getData()!=null){
Uri mImageUri=data.getData();
// Get the cursor
Cursor cursor = getContentResolver().query(mImageUri,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imageEncoded = cursor.getString(columnIndex);
cursor.close();
} else {
if (data.getClipData() != null) {
ClipData mClipData = data.getClipData();
ArrayList<Uri> mArrayUri = new ArrayList<Uri>();
for (int i = 0; i < mClipData.getItemCount(); i++) {
ClipData.Item item = mClipData.getItemAt(i);
Uri uri = item.getUri();
mArrayUri.add(uri);
// Get the cursor
Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imageEncoded = cursor.getString(columnIndex);
imagesEncodedList.add(imageEncoded);
Toast.makeText(this, ""+uri, Toast.LENGTH_SHORT).show();
Toast.makeText(this, ""+imageEncoded, Toast.LENGTH_SHORT).show();
Toast.makeText(this, ""+imagesEncodedList, Toast.LENGTH_SHORT).show();
cursor.close();
}
Log.v("LOG_TAG", "Selected Images" + mArrayUri.size());
}
}
} 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();
}
super.onActivityResult(requestCode, resultCode, data);
I am working on a address book like Android SDK 14+ app. The users should be able to pick an image from the Gallery to add it to a contact entry.
Running the following code to pick and copy the image is no problem in API 14-20 but does not work in API 21+. The file is not found anymore:
protected void pickFoto() {
if (filePermissionsRequired()) {
askForFilePermissions(new PermissionRequestCompletionHandler() {
#Override
public void onPermissionRequestResult(boolean permissionGranted) {
if (permissionGranted)
addOrEditReceipt();
}
});
return;
}
Intent pickPhotoIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhotoIntent , PICK_FOTO_ACTION);
}
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
...
case PICK_FOTO_ACTION: {
Uri imageUri = intent.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(imageUri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
File imgFile = new File(filePath);
if (imgFile.exists())
// use the file...
else
Toast.makeText(this, "Image file not found", Toast.LENGTH_LONG).show();
break;
}
}
public interface PermissionRequestCompletionHandler {
void onPermissionRequestResult(boolean permissionGranted);
}
private PermissionRequestCompletionHandler permissionRequestCompletionHandler;
public boolean filePermissionsRequired() {
if (Build.VERSION.SDK_INT >= 23)
return checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED;
else
return false;
}
public boolean askForFilePermissions(PermissionRequestCompletionHandler completionHandler) {
if (Build.VERSION.SDK_INT >= 23) {
permissionRequestCompletionHandler = completionHandler;
boolean hasPermission = this.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
if (!hasPermission) {
this.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
return true;
}
}
permissionRequestCompletionHandler = null;
return false;
}
The app has runtime permissions to access the Gallery. So what am I doing wrong? How to access the file on newer API versions?
}
try below code to open the camera and getting result:
File file = new File(Environment.getExternalStorageDirectory() + "/DCIM/", "image" + System.currentTimeMillis() + ".png");
Uri imageUri = Uri.fromFile(file);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, PICK_FOTO_ACTION);
for getting result :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case PICK_FOTO_ACTION: {
Uri imageUri = imageUri;
File imgFile = new File(imageUri.getPath());
if (imgFile.exists())
// use the file...
else
Toast.makeText(this, "Image file not found", Toast.LENGTH_LONG).show();
break;
}
}
}
for getting actual path from uri :
public String getPath(Uri uri)
{
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor == null) return null;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String s=cursor.getString(column_index);
cursor.close();
return s;
}
remove unwanted uri part :
public String RemoveUnwantedString(String pathUri){
//pathUri = "content://com.google.android.apps.photos.contentprovider/-1/2/content://media/external/video/media/5213/ORIGINAL/NONE/2106970034"
String[] d1 = pathUri.split("content://");
for (String item1:d1) {
if (item1.contains("media/")) {
String[] d2 = item1.split("/ORIGINAL/");
for (String item2:d2) {
if (item2.contains("media/")) {
pathUri = "content://" + item2;
break;
}
}
break;
}
}
//pathUri = "content://media/external/video/media/5213"
return pathUri;
}
For versions 21 and higher you can do this , you need to add a condition to check the SDK version for this. Exectute this code in the API 21+ condition block.
String wholeID = DocumentsContract.getDocumentId(imageUri );
String id = wholeID.split(":")[1];
String sel = MediaStore.Images.Media._ID + "=?";
cursor =
getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, sel, new String[]{ id }, null);
try
{
int column_index = cursor
.getColumnIndex(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
path = cursor.getString(column_index).toString();
cursor.close();
}
catch(NullPointerException e) {
}
Call the Gallery with belo code
public static final int SELECT_IMAGE_FROM_GALLERY_CODE = 701;
public static void callGallery(Activity activity) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
activity.startActivityForResult(Intent.createChooser(intent, "Complete action using"),
SELECT_IMAGE_FROM_GALLERY_CODE);
}
In OnActivityResult, read URI and read path from uri.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CommonUtils.SELECT_IMAGE_FROM_GALLERY_CODE) {
if (data != null) {
Uri selectedImageUri = data.getData();
// get path from Uri
String imagepath = getPath(this, selectedImageUri);
if (null != imagepath && (!imagepath.isEmpty())) {
// if the image path is not null and not empty, copy image to sdcard
try {
copyDirectoryOrFile(new File(imagepath), new File(myTargetImageFilePath));
} catch (IOException e) {
e.printStackTrace();
}
// load the image into imageView with the help og glide.
loadImageWithGlide(myImageViewContactImage,
myTargetImageFilePath, myDefaultImagePath, myErrorImagePath, false);
} else {
Toast.makeText(this, "Error: Photo selection failed.", Toast.LENGTH_LONG).show();
}
}
}
}
public void loadImageWithGlide(ImageView theImageViewToLoadImage,
String theLoadImagePath, int theDefaultImagePath, int theErrorImagePath,
boolean theIsSkipMemoryCache) {
if (theIsSkipMemoryCache) {
Glide.with(ProfileActivity.this) //passing context
.load(theLoadImagePath) //passing your url to load image.
.placeholder(theDefaultImagePath) //this would be your default image (like default profile or logo etc). it would be loaded at initial time and it will replace with your loaded image once glide successfully load image using url.
.error(theErrorImagePath)//in case of any glide exception or not able to download then this image will be appear . if you won't mention this error() then nothing to worry placeHolder image would be remain as it is.
.diskCacheStrategy(DiskCacheStrategy.ALL) //using to load into cache then second time it will load fast.
//.animate(R.anim.fade_in) // when image (url) will be loaded by glide then this face in animation help to replace url image in the place of placeHolder (default) image.
.centerCrop()
.into(theImageViewToLoadImage); //pass imageView reference to appear the image.
} else {
Glide.with(ProfileActivity.this)
.load(theLoadImagePath)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.centerCrop()
.into(theImageViewToLoadImage);
}
}
public static String getPath(Context theCtx, Uri uri) {
try {
Cursor cursor = (theCtx).getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
String document_id = cursor.getString(0);
document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
cursor.close();
cursor = (theCtx).getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
cursor.moveToFirst();
String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
cursor.close();
return path;
} catch (Exception e) {
return null;
}
}
public static void copyDirectoryOrFile(File sourceLocation, File targetLocation)
throws IOException {
if (sourceLocation.isDirectory()) {
if (!targetLocation.exists() && !targetLocation.mkdirs()) {
throw new IOException("Cannot create directory " + targetLocation.getAbsolutePath());
}
String[] children = sourceLocation.list();
for (int i = 0; i < children.length; i++) {
copyDirectoryOrFile(new File(sourceLocation, children[i]),
new File(targetLocation, children[i]));
}
} else {
File directory = targetLocation.getParentFile();
if (directory != null && !directory.exists() && !directory.mkdirs()) {
throw new IOException("Cannot create directory " + directory.getAbsolutePath());
}
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
if (out != null) {
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
To load image with glide, add following dependency in app gradle file
compile 'com.github.bumptech.glide:glide:3.7.0'
Im trying to do image slider with gallery images.I can get image from gallery but I could not to display like a slideshow , Could you help me about that how can I do that.
Here is my code
public class MainActivity extends AppCompatActivity {
int PICK_IMAGE_MULTIPLE = 1;
String imageEncoded;
List<String> imagesEncodedList;
public static final int IMAGE_GALLERY_REQUEST = 20;
private ImageView imgPicture;
InputStream inputstream;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgPicture = (ImageView) findViewById(R.id.imageView);
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), PICK_IMAGE_MULTIPLE);}
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
try {
// When an Image is picked
if (requestCode == PICK_IMAGE_MULTIPLE && resultCode == RESULT_OK
&& null != data) {
// Get the Image from data
String[] filePathColumn = { MediaStore.Images.Media.DATA };
imagesEncodedList = new ArrayList<String>();
if(data.getData()!=null){
Uri mImageUri=data.getData();
// Get the cursor
Cursor cursor = getContentResolver().query(mImageUri,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imageEncoded = cursor.getString(columnIndex);
display(null,mImageUri,true);
cursor.close();
} else {
if (data.getClipData() != null) {
ClipData mClipData = data.getClipData();
ArrayList<Uri> mArrayUri = new ArrayList<Uri>();
for (int i = 0; i < mClipData.getItemCount(); i++) {
ClipData.Item item = mClipData.getItemAt(i);
Uri uri = item.getUri();
mArrayUri.add(uri);
// Get the cursor
Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imageEncoded = cursor.getString(columnIndex);
imagesEncodedList.add(imageEncoded);
cursor.close();
display(mArrayUri,null,false);
}
Log.v("LOG_TAG", "Selected Images" + mArrayUri.size());
}
}
} 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();
}
super.onActivityResult(requestCode, resultCode, data);
}
public void display(ArrayList<Uri> list, Uri SUri, Boolean x)
{
if(x){
// declare a stream to read the image data from the SD Card.
InputStream inputStream;
// we are getting an input stream, based on the URI of the image.
try {
inputStream = getContentResolver().openInputStream(SUri);
// get a bitmap from the stream.
Bitmap image = BitmapFactory.decodeStream(inputStream);
// show the image to the user
imgPicture.setImageBitmap(image);
} catch (FileNotFoundException e) {
e.printStackTrace();
// show a message to the user indictating that the image is unavailable.
Toast.makeText(this, "Unable to open image", Toast.LENGTH_LONG).show();
}
}else
{
InputStream inputStream;
// we are getting an input stream, based on the URI of the image.
for (int i= 0; i<list.size(); i++) {
try {
inputStream = getContentResolver().openInputStream(list.get(i));
// get a bitmap from the stream.
Bitmap image = BitmapFactory.decodeStream(inputStream);
// show the image to the user
imgPicture.setImageBitmap(image);
} catch (FileNotFoundException e) {
e.printStackTrace();
// show a message to the user indictating that the image is unavailable.
Toast.makeText(this, "Unable to open image", Toast.LENGTH_LONG).show();
}
}
}
}
}
I want to store my images to internal storage, I searched google and stackoverflow but couldn't get it done, Here is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
imageView = (ImageView) findViewById(R.id.ss);
tv = (TextView) findViewById(R.id.tv);
// Firebase.setAndroidContext(this);
//Firebase ref = new Firebase(FIREBASE_URL);
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
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 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.decodeResource(getResources(),
RESULT_LOAD_IMAGE);
// Find the SD Card path
File filepath = Environment.getExternalStorageDirectory();
// Create a new folder in SD Card
File dir = new File(filepath.getAbsolutePath()
+ "/Save Image Tutorial/");
dir.mkdirs();
// Create a name for the saved image
File file = new File(dir, "myimage.png");
// Show a toast message on successful save
Toast.makeText(MainActivity.this, "Image Saved to SD Card",
Toast.LENGTH_SHORT).show();
try {
output = new FileOutputStream(file);
// Compress into png format image from 0% - 100%
bitmap.compress(Bitmap.CompressFormat.PNG, 100, output);
output.flush();
output.close();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// drawView.load_pic(picturePath);
}
}
I want to get an image from the gallery and store it to internal storage but in this code, it is only saving the name of the file in the directory. If someone could help me to solve this.
You could use FileOutputStream to store your bitmap. After getting the bitmap from gallery, FileOutputStream out = null;
try {
out = new FileOutputStream("fileName"); //Enter the desired filename
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
you are writing Image file on external storage
File filepath = Environment.getExternalStorageDirectory();
so check that you have mention proper permission in android manifest to write data on SD card
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
and also get the bitmap from selected path
Bitmap bitmap = BitmapFactory.decodeFile(picturePath);
instead of
bitmap = BitmapFactory.decodeResource(getResources(),
RESULT_LOAD_IMAGE);
RESULT_LOAD_IMAGE is request code not resource id of selected image
OnChoose Code
chooseimage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (Build.VERSION.SDK_INT >= 23){
boolean result= Utility.checkPermission(getActivity());
if(result) {
galleryIntent();
}
}
else {
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start new activity with the LOAD_IMAGE_RESULTS to handle back the results when image is picked from the Image Gallery.
startActivityForResult(i,LOAD_IMAGE_RESULTS); //LOAD_IMAGE_RESULTS
}
}
});
Also Runtime permission added and Set image on your desired location
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (Build.VERSION.SDK_INT >= 23) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == LOAD_IMAGE_RESULTS) {
onSelectFromGalleryResult(data);
}
}
}
else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && isMediaDocument(data.getData())) {
Bitmap bitmap = null;
Uri selectedImage = data.getData();
String wholeID = DocumentsContract.getDocumentId(selectedImage);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String[] column = {MediaStore.Images.Media.DATA};
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = getActivity().getContentResolver().
query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{id}, null);
String filePath = "";
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
//filePath = cursor.getString(columnIndex);
mPath = cursor.getString(columnIndex);
}
cursor.close();
}
else {
if (requestCode == LOAD_IMAGE_RESULTS && resultCode == getActivity().RESULT_OK && data != null) {
// Let's read picked image data - its URI
Uri pickedImage = data.getData();
// Let's read picked image path using content resolver
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(pickedImage, filePath, null, null, null);
cursor.moveToFirst();
mPath = cursor.getString(cursor.getColumnIndex(filePath[0]));
//edAttach.setText(mPath.toString()); path set anywhere
cursor.close();
}
}
}
}
private void onSelectFromGalleryResult(Intent data) {
Bitmap bitmap=null;
if (data != null) {
try {
bitmap= MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
ivprofile.setImageBitmap(bm);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && isMediaDocument(data.getData())) {
Uri selectedImage = data.getData();
String wholeID = DocumentsContract.getDocumentId(selectedImage);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String[] column = {MediaStore.Images.Media.DATA};
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = getActivity().getContentResolver().
query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{id}, null);
String filePath = "";
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
//filePath = cursor.getString(columnIndex);
mPath = cursor.getString(columnIndex);
//edAttach.setText(mPath); path set anywhere
}
cursor.close();
}
else {
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]);
mPath = cursor.getString(columnIndex).toString();
System.out.println("picturePath" + mPath);
if (!mPath.equalsIgnoreCase(null)) {
edAttach.setText(mPath);
}
cursor.close();
}
// Your Image Copy on Your desired location
if(!mPath.equalsIgnoreCase(""))
{
File filepath = Environment.getExternalStorageDirectory();
// Create a new folder in SD Card
File dir = new File(filepath.getAbsolutePath()
+ "/"+"Save Image Tutorial"+"/");
dir.mkdirs();
// Create a name for the saved image
File file = new File(dir, "myImage.png");
// Show a toast message on successful save
try {
FileOutputStream output = new FileOutputStream(file);
// Compress into png format image from 0% - 100%
bitmap.compress(Bitmap.CompressFormat.PNG, 100, output);
output.flush();
output.close();
Toast.makeText(getActivity(), "Image Saved to SD Card",
Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public boolean hasPermissionInManifest(Context context, String permissionName) {
final String packageName = context.getPackageName();
try {
final PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS);
final String[] declaredPermisisons = packageInfo.requestedPermissions;
if (declaredPermisisons != null && declaredPermisisons.length > 0) {
for (String p : declaredPermisisons) {
if (p.equals(permissionName)) {
return true;
}
}
}
} catch (PackageManager.NameNotFoundException e) {
}
return false;
}
public static boolean isMediaDocument(Uri uri)
{
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
private void galleryIntent()
{
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);//
startActivityForResult(Intent.createChooser(intent, "Select File"),LOAD_IMAGE_RESULTS);
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
galleryIntent();
} else {
//code for deny
}
break;
}
}
Or Permission In your mainfiest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Utility.java
import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
public class Utility {
public static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 123;
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static boolean checkPermission(final Context context)
{
int currentAPIVersion = Build.VERSION.SDK_INT;
if(currentAPIVersion>= Build.VERSION_CODES.M)
{
if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.READ_EXTERNAL_STORAGE)) {
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
alertBuilder.setCancelable(true);
alertBuilder.setTitle("Permission necessary");
alertBuilder.setMessage("External storage permission is necessary");
alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
});
AlertDialog alert = alertBuilder.create();
alert.show();
} else {
ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
return false;
} else {
return true;
}
} else {
return true;
}
}
}
I have an onclick that will allow a user to select a file from gallery like so:
case R.id.ColourCustom:
customBorderChange();
break;
private void customBorderChange() {
final ImageView QPBackground = (ImageView) findViewById(R.id.QPBackground);
menuHandler.removeCallbacks(menuTimer);
menuHandler.postDelayed(menuTimer, 5000);
bgHandler.removeCallbacks(runnableBG);
bgHandler.postDelayed(runnableBG, 2000);
Intent i = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, GALLERY_REQUEST);
File file = getFileStreamPath("QuickPlayBG.png");
if (file.exists()) {
QPBackground.setImageBitmap(getThumbnail("QuickPlayBG.png"));
} else {
String uri21 = "#drawable/bg_green";
int imageResource21 = getResources().getIdentifier(uri21, null, getPackageName());
QPBackground.setBackgroundResource(imageResource21);
}
}
This sends you here:
protected void onActivityResult (int requestCode, int resultCode, Intent data)
{
Uri selectedImageUri;
if (requestCode == GALLERY_REQUEST && resultCode == RESULT_OK && null !=
data) {
selectedImageUri = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImageUri,
filePathColumn, null, null, null);
cursor.moveToFirst();
cursor.close();
}
try {
Bundle extras = data.getExtras();
Bitmap photo = extras.getParcelable("data");
saveBGFile(photo);
} catch (Exception e) {
String errorMessage = "Make your mind up mate!";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
try {
saveQPConfig();
} catch (IOException e) {
String errorMessage = "Saving failed";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
Which saves the file, using saveBGFile:
public void saveBGFile(Bitmap image) {
FileOutputStream out = null;
String filename = "QuickPlayBG.png";
try {
out = new FileOutputStream(filename);
image.compress(Bitmap.CompressFormat.PNG, 100, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
The issue is with this line only:
QPBackground.setImageBitmap(getThumbnail("QuickPlayBG.png"));
It doesn't load anything. If I change "QuickPlayBG.png" to another filename that I am using in another part of my app, it loads fine. Both files are created using the same method. I verified that "QuickPlayBG.png" exists.
Compiler gives me the following hint:
E/﹕ ReadStreamToBuffer : Qmage Stream read error!! required length 12 bytes, but red 0 bytes
E/﹕ isQmage : input SkStreamRewindable length is less than Qmage minimum size : 0
I think it has to do with the way I am saving the image, but I cannot see the fault myself. What could be the problem, that it is not loading the image?
Edit:
Here is the getThumbnail method I am using (works for another filename):
public Bitmap getThumbnail(String filename) {
final Context context = this;
String fullPath = Environment.getExternalStorageDirectory().getAbsolutePath();
Bitmap thumbnail = null;
if (thumbnail == null) {
try {
File filePath = context.getFileStreamPath(filename);
FileInputStream fi = new FileInputStream(filePath);
thumbnail = BitmapFactory.decodeStream(fi);
} catch (Exception ex) {
Log.e("getThumbnail() !exist", ex.getMessage());
}
}
return thumbnail;
}
Use this short and sweet code for this. use intent of gallery.
1.declaire variable.
private static int RESULT_IMG = 1;
String imgString;
2.call intent of gallery on onclick of button.
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
3.onActivityResult to your code.
#Override
protected void onActivityResult(int requestCode, int responseCode, Intent data) {
super.onActivityResult(requestCode, responseCode, data);
try {
if (requestCode == RESULT_IMG && responseCode == RESULT_OK
&& null != data) {
Uri pickedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(pickedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgString = cursor.getString(columnIndex);
cursor.close();
//set bitmap to your imageview
ImageView imgView = (ImageView) findViewById(R.id.imgView);
imgView.setImageBitmap(BitmapFactory.decodeFile(imgString));
} else {
Toast.makeText(this, "please select picture",Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "error message", Toast.LENGTH_LONG)
.show();
}
}