onactivityresult() is deprecated in android fragment - java

I search on google for onactivityresult() is deprecated. but my problem was not solve . here is the code of fragment
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull #NotNull String[] permissions, #NonNull #NotNull int[] grantResults) {
switch (requestCode){
case CAMERA_REQUEST_CODE:{
if (grantResults.length >0 ){
boolean cameraAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean writeStorageAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if (cameraAccepted && writeStorageAccepted){
pickFromCamera();
}
else {
Toast.makeText(getActivity(), "Please enable camera & storage permission first ", Toast.LENGTH_SHORT).show();
}
}
}
private void pickFromCamera() {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE,"Temp Pic");
values.put(MediaStore.Images.Media.DESCRIPTION,"Temp Description");
// put image uri
image_uri = requireActivity().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
// intent tom start camera
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
startActivityForResult(cameraIntent, IMAGE_PICK_CAMERA_CODE);
}
private void pickFromGallery() {
// pick from gallery
Intent galleryIntent = new Intent(Intent .ACTION_PICK);
galleryIntent.setType("Images/*");
startActivityForResult(galleryIntent, IMAGE_PICK_GALLERY_CODE);
}
}

Kotlin - Below code instead of startActivityForResult deprecation
this method gives the result itself and returns a value.
val resultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
when (result.resultCode) {
Activity.RESULT_OK -> {
// logic
}
else -> {
// logic
}
}
}

Related

How to take storage permission in Android 11

My Topic,
i am trying to take storage permission in android, my permission code works in below andoid 11 ,
but problem is when i try to take storage permission in android 11 then code not works , so please help me..
This is my code:-
This is my AndroidManifest.xml Code
android:requestLegacyExternalStorage="true"
This is my JavaCode Code
#Override
protected void onActivityResult(int _requestCode, int _resultCode, Intent _data) {
super.onActivityResult(_requestCode, _resultCode, _data);
if (_resultCode == RESULT_OK){
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.R){
if (Environment.isExternalStorageManager()){
Toast.makeText(this,"Permission Granted",Toast.LENGTH_SHORT).show();
i.setClass(getApplicationContext(), Main2Activity.class);
startActivity(i);
} else {
_takePermission();
}
}
}
switch (_requestCode) {
default:
break;
}
}
public boolean _isPermissionGranted() {
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.R){
return Environment.isExternalStorageManager();
} else {
int readexternalStoragePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
return readexternalStoragePermission == PackageManager.PERMISSION_GRANTED;
}
}
public void _takePermission() {
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.R) {
try {
Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
intent.addCategory("android.intent.category.DEFAULT");
intent.setData(Uri.parse(String.format("package:%s",getApplicationContext().getPackageName())));
startActivityForResult(intent,100);
} catch (Exception exception){
Intent intent = new Intent();
intent.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
startActivityForResult(intent,100);
}
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},101);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length > 0){
if (requestCode == 101){
boolean readExternalStorage = grantResults[0] == PackageManager.PERMISSION_GRANTED;
if (readExternalStorage){
Toast.makeText(this,"Permission Granted",Toast.LENGTH_SHORT).show();
i.setClass(getApplicationContext(), Main2Activity.class);
startActivity(i);
} else {
_takePermission();
}
}
}
Above is the complete code, please check and tell me what my mistake is, and what is the correct bridge.
Thanks for watching..
android:requestLegacyExternalStorage="true" will not affect if your app targetSdk > 30 (Android 11 and above).
Must add this to manifest:
Request to permission:
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.MANAGE_EXTERNAL_STORAGE}, 1);
Check whether app can access storage:
if (!Environment.isExternalStorageManager())
Request to access "All files and media" access:
Intent intent = new Intent();
intent.setAction(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
Uri uri = Uri.fromParts("package", this.getPackageName(), null);
intent.setData(uri);
startActivity(intent);

take photo but not OCR: android studio

I combined the two Java codes, but I have a problem: when I take a picture and then I want to read the text with this picture, it writes the text of the program-assigned image (not taken photo).
The problem is the combination of commands, which I can not sort. Always read the original image (ImageView is installed with a Bitmap test image).
I tried many times but could not order.
P.S I do not want to save the captured image.
Thanks in advance for the feedback.
my Java code:
public class MainActivity extends AppCompatActivity {
private static final int CAMERA_REQUEST = 1888; ///////
private ImageView imageView;///
private static final int MY_CAMERA_PERMISSION_CODE = 100;////
////////////
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults)
{
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == MY_CAMERA_PERMISSION_CODE)
{
if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(this, "camera permission granted", Toast.LENGTH_LONG).show();
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
else
{
Toast.makeText(this, "camera permission denied", Toast.LENGTH_LONG).show();
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}/////////////
ImageView imageview;
Button btnProcess;
EditText txtView, txtVieww;
Bitmap photo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.imageView = (ImageView)this.findViewById(R.id.image_view);////
Button photoButton = (Button) this.findViewById(R.id.button1);////
imageview = findViewById(R.id.image_view);
btnProcess = findViewById(R.id.btnProcess);
txtView = findViewById(R.id.txtView);
txtVieww = findViewById(R.id.txtVieww);
photo = BitmapFactory.decodeResource(getApplicationContext().getResources(),
R.drawable.newyt);
imageview.setImageBitmap(photo);
/////
photoButton.setOnClickListener(v -> {
if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)
{
requestPermissions(new String[]{Manifest.permission.CAMERA}, MY_CAMERA_PERMISSION_CODE);
}
else
{
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
///////
btnProcess.setOnClickListener(v -> {
TextRecognizer txtRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();
if (!txtRecognizer.isOperational()) {
txtView.setText(R.string.error_prompt);
txtVieww.setText(R.string.error_prompt);
} else {
Frame frame = new Frame.Builder().setBitmap(photo).build();
SparseArray<TextBlock> items = txtRecognizer.detect(frame);
StringBuilder strBuilder = new StringBuilder();
for (int i = 0; i < items.size(); i++) {
TextBlock item = items.valueAt(i);
strBuilder.append(item.getValue());
strBuilder.append("/");
for (Text line : item.getComponents()) {
//extract scanned text lines here
Log.v("lines", line.getValue());
for (Text element : line.getComponents()) {
//extract scanned text words here
Log.v("element", element.getValue());
}
}
}
final String substringi = strBuilder.substring(0, 10).replaceAll("\\s+", "");
final String substringg = substringi.substring(0, 5);
txtView.setText(substringi);
txtVieww.setText(substringg);
}
});
}
}

How to recognize landmarks using Firebase ML kit?

I'm creating an application for recognizing landmarks.
When the image is recognized, the result should fall to onSuccess, but instead comes to onFailure.
The following message is displayed in the Log:
If you have not set up billing, please go to the Firebase Console to set up billing: https://firebase.corp.google.com/u/0/project/_/overview?purchaseBillingPlan= true
If you are specifying a debug API Key override and turning on API Key restrictions, make sure the restrictions are set up correctly.
When I click on the link I see the following page:
https://login.corp.google.com/request?s=firebase.corp.google.com:443/uberproxy/&d=https://firebase.corp.google.com/u/0/project/_/overview%3FpurchaseBillingPlan%3Dtrue%26upxsrf%3DAKKYJRc2HD6ROcy9V9DxnYxw-pd8yGnml-oEi37m5hKhkWurWQ:1557057663745&maxAge=1200&authLevel=2000000&keyIds=X-q,k02
What will I need to to do?
public class RecognizeLandmarks extends AppCompatActivity {
EditText mResultEt;
ImageView mPreviewIv;
TextView tvLName, tvLiD, tvLConfidence, tvLlatitude, tvLlongitude;
public static final int CAMERA_REQUEST_CODE = 200;
public static final int STORAGE_REQUEST_CODE = 400;
public static final int IMAGE_PIC_GALLERY_CODE = 1000;
public static final int IMAGE_PIC_CAMERA_CODE = 1001;
private static final String TAG = "MyLog";
String cameraPermission[];
String storagePermission[];
Uri image_uri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recognize_landmarks);
androidx.appcompat.app.ActionBar actionBar = getSupportActionBar();
actionBar.setSubtitle("Click image button to insert Image");
mResultEt = findViewById(R.id.resultEt);
mPreviewIv = findViewById(R.id.imageIv);
tvLName = findViewById(R.id.tvLName);
tvLiD = findViewById(R.id.tvLiD);
tvLConfidence = findViewById(R.id.tvLConfidence);
tvLlatitude = findViewById(R.id.tvLlatitude);
tvLlongitude = findViewById(R.id.tvLlongitude);
//camera permission
cameraPermission = new String[]{Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE};
//storage permission
storagePermission = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//inflate menu
getMenuInflater().inflate(R.menu.menu_recognize_text, menu);
return true;
}
//handle actionbar item clicks
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId( );
if (id == R.id.addImage) {
showImageImportDialog( );
}
if (id == R.id.settings) {
Toast.makeText(this, "Settings", Toast.LENGTH_SHORT).show( );
}
return super.onOptionsItemSelected(item);
}
private void showImageImportDialog() {
// items to display in dialog
String[] items = {" Camera", " Gallery"};
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("Select Image");
dialog.setItems(items, new DialogInterface.OnClickListener( ) {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if (i == 0) {
//camera option clicked
/*for os Marshmallow and above we need to ask runtime permission for camera and storage*/
if (!checkCameraPermission()) {
//camera permission not allowed, request it
requestCameraPermission();
} else {
//permission allowed, take picture
pickCamera();
}
}
if (i == 1) {
//gallery option clicked
if (!checkStoragePermission()) {
//storage permission not allowed, request it
requestStoragePermission();
} else {
//permission allowed, take picture
pickGallery();
}
}
}
});
dialog.create().show();
}
private void pickGallery() {
//intent to pick image from gallery
Intent intent = new Intent(Intent.ACTION_PICK);
//set intent type to image
intent.setType("image/*");
startActivityForResult(intent, IMAGE_PIC_GALLERY_CODE);
}
private void pickCamera() {
//intent to take image from camera, it will also be save to storage to get high quality image
ContentValues values = new ContentValues( );
values.put(MediaStore.Images.Media.TITLE, "NewPic"); //title of the picture
values.put(MediaStore.Images.Media.DESCRIPTION, "Image to text"); //description
image_uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
startActivityForResult(cameraIntent, IMAGE_PIC_CAMERA_CODE);
}
private void requestStoragePermission() {
ActivityCompat.requestPermissions(this, storagePermission, STORAGE_REQUEST_CODE);
}
private boolean checkStoragePermission() {
boolean result = ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED);
return result;
}
private void requestCameraPermission() {
ActivityCompat.requestPermissions(this, cameraPermission, CAMERA_REQUEST_CODE);
}
private boolean checkCameraPermission() {
/*Check camera permission and return the result
* in order to get high quality image we have to save image to external storage first
* before inserting to image view that`s why storage permission will also be required */
boolean result = ContextCompat.checkSelfPermission(this,
Manifest.permission.CAMERA) == (PackageManager.PERMISSION_GRANTED);
boolean result1 = ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED);
return result && result1;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case CAMERA_REQUEST_CODE:
if (grantResults.length > 0) {
boolean cameraAccepted = grantResults[0] ==
PackageManager.PERMISSION_GRANTED;
boolean writeStorageAccepted = grantResults[0] ==
PackageManager.PERMISSION_GRANTED;
if (cameraAccepted && writeStorageAccepted) {
pickCamera();
} else {
Toast.makeText(this, "permission denied", Toast.LENGTH_SHORT).show( );
}
}
break;
case STORAGE_REQUEST_CODE:
if (grantResults.length > 0) {
boolean writeStorageAccepted = grantResults[0] ==
PackageManager.PERMISSION_GRANTED;
if (writeStorageAccepted) {
pickGallery( );
}
else {
Toast.makeText(this, "permission denied", Toast.LENGTH_SHORT).show( );
}
}
break;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
//got image from camera or gallery
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == IMAGE_PIC_GALLERY_CODE) {
//got image from gallery now crop it
CropImage.activity(data.getData( ))
.setGuidelines(CropImageView.Guidelines.ON) // enable image guidelines
.start(this);
}
if (requestCode == IMAGE_PIC_CAMERA_CODE) {
//got image from camera crop it
CropImage.activity(image_uri)
.setGuidelines(CropImageView.Guidelines.ON) // enable image guidelines
.start(this);
}
}
//get cropped image
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result1 = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result1.getUri( ); // get image uri
//set image to image view
mPreviewIv.setImageURI(resultUri);// past image in iV
//get drawable bitmap for text recognition
BitmapDrawable bitmapDrawable = (BitmapDrawable) mPreviewIv.getDrawable( );
Bitmap bitmap = bitmapDrawable.getBitmap( );
FirebaseVisionImage image = FirebaseVisionImage.fromBitmap(bitmap);
FirebaseVisionCloudDetectorOptions options =
new FirebaseVisionCloudDetectorOptions.Builder( )
.setModelType(FirebaseVisionCloudDetectorOptions.LATEST_MODEL)
.setMaxResults(15)
.build( );
FirebaseVisionCloudLandmarkDetector detector = FirebaseVision.getInstance( )
.getVisionCloudLandmarkDetector(options);
Task<List<FirebaseVisionCloudLandmark>> result = detector.detectInImage(image)
.addOnSuccessListener(new OnSuccessListener<List<FirebaseVisionCloudLandmark>>( ) {
#Override
public void onSuccess(List<FirebaseVisionCloudLandmark> firebaseVisionCloudLandmarks) {
// Task completed successfully
// ...
for(FirebaseVisionCloudLandmark landmark : firebaseVisionCloudLandmarks) {
//Rect bounds = landmark.getBoundingBox();
String landmarkName = landmark.getLandmark( );
tvLName.setText(landmarkName);
String entityId = landmark.getEntityId( );
tvLiD.setText(entityId);
float confidence = landmark.getConfidence( );
tvLConfidence.setText(Float.toString(confidence));
// Multiple locations are possible, e.g., the location of the depicted
// landmark and the location the picture was taken.
for(FirebaseVisionLatLng loc : landmark.getLocations( )) {
double latitude = loc.getLatitude( );
tvLlatitude.setText(Double.toString(latitude));
double longitude = loc.getLongitude( );
tvLlongitude.setText(Double.toString(longitude));
}
}
}
})
.addOnFailureListener(new OnFailureListener( ) {
#Override
public void onFailure(#NonNull Exception e) {
// Task failed with an exception
// ...
Log.d(TAG,e.getMessage());
Toast.makeText(RecognizeLandmarks.this, "Recognizing Failed", Toast.LENGTH_SHORT).show( );
}
});
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
//if there is any error show it
Exception error = result1.getError( );
Toast.makeText(this, "" + error, Toast.LENGTH_SHORT).show( );
}
}
}
}
Result
D/MyLog: If you haven't set up billing, please go to Firebase console to set up billing: https://firebase.corp.google.com/u/0/project/_/overview?purchaseBillingPlan=true. If you are specifying a debug Api Key override and turned on Api Key restrictions, make sure the restrictions are set up correctly
ML Kit's landmark detection does not run on the device itself, but uses Google Cloud Vision. For this reason your project needs to be on a paid plan, before you can use landmark detection. The first 1000 calls are free, after which you will be charged for additional calls.

Replacing a button to go a paid layout with a swiping motion

I am building an app. One of the features I have is a paid option in which the user has access to an additional layout. Right now, the user can get there by clicking a button. Instead, I would like to have a swiping motion- if the user swipes down, it will ask for permission for the paid layout. If they do pay, when they swipe up, they can access the original layout.
Here is my main activity :
public class MainActivity extends AppCompatActivity {
EditText editText2;
Button btn_purchase;
ImageView imageView2;
String skuId;
SessionManager sessionManager;
// create new Person
private BillingClient mBillingClient;
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sessionManager=new SessionManager(MainActivity.this);
if(sessionManager.getPurchased()){
Intent intent = new Intent(MainActivity.this, PaidActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
btn_purchase=findViewById(R.id.btn_purchase);
imageView2 = (ImageView) findViewById(R.id.imageView2);
mBillingClient = BillingClient.newBuilder(MainActivity.this).setListener(new PurchasesUpdatedListener() {
#Override
public void onPurchasesUpdated(int responseCode, #Nullable List<Purchase> purchases) {
if (responseCode == BillingClient.BillingResponse.OK
&& purchases != null) {
for (Purchase purchase : purchases) {
//TODO: Handle purchase
// handlePurchase(purchase);
Log.e("Main", "handle Purchase ");
Log.e("MainAct", "onPurchasesUpdated() response: " + responseCode);
Log.e("dev", "successful purchase...");
String purchasedSku = purchase.getSku();
Log.e("dev", "Purchased SKU: " + purchasedSku);
String purchaseToken = purchase.getPurchaseToken();
sessionManager.savePurchased(true);
Intent intent = new Intent(MainActivity.this, PaidActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
} else if (responseCode == BillingClient.BillingResponse.USER_CANCELED) {
// Handle an error caused by a user cancelling the purchase flow.
} else {
// Handle any other error codes.
}
}
}).build();
List<String> skuList = new ArrayList <> ();
skuList.add("appsubscription2018");
SkuDetailsParams.Builder params = SkuDetailsParams.newBuilder();
params.setSkusList(skuList).setType(BillingClient.SkuType.INAPP);
mBillingClient.querySkuDetailsAsync(params.build(),
new SkuDetailsResponseListener() {
#Override
public void onSkuDetailsResponse(int responseCode, List<SkuDetails> skuDetailsList) {
// Process the result.
if (responseCode == BillingClient.BillingResponse.OK && skuDetailsList != null) {
Log.e("MainActivity", "onSkuDetailsResponse: success");
for (SkuDetails skuDetails : skuDetailsList) {
Log.e("MainActivity", "products: "+skuDetailsList);
String sku = skuDetails.getSku();
skuId = skuDetails.getSku();
String price = skuDetails.getPrice();
if ("appsubscription2018 ".equals(sku)) {
Log.e("MainActivity", "product is appsubscription2018 ");
// mPremiumUpgradePrice = price;
}
}
}
}
});
btn_purchase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mBillingClient.startConnection(new BillingClientStateListener() {
#Override
public void onBillingSetupFinished(#BillingClient.BillingResponse int billingResponseCode) {
if (billingResponseCode == BillingClient.BillingResponse.OK) {
// The billing client is ready. You can query purchases here.
// The billing client is ready. You can query purchases here.
BillingFlowParams flowParams = BillingFlowParams.newBuilder()
.setSku("appsubscription2018")
.setType(BillingClient.SkuType.INAPP)
.build();
int responseCode = mBillingClient.launchBillingFlow(MainActivity.this, flowParams);
if (responseCode != BillingClient.BillingResponse.OK) {
Log.e("Main", "launchBillingFlow ok");
}
}
}
#Override
public void onBillingServiceDisconnected() {
// Try to restart the connection on the next request to
// Google Play by calling the startConnection() method.
}
});
}
});
imageView2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (checkFilePermission(MainActivity.this)){
getPhoto();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode ==1 && resultCode == RESULT_OK && data != null) {
Uri selectedImage = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
imageView2.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static boolean checkFilePermission(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}, 1);
}
});
AlertDialog alert = alertBuilder.create();
alert.show();
} else {
ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
}
return false;
} else {
return true;
}
} else {
return true;
}
}
public void getPhoto() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent,1);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode ==1){
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED);{
getPhoto();
}
}
}
}

Android Multiple Permissions Error

I have a method that should check if some permission that I need to have are Granted or not :
public boolean checkCamera(){
String[] permissions= new String[]{
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.CAMERA};
int result;
List<String> listPermissionsNeeded = new ArrayList<>();
for (String p:permissions) {
result = ContextCompat.checkSelfPermission(getApplicationContext(),p);
if (result != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(p);
}
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),MULTIPLE_PERMISSIONS );
return false;
}
return true;
}
If not, it request these permissions. The problem is, if I denied one of them it pass as valid Permission.
private void requestPermissionCamera(){
if(checkCamera()){
values.put(MediaStore.Images.Media.TITLE, "New Picture");
values.put(MediaStore.Images.Media.DESCRIPTION, "From your Camera");
imageUri = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent,requestCodeCamera);
}
}
In the moment that checks, it's not returning false as it should and on RequestResult the same thing.
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode){
case MULTIPLE_PERMISSIONS:
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
values.put(MediaStore.Images.Media.TITLE, "New Picture");
values.put(MediaStore.Images.Media.DESCRIPTION, "From your Camera");
imageUri = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent,requestCodeCamera);
} else {
Toast.makeText(this, "Not All permissions are granted", Toast.LENGTH_SHORT).show();
}
break;
case READ_STORAGE:

Categories