Android Studio, Chipmunk, Bluetooth, Java - java

I am new to Stackoverflow.
I get the following error and do not understand why:
incompatible types: cannot be converted to Context
Code snippet:
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Add the name and address to an array adapter to show in a ListView
if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT)) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
The error line did not show up!
The error line is:
if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT)) {
I have permissions set in my .xml file.
I am very new to Android Studio!
Event Log output:
C:\Users\jsla3009\AndroidStudioProjects\Test_Bluetooth\app\src\main\java\com\example\test_bluetooth\MainActivity.java:97: error: incompatible types: cannot be converted to Context
if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT)) {
^
C:\Users\jsla3009\AndroidStudioProjects\Test_Bluetooth\app\src\main\java\com\example\test_bluetooth\MainActivity.java:
uses or overrides a deprecated API.
Recompile with -Xlint:deprecation for details.
C:\Users\jsla3009\AndroidStudioProjects\Test_Bluetooth\app\src\main\java\com\example\test_bluetooth\MainActivity.java:
uses unchecked or unsafe operations.
Recompile with -Xlint:unchecked for details.
Some messages have been simplified; recompile with -Xdiags:verbose to get full output

this always references the object you are currently in.
Your error means that you are trying to pass something other than a Context as your first argument in checkSelfPermission, which means that this is not a Context.
Check that MainActivity extends Context or some subclass of it, e.g. AppCompatActivity.
Check that your code is not inside of an anonymous class. If it is, use MainActivity.this instead of this to clarify you mean to pass the MainActivity instance and not the instance of your anonymous class.
If that doesn't help, please share your entire class!

Related

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

What is the following Java/Android syntax actually doing?

I came across the following syntax, which is alien to me. I know String[] is a String array, but what are the curly braces doing
new String[]{Manifest.permission.ACCESS_FINE_LOCATION}
in the following code snippet:
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
}
Calling this Android method displays a dialog box that prompts the app to grant permission and invokes onRequestPermissionsResult when the choice is made. Once this permission has been granted to the system, startAcquisition, stopAcquisition, and acquireGeoPosition are granted access to the location services.
new String[]{Manifest.permission.ACCESS_FINE_LOCATION}
For this syntax it an inline initializing for a list of string.

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

Volley onErrorResponse getString occassionally returns null

Be great if someone can share a solution to this seemingly simple problem, as my app crashes when attempting to get a String Resource using the following line in my application within the onErrorResponse section of a simple Volley request:
mTextView.setText(sActivity.getString(R.string.connection_error,
customMessageParameter));
This issue appears to only occur for some users (despite attempting to replicate the crash myself), which is reported via Fabric, namely the following:
Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual
method 'java.lang.String android.content.Context.getString(int)' on a null
object reference at
com.appname.MyFragment$13.onErrorResponse(MyFragment.java:651)
I ensure the Activity sActivity variable is initialised using the following function, which is invoked in each lifecycle call from onAttach to ensure it's available:
private void setActivity(Activity activity, Context context) {
if (activity != null) {
sActivity = activity;
} else if (getActivity() != null) {
sActivity = getActivity();
} else if (context != null) {
sActivity = (Activity) context;
}
}
I understand how to check the getString() call is not equal to null beforehand and how this can ensure the app will not crash, yet I need to obtain dynamic values from the String Resources at run-time that will vary.
From what I've gathered, the activity instance can vary using asynchronous network calls that can result in this issue. I've also considered simply using getString() on its own and also getResources().getString(), yet I'm unsure if this will prevent the issue from arising.
You should not pass the activity to the fragment and store it that way, this is likely the cause of your problem. Just use getActivity() from inside the fragment.
Also, your setActivity code does not necesarilly guarantee that sActivity won't be null. What happens if all 3 conditionals happen to be null? There is no final else to catch the situation where all 3 are null. Plus, Android can be funky sometimes while fragments/activites are inflating. Theres a good chance all 3 of those variables are null at the time of OnAttach. Either way, getActivity() should return what you need if you use it in the OnCreate or after the Fragment has fully been inflated. You shouldn't have an activity variable since getActivity does exactly what you need, and what happens when the activity changes but you have an older version of it stored in memory that you try to call methods on?
Also, use getResources().getString(), since you are getting the string from your string resources.
To summarize, your line of code should look like this instead (with no need for your setActivity method or sActivity variable).
getActivity().getResources().getString(R.string.connection_error)
It's been a while, so let me know if this doesn't work for you and I can try to help you further.

Using requestPermissions getting error message

Trying to request permission in apk 23 using this
requestPermissions(this,new String[]{permission.ACCESS_FINE_LOCATION}, 8);
and my android manifest has access_fine_location in it, but when I try to compile I get this:
error: cannot find symbol
requestPermissions(this,
^
symbol: method requestPermissions(GMGeolocation,String[],int)
location: class GMGeolocation
I've tried pulling examples from all the other posts on this but it still gives me this error. Any idea what I'm doing wrong?
Here's related code snippet
public class GMGeolocation {
public void GMGeolocation_Init() {
RunnerActivity.ViewHandler.post( new Runnable() {
public void run() {
requestPermissions(this,new String[]{permission.ACCESS_FINE_LOCATION}, 8);
// Acquire a reference to the system Location Manager
locationManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);
// Try and restore the current location from a cached value
provideLocation(locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER));
provideLocation(locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER));
}});
}
you are not handling it properly, firstly you are requesting permission, then on the very next line using the location services while you can use it once permission is granted on onRequestPermissionsResult()
Check this guide to implement it properly OR set your app target to 22 if you don't want to use runtime permissions
Hope it will help you

Categories

Resources