Cannot resolve method checkSelfPermission - java

I'm trying to make my app ready for Android 6 and now I'm stuck to the point where you need to request and check permissions.
I tried the following from the docs:
int permissionCheck = ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.WRITE_CALENDAR);
The problem is that Android Studio says Cannot resolve method 'checkSelfPermission'.
I already included the appcompat and support lib. ContextCompat is known to AS but the method itself isn't known. I don't know what am I doing wrong - in another project I can write this method and it gets recognized.
TargetAPI is 23.
Does anyone know a solution?

Here is how you need to call in various scenarios,
In case of activity:
ContextCompat.checkSelfPermission(MyActivity.this,
Manifest.permission.WRITE_CALENDAR);
In case of fragment:
ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.WRITE_CALENDAR);
In case of any utility class use context:
ContextCompat.checkSelfPermission(context,
Manifest.permission.WRITE_CALENDAR);
Comment below for further information

Oh my godness - what a stupid mistake.
AS imported the supportlib as a jar and this jar was from like 2014. I just replaced the jarimport with the real dependency and know it is working.
Thanks for your help guys!

For Fragment use getActivity().checkSelfPermission
For Activity use this..checkSelfPermission or simply checkSelfPermission

#SuppressLint("NewApi")
I simply used this on top of my page and it works for me...

As silly as it maybe, it could be in the wrong place. I had the same problem. The bolded part is where I had originally put the code. The italic part is where it should have gone
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Log.i("-----------", location.toString());
}
**if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {'some code'}**
}; 'End of LocationListener method
*if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) { 'some code'}*

I had the same problem.
In my case I added a library that was using an old appcompat version, then the compiler could not find the right appcompat.
To fix the problem I added the option {transitive = false} while importing the culprit library, and this fixed the problem.
Now I have:
api ('org.library.using.old.appcompat:1.0.1') {transitive = false}

Trying to use checkSelfPermission() in a Fragment with Kotlin and wondering how to get around Context being null?
Have a look at the sample below, and remember, before the Fragment is attached to the Activity, the Context will be null.
private fun fineLocationPermissionApproved(): Boolean {
val context = context ?: return false
return PackageManager.PERMISSION_GRANTED == checkSelfPermission(
context,
Manifest.permission.ACCESS_FINE_LOCATION
)
}

Related

reference to onLocationChanged is ambiguous

I am trying to make a speedometer using implement LocationListener.
How ever when make a call to onLocationChanged it is saying the reference to onLocationChanged is ambiguous
my codes :
//speedometer and llocation servie
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "First enable LOCATION ACCESS in settings.", Toast.LENGTH_LONG).show();
return;
}
LocationManager lm =(LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0,this);
this.onLocationChanged(null);
After trying for some time I realised it is because this was of doing it is probably deprecated
So I tried tweeking compile sdk from 32 to 29 which seemed to remove that error but added a lot of library related compile errors... somebody please Help !
Thanks in advance
If you have any alternative way of making a speedometer do tell
The error indicates that there are two signatures for that method:
onLocationChanged(List<Location> locations)
onLocationChanged(Location location)
When using null, the compiler cannot determine which one of the two methods you are targeting. You need to cast null either to a Location or a List:
this.onLocationChanged((Location) null);
this.onLocationChanged((List<Location>) null);

Problems implementing the new sensitive clipboard code in Android SDK 13

Has anyone else tried to mark their clipboard copied data as sensitive as per the following recommendation?
https://developer.android.com/about/versions/13/features/copy-paste
clipData.apply {
description.extras = PersistableBundle().apply {
putBoolean(ClipDescription.EXTRA_IS_SENSITIVE, true)
}
}
When I tried to do so, I don't find a clipData.apply method.
How can I set the sensitivity settings in an android app Java code?
apply() is a Kotlin scope function. You appear to be programming in Java, so the Kotlin syntax will not work for you.
By eyeball, the Java equivalent would be:
PersistableBundle extras = new PersistableBundle();
extras.putBoolean(ClipDescription.EXTRA_IS_SENSITIVE, true);
clipData.getDescription().setExtras(extras);

setTargetFragment() getTargetFragment() deprecated

I am using deprecated method setTargetFragment() getTargetFragment() . Using setTargetFragment(target) lets the "called" fragment know where to send the result and calling onActivityResult() manually in this case. check caller fragment like this
if (getTargetFragment() instanceof FragmentA ){
// Some Code
getTargetFragment().onActivityResult(requestCode, Activity.RESULT_OK, returnIntent);
}
Starting new fragment like this
Media_Gallery gallery = new Media_Gallery();
gallery.setTargetFragment(AddMedia.this,104);
FragmentTransaction fragmentTrasaction=getParentFragmentManager().beginTransaction();
fragmentTrasaction.addToBackStack("Image");
fragmentTrasaction.replace(R.id.Main_Layout,gallery,"Image");
fragmentTrasaction.commit();
As i am targeting latest API (33) It's stop working for me. Trying to get logic from here but it's bit confusing to me. Can anyone help me understand how can i replace deprecated method to

Handling a deep link from the google assistant in Java

Looking to handle a deep link from the Google Assistant. As I only have an emulator at the moment I am having trouble testing it (from what I have read it requires a real device). That said, I was wondering if I am handling it the correct way. I am unfamiliar with Kotlin and my code was turning into Spaghetti trying to integrate, so I put this together in my existing launcher activity just to try and get it bootstrapped for now. The manifest and actions.xml were set up like the fitness app tutorial.
Am I doing this correctly?
if (mAuth.getCurrentUser() != null) {
data = this.getIntent().getData();
if (data != null && data.isHierarchical()) {
uriData = data.toString();
containsStart = containsIgnoreCase(uriData,"start");
containsRun = containsIgnoreCase(uriData,"run");
if(containsStart && containsRun) {
Intent intent = new Intent(getApplication(), RunActivity.class);
intent.putExtra("runStart", true);
startActivity(intent);
}
}
else {
checkUserAccType();
}
//Else, if there is no current user, start the Authentication activity
}
A few observations and recommendation about your code:
Instead of using containsIgnoreCase uses getPath() and match the path. See example.
Also, for the activity parameter use URL query param instead of containsIgnoreCase. See example
Starting the activity or fragment. I assume startActivity and checkUserAccType will handle that part. See example.
// Else... section should go one line below.
Authentication. It looks fine. And it seems you're using Firebase by the getCurrent method signature. See example

Android Studio #androidx.annotation.NonNull error when onRequestPermissionResult is called inside MapFragment

Hello I am still fairly new to this, so please help me understand why I am having this error. I have tried many solutions, so I'm just going to list everything I've done since I can't seem to understand why this is happening.
I created a project that integrates GoogleMaps at min SDK 21 to target/compile at SDK 28. I did call the permissions needed inside the Manifesto.
I created a file that extends the MapFragment class and everything seems to be working fine. I am able to check and request permission for the user's location (the box does show up), but when I called the onRequestPermissionResult method it is shown differently and gives me an error saying "error: cannot find symbol class NonNull":
#Override
public void onRequestPermissionsResult(int requestCode, #androidx.annotation.NonNull String[] permissions, #androidx.annotation.NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
In my other Fragment (android.support.v4.app) classes the #androidx.annotation.NonNull is #NonNull instead. I first thought maybe I needed to add implementation 'com.android.support:support-annotations:28.0.0' to the build.gradle, but that wasn't the case. I then tried to just replace the #androidx.annotation.NonNull with #NonNull which made the error go away, but whenever I clicked allow or deny it wasn't hitting the onRequestPermissionResult method.
I created a method that checks for a permission, but it won't let me use requestPermission on its own without checking if the build is greater or equal to SDK 23, but my min SDK is 21. So instead I just checked if the build is greater or equal to 21 and used ActivityCompat to get the requestPermission method and it works. It will check and ask for permission, so I'm thinking maybe the onRequestPermissionResult only works in the MainActivity which is what I don't want. I want to be able to call a method after checking if the request was granted inside the MapFragment. Is it because MapFragment isn't supported with android.support.v4.app? It looks like this:
private boolean checkAskPermission(int requestCode, String permissionString){
if(Build.VERSION.SDK_INT >= 21){
int permission = ContextCompat.checkSelfPermission(mContext, permissionString);
if(permission!=PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(getActivity(), new String[]{permissionString}, requestCode);
return false;
}
}
return true;
}
At this point I don't know what else to try. I thought maybe I wasn't checking the permission correctly inside onRequestPermissionResult when I change #androidx.annotation.NonNull to #NonNull to be able to use it, but the method doesn't hit when I use a break on it.
Please leave detail responses, so I can fully understand my problem. I have been stuck on this for a day.
Edit: Solution
private boolean checkAskPermission(int requestCode, String permissionString){
if(Build.VERSION.SDK_INT >= 23){
int permission = ContextCompat.checkSelfPermission(mContext, permissionString);
if(permission!=PackageManager.PERMISSION_GRANTED){
requestPermissions(new String[]{permissionString}, requestCode);
return false;
}
}
return true;
}
and just changed the #androidx.annotation.NonNull to #NonNull and now it hits the method.
Thanks to Eugene for clearing up SDK permissions. Only SDK 23 and higher require permission.
import that annotation class:
import androidx.annotation.NonNull;
which is either coming from this dependency:
implementation "androidx.annotation:annotation:1.0.0"
or from this dependency, in case not yet using androidx:
implementation "com.android.support:support-annotations:28.0.0"
then you can use it as usual:
#NonNull
The only work-around that I found useful was to fore-go the react-native run-android command and manually go into the react-native library (for me: ProjectHome/node_modules/ModuleIWantToChange/android/src/main/java/FileToChange.java) that was importing androidx.annotation.NonNull, changing that dependency to android.support.annotation.NonNull and then making sure to compile with the com.android.support:support-annotations under "dependencies" in that node_module's "android/build.gradle" file. In my case, I'm using version "com.android.support:support-annotations:25.3.1". You'll have to make sure that you have the version you call out here. Look at what you have installed with Android Studio under $ANDROID_HOME/extras/android/m2repository/com/android/support/support-annotations.
Then, instead of react-native run-android, I moved to the android directory under the project's home directory and ran sudo ./gradlew --stacktrace installDebug (stacktrace is optional) to build and install the apk on my emulator/device.
This might not work for everyone, but it was a tolerable fix in my case.
[...] but the method doesn't hit when I use a break on it.
[...] used ActivityCompat to get the requestPermission [...]
You're in a fragment. Don't ask the activity for permissions. If you ask the fragment you also get callback in the fragment.
requestPermissions(new String[]{permissionString}, requestCode);
Runtime permissions were introduced in API 23 (that's why the method is only available since API 23). Fix your condition. Before that having the permission declared in manifest is enough.
Off-topic: Platform fragments have been deprecated. Use support fragments instead. Extend SupportMapFragment.
#androidx.annotation.NonNull cannot be found because you don't use AndroidX in your project. You can use whatever other #NonNull annotation is available (either from the SDK or from the support library).

Categories

Resources