I'm writting a code that the user can upload video from his phone.
My only problem is that i dont know how to get/save the file.
With the intent the user access to his libary and choose his video.
But then i dont know how to get what he choose
Here is my code
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
btnVideo.setOnClickListener(this);
btnAudio.setOnClickListener(this);
}
#Override
public void onClick(View view) {
int id = view.getId();
switch (id){
case R.id.btnUploadVideo:
if(!checkStoragePermission())return;
uploadVideo();
break;
case R.id.btnUploadAudio:
break;
}
}
private void uploadVideo() {
Intent intent = new Intent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Video"),OPEN_MEDIA_PICKER);
}
private boolean checkStoragePermission(){
int resultCode = ActivityCompat.checkSelfPermission(getContext(),
android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
boolean granted = resultCode == PackageManager.PERMISSION_GRANTED;
if (!granted){
ActivityCompat.requestPermissions(
getActivity(),
new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},
PICK_VIDEO_REQUEST /*Constant Field int*/
);
}
return granted;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PICK_VIDEO_REQUEST && grantResults[0] == PackageManager.PERMISSION_GRANTED){
uploadVideo();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == PICK_VIDEO_REQUEST) {
Uri selectedImageUri = data.getData();
}
}
}
What should i do on the "onActivityResult"? How should i save/get the user choose.
My only problem is that i dont know how to get/save the file.
Your code has nothing to do with a file.
If you want the use to pick a file, use a third-party file-chooser library.
Your code is having the user choose a piece of content, and that content does not have to be a file, let alone a file that you have direct filesystem access to.
You are welcome to use data.getData() to get the Uri to the content, then use ContentResolver and openInputStream() to get an InputStream on that content, if that meets your needs.
Related
I am trying to choose an image from device's gallery, crop it and then display it in an imageView. After I click on an image in image selector, the app quits with logcat message showing V/FA: Inactivity, disconnecting from the service. I am running a service in background to get data from firestore.
I have also tried using cropping libraries like https://github.com/ArthurHub/Android-Image-Cropper but the behaviour was same.
I also tried the following.
FABfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_IMAGE_REQUEST);
}
});
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){
mImageUri = data.getData();
imageView.setImageURI(result.getUri());
}
}
Please help to resolve this issue.
Use these methods to choose image from gallery:
public void showGallery() {
if (hasPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
loadGallery();
} else {
requestPermissionsSafely(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
}
}
private void loadGallery() {
Intent choose = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(choose, PICK_IMAGE_GALLERY);
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
loadGallery();
}
break;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_GALLERY) {
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = data.getData();
}
}
}
And:
#TargetApi(Build.VERSION_CODES.M)
public void requestPermissionsSafely(String[] permissions, int requestCode) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(permissions, requestCode);
}
}
#TargetApi(Build.VERSION_CODES.M)
public boolean hasPermission(String permission) {
return Build.VERSION.SDK_INT < Build.VERSION_CODES.M ||
checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED;
}
I am just making an app which will capture image by camera and show in another activity and then upload on firebase that work fine .But I want to attach a feature that when this app is installed in any mobile then go to app permissions like below image
this is my code first activity code
camera = (ImageView) findViewById(R.id.takePic);
camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_REQUEST_CODE);
// Intent intent = new Intent(Home.this,PostActivity.class);
// startActivity(intent);
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST_CODE && resultCode==RESULT_OK)
{
Uri uri = data.getData();
Log.e("Image : ", uri.toString());
Intent intent = new Intent(this, PictureActivity.class);
intent.putExtra("imgUrl", uri.toString());
startActivity(intent);
}
}
this is second activity code
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
// path = (Uri) bundle.get("imgUrl");
Log.e("ashish", bundle.getString("imgUrl") + "");
path = Uri.parse(bundle.getString("imgUrl"));
}
ImageView selfiiii = (ImageView) findViewById(R.id.mySelfie);
selfiiii.setImageURI(path);
A work around for this is by opening the app setting. Not the direct permission panel.
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivity(intent);
or you could do a runtime permission request. To open dialog
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
1);
and to get result
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case 1: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Permitted! do Something
} else {
Toast.makeText(MainActivity.this, "Permission denied to read your External storage", Toast.LENGTH_SHORT).show();
}
return;
}
}
}
I want to give storage permission for my app. My code working perfect till Marshmallow, only problem in Nougat
The below method always return false in nougat even permission granted manually from settings.
private boolean checkWriteExternalPermission() {
String permission = "android.permission.WRITE_EXTERNAL_STORAGE";
int res = getApplicationContext().checkCallingOrSelfPermission(
permission);
return (res == PackageManager.PERMISSION_GRANTED);
}
I used this for Nougat and allow permission but above method still returns false.
void storagePermission(){
StorageManager sm = (StorageManager)getSystemService(Context.STORAGE_SERVICE);
StorageVolume volume = sm.getPrimaryStorageVolume();
Intent intent = volume.createAccessIntent(Environment.DIRECTORY_PICTURES);
startActivityForResult(intent, 1);
}
Please help me to resolve this.
You should use libs: https://github.com/hotchemi/PermissionsDispatcher
#RuntimePermissions
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MainActivityPermissionsDispatcher.storagePermissionWithCheck(this);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// NOTE: delegate the permission handling to generated method
MainActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
}
#NeedsPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
void storagePermission(){
StorageManager sm =(StorageManager)getSystemService(Context.STORAGE_SERVICE);
StorageVolume volume = sm.getPrimaryStorageVolume();
Intent intent = volume.createAccessIntent(Environment.DIRECTORY_PICTURES);
startActivityForResult(intent, 1);
}
#OnPermissionDenied(Manifest.permission.WRITE_EXTERNAL_STORAGE)
void showDeniedForCamera() {
// don't allow code here
}
#OnNeverAskAgain(Manifest.permission.WRITE_EXTERNAL_STORAGE)
void showNeverAskForCamera() {
// neverAskAgain code here
}
}
You should add this code:
public void onActivityResult(final int requestCode, int resultCode, final Intent data){
if(requestCode==1) {
switch (resultCode) {
case Activity.RESULT_OK:
getContentResolver().takePersistableUriPermission(data.getData(),
Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
break;
}
}
}
I want to request permission to read external storage on runtime. When I click on a Button the app should ask for permission, but the dialog does not show up when button is clicked. Code (This is from a Fragment):
private Button photo;
//Constants
private static final int GALLERY_INTENT = 2339;
private static final int REQUEST_EXTERNAL_STORAGE = 4435;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_profile, container, false);
photo = (Button) rootView.findViewById(R.id.photoButton);
photo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//start permission check for gallery
//check if permission is granted
if(ActivityCompat.checkSelfPermission(getContext(),
Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED){
//if permission is not granted, ask for permission.
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_EXTERNAL_STORAGE);
}else{
//if permission already granted, start gallery intent.
uploadPhotoToFirebase();
}
}
});
return rootView;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GALLERY_INTENT && resultCode == RESULT_OK){
Uri uri = data.getData();
StorageReference storageReference = FirebaseStorage
.getInstance()
.getReference("profile_images/"+FirebaseAuth
.getInstance()
.getCurrentUser()
.getUid()
);
storageReference.putFile(uri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
//File successfully uploaded
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
//File upload not successful
}
});
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case REQUEST_EXTERNAL_STORAGE:
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
//Permission to read external storage GRANTED
uploadPhotoToFirebase();
}else{
//Permission to read external storage DENIED
}
}
}
private void uploadPhotoToFirebase(){
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, GALLERY_INTENT);
}
}
Anyone knows why the dialog requesting permission does not show up here?
For the dialog to appear, you need to:
Have a targetSdkVersion of 23 or higher
Have the permission(s) that you are requesting also in the manifest, with <uses-permission> elements
Be running on Android 6.0 or higher
I want to get photo from my photo gallery to crop it, but the path is null. Andorid5.0 can use this way, but Android 6.0 and Android 7.0 can't use this way. I have got this app permission.
public void initPop(View view) {
albums = (TextView)view.findViewById(R.id.albums);
cancel = (LinearLayout) view.findViewById(R.id.cancel);
albums.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
popupWindow.dismiss();
Intent openAlbumIntent = new Intent(Intent.ACTION_GET_CONTENT);
openAlbumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
startActivityForResult(openAlbumIntent, PHOTOZOOM);
}
});
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
popupWindow.dismiss();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) {
return;
}
Uri uri = null;
switch (requestCode) {
case PHOTOZOOM:
if (data == null) {
return;
}
uri = data.getData();
String[] proj = {
MediaStore.Images.Media.DATA
};
Cursor cursor = getContentResolver().query(uri, proj, null, null, null);
if (cursor != null) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
Log.i("Ienning", "onActivityResult: the cursor is " + column_index);
path = cursor.getString(column_index);
}
Intent intent3 = new Intent(PersonCenter.this, ClipActivity.class);
intent3.putExtra("path", path);
Log.i("Ienning", "The Path is " + path);
startActivityForResult(intent3, IMAGE_COMPLETE);
break;
case IMAGE_COMPLETE:
final String temppath = data.getStringExtra("path");
editor.putString("temppath", temppath);
editor.commit();
head.setImageBitmap(getLoacalBitmap(temppath));
break;
default:
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
And permission code:
public void getpermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE))
{
new AlertDialog.Builder(this)
.setMessage("get permission")
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(PersonCenter.this, new String[] {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS}, MY_PERMISSIONS_REQUEST_WRITE_STORAGE);
}
}).show();
} else {
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS}, MY_PERMISSIONS_REQUEST_WRITE_STORAGE);
}
}
else {
Log.i("Ienning", " this is ok manifest permission");
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == MY_PERMISSIONS_REQUEST_WRITE_STORAGE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.i("Ienning", "onRequestPermissionResult: the result permission is ok!");
} else {
if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Toast.makeText(this, "permission denied!", Toast.LENGTH_SHORT).show();
}
}
return;
}
}
And loginfo is
10-28 19:39:44.424 25265-25265/com.example.ienning.ncuhome I/Ienning: onActivityResult: the cursor is 0
10-28 19:39:44.425 25265-25265/com.example.ienning.ncuhome I/Ienning: The Path is null
Andorid5.0 can use this way
You did not test it very well. Your approach will fail on all Android devices, at least some of the time. It will fail more frequently on Android 6.0+.
Your code makes two invalid assumptions:
You assume that the Uri that comes back from ACTION_GET_CONTENT has something to do with the MediaStore. This is incorrect. The Uri that comes back from ACTION_GET_CONTENT can be anything that the user-selected activity wants to return. All that is more-or-less guaranteed is that you can use ContentResolver and openInputStream() to read the content.
You assume that the MediaStore will always give you a DATA column that is usable. That is not a requirement, even if the MediaStore happens to know about the Uri (see the previous bullet).
If the scheme of the Uri that you get back from ACTION_GET_CONTENT is file, then getPath() will be a filesystem path. You may be able to use that path (otherwise, it is a bug in the third-party app that gave you that Uri).
More commonly, the scheme of the Uri will be content. In that case, you can use ContentResolver and openInputStream() to read in the content identified by that Uri, but there is no required filesystem path behind that Uri. That Uri can point to anything the other developer wants: BLOB columns in databases, files in locations that you cannot access, data that needs to be downloaded because it is not yet on the device, etc.