After upgrading to appcompat 25.1.0 I've started getting weird errors.
In my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
I get lint error:
AppCompatActivity.onCreate can only be called from within the same library group (groupId=com.android.support)
How to prevent such behavior?
As previous responses highlighted, it is bug. I recommend not to disable the specific lint warning project-wide, but for that method only. Annotate your method as follows:
#SuppressLint("RestrictedApi")
#Override
public void setupDialog(Dialog dialog, int style) {
super.setupDialog(dialog, style);
//your code here
}
As Felipe already pointed out in his comment this is a bug in the pre-release version of the tools.
You can workaround it for now, until Google release a fix, by adding the following into your project module's build.gradle file:
android {
lintOptions {
disable 'RestrictedApi'
}
}
It's worth noting that this may hide true errors in your project as it suppresses all errors of that type, so the better option would be to downgrade the version of Android Studio and the tools used in the project.
Disabling the warning in lintOptions doesn't look a good option it's better to suppress inspection at the statement level.
Add this comment above the line of code which gives the warning:
//noinspection RestrictedApi
Related
I moved my Eclispe project to Android Studio, but it outputs a lot of deprecated errors when built. I tried some methods, but they don't work.
Try placing this at the top of the methods:
#SuppressWarnings("deprecation")
Example
#SuppressWarnings("deprecation")
public void testMethod(){
...
}
For a brief explaination go to this link:
https://stackoverflow.com/questions/7397996/what-is-suppresswarningsdeprecation-and-unused-in-android
Update:
It seems that there is also some known issues with deprecations. You might want to read this for more info:
stackoverflow.com/questions/26921774/how-to-avoid-deprecation-warnings-when-suppresswarningsdeprecation-doesnt
I have a custom Gradle plugin that uses the following code:
project.getGradle().addListener(new DependencyResolutionListener() {
#Override
void beforeResolve(ResolvableDependencies resolvableDependencies) {
depsToAdd.each { dep ->
compileConfig.getDependencies()
.add(project.getDependencies()
.create(dep)
}
}
#Override
void afterResolve(ResolvableDependencies resolvableDependencies) {
}
})
This seems to work fine from command line. However, if I refresh gradle from Android Studio, it barfs with Cannot change configuration :app:compile after it has been resolved
My guess is there is some sort of caching going on or Studio builds more variants (I just run the assemble for the variant I want from command line which works every time).
Does anyone know what might be going on and how best to resolve this?
I managed to figure this out. The way do this is to add a DependencyResolutionListener in which you add the dependencies and then remove the listener so it doesn't try to add them on later resolution steps.
compileDeps = project.getConfigurations().getByName("compile").getDependencies()
project.getGradle().addListener(new DependencyResolutionListener() {
#Override
void beforeResolve(ResolvableDependencies resolvableDependencies) {
compileDeps.add(project.getDependencies().create("org.foo:bar:$version"))
project.getGradle().removeListener(this)
}
#Override
void afterResolve(ResolvableDependencies resolvableDependencies) {}
})
I have a working example of a plugin that uses this here
i have a question regarding development environments settings.
i am trying to see if there is any possibility to make a compilation warning in a development environment(eclipse,android studio)for android applications using a deprecated feature(could be a method , constructor or whatever you can think of ). until now i am working manually to find the use of this deprecated features , and my boss asked me to look for an automatic settings in my idea ...
so lets say for a specific code :
protected void onPrepareDialog(int paramInt, Dialog paramDialog)
{
try
{
super.onPrepareDialog(paramInt, paramDialog);
AlertDialog localAlertDialog = (AlertDialog)paramDialog;
localAlertDialog.setTitle("Passphrase required");
((TextView)localAlertDialog.findViewById(2131230727)).setText(Preferences.getConfigName(this, getConfigFile()));
Button localButton = localAlertDialog.getButton(-3);
if (this.mOpenVpnService != null);
for (boolean bool = true; ; bool = false)
{
localButton.setEnabled(bool);
return;
}
i have several deprecated features here , and android studio declares it , but what i need is a configuration for this warning to be automated and save me the need of walking through each class manually ...
Select Analyze > Inspect Code to run lint on your project. It should detect any deprecated methods, as well as others common mistakes in your project.
You can select "Run inspection by name" and there you can find "Deprecated API usage" (Java / Code maturity issues).
For me the best solution is add this lines in the file build.gradle(project:appname)
allprojects {
tasks.withType(JavaCompile) {
options.compilerArgs << "-Xlint:unchecked" << "-Xlint:deprecation"
}
Then all the deprecated methods in the java files appear in the build tab:
deprecated api tab android studio
This works on gradle 5.1.1
I use a version switch to support older Android versions.
int sdk = Build.VERSION.SDK_INT;
if (sdk < Build.VERSION_CODES.HONEYCOMB) {
ColorDrawable colorDrawable = new ColorDrawable(shapeColor);
//noinspection deprecation
viewHolder.shape.setBackgroundDrawable(colorDrawable);
} else {
viewHolder.shape.setColor(shapeColor);
}
When build the project with Gradle from the command line the following warning is output by Lint:
app/src/main/java/com/example/MyApp/CustomListAdapter.java:92: warning:
[deprecation] setBackgroundDrawable(Drawable) in View has been deprecated
viewHolder.shape.setBackgroundDrawable(colorDrawable);
^
Can I annotate the specific line or method to mute the warning (since I do it on purpose)? I do not want to disable all warnings.
Case is important, use the following either inline or class-wide:
#Suppress("DEPRECATION")
This is in Kotlin.
I've noticed that the #SuppressLint("deprecated") inline annotation won't be picked up anymore - while #SuppressWarnings("deprecation") is being picked up.
one can disable the Deprecation checks for the Gradle linter with lintOptions within the module-level build.gradle file; while there is no chance to define individual files like that:
android {
lintOptions {
disable 'Deprecation'
}
}
or on can assign one rather detailed lint.xml configuration file with LintOptions:lintConfig (when settings showAll true, it will still show the warnings - no matter the provided XML configuration):
android {
lintOptions {
lintConfig file("lint.xml")
showAll false
}
}
where one can add individual files, by adding their paths:
<?xml version="1.0" encoding="UTF-8"?>
<lint>
<issue id="Deprecation" severity="Error">
<ignore path="app/src/main/java/com/example/MyApp/CustomListAdapter.java" />
</issue>
</lint>
The source code of com.android.builder.model.LintOptions might explain, what actually happens there (and confirms about 50% of what I've wrote).
in order to get rid of the inline warnings in Android Studio... that linter appears to be another linter - and these annotations do not affect the linter of the Gradle build (it may be required to use this combined with one of the methods stated above, in order to ignore known deprecated classes and methods):
//noinspection deprecation
update The Android Studio 2.3 release notes mention a new feature:
Lint Baseline: With Android Studio 2.3, you can set unresolved lint warnings as a baseline in your project. From that point forward, Lint will report only new issues. This is helpful if you have many legacy lint issues in your app, but just want to focus on fixing new issues. Learn more about Lint baseline and the new Lint checks & annotations added in this release.
here it's explained, how to create a Lint warnings baseline - which records the detected warnings into an XML file and then mutes them (which is way better than to have the code annotations inline, distributed all over the place); I'd assume, that options lintConfig and baseline should be combine-able (depending on the requirements).
android {
lintOptions {
baseline file("lint-baseline.xml")
}
}
Just something new: Not sure about Android Studio, but, to remove this warning from this line, you can use:
//noinspection deprecation
This removes the warning from the next line.
E.g:
//noinspection deprecation
e.setBackgroundDrawable(editTextDrawable);
It won't show an error. However, as #JJD said, this still outputs the warning to the console. But at least you can have a nice error-less code which can be useful like for Git for example. And, this prevents the problem with #SupressWarnings, which is it ignores all warnings in the method. So if you have something deprecated that you are not aware of, #SupressWarnings will hide it and you will not be warned. That is the advantage of the //noinspection
I ran into a similar problem. First I got a compiler warning:
:compileDebugJava
Note: /path/file.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Which you can suppress with #SuppressWarnings("deprecation") or just ignore since it is a warning and does cause your build to fail.
Additionally I got the lint error (details in build/lint-results.html):
Call requires API level 13 (current min is 9)
This could be suppressed by adding #SuppressLint("NewApi"). Alternatively you could use #TargetApi(13) to hint that the method/class may use methods that depend on API version 13, rather than what you have set as minSdkVersion (e.g. 9).
The annotations can only be done at a class or function level, not for a single line. Also note that "deprecation" should not be capitalized, while that didn't seem to matter for "NewApi".
To avoid lint warnings, always split functions so one function deals with the old system and other one deals with the new system. The old can supress the warning safely. The new one should be annotated to be used only on newest api levels.
This is an example on how it should look:
#SuppressWarnings("deprecation")
private static int getVersionCode_old(#NonNull Context appContext) {
PackageInfo pInfo;
try {
pInfo = appContext.getPackageManager().getPackageInfo(appContext.getPackageName(), 0);
return pInfo.versionCode;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
#RequiresApi(api = Build.VERSION_CODES.P)
private static int getVersionCode_new(#NonNull Context appContext) {
PackageInfo pInfo ;
try {
pInfo = appContext.getPackageManager().getPackageInfo(appContext.getPackageName(), 0);
return (int) pInfo.getLongVersionCode();
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
public static int getVersionCodeUniversal(#NonNull Context appContext)
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
return getVersionCode_new(appContext);
}
else
{
return getVersionCode_old(appContext);
}
}
Another important hint to avoid lint warnings: if you are using a whole deprecated class then you should remove all explicit imports for that class. Then just access to that class directly using its full path, and only do it in the old versions of your functions.
And finally, you should consider start using androidX, the new Google libraries where you will find a lot of universal functions ready to use. Then you can save a lot of time with this kind of small problems. For example, you can remove all the code of the above example and simply use this new and universal androidX function:
PackageInfo.getLongVersionCode()
You need to create a lint.xml file to tell lint what to ignore.
http://tools.android.com/tips/lint/suppressing-lint-warnings see this for more details
yours might look a little like this
<?xml version="1.0" encoding="UTF-8"?>
<lint>
<!-- Disable the given check in this project -->
<issue id="Deprecation">
<ignore path="app/src/main/java/com/example/MyApp/CustomListAdapter.java" />
</issue>
</lint>
To handle this in the source you should use something like
#SuppressLint("Deprecation")
Just use #SuppressWarnings("deprecation") above the function to suppress that specific warning for that function only.
Works like a charm!
#Blackd has the better answer. You should accept that!
Try to find a method from ViewCompat to replace the deprecated method.
In your case, use ViewCompat.setBackground(View, Drawable).
There are many classes named XXXCompat for cases like that, such as ContextCompat, ActivityCompat and so on.
After finally getting the Android Facebook SDK to properly import thanks to this, I found that eclipse does not recognize the override of onclick in FbDialog.java:
mCrossImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mListener.onCancel();
FbDialog.this.dismiss();
}
});
Nor does it recognize the overrides of onServiceConnected and onServiceDisconnected in the TokenRefreshServiceConnection implementation of ServiceConnection
#Override
public void onServiceConnected(ComponentName className, IBinder service) {
messageSender = new Messenger(service);
refreshToken();
}
#Override
public void onServiceDisconnected(ComponentName arg) {
serviceListener.onError(new Error("Service disconnected"));
// We returned an error so there's no point in
// keeping the binding open.
mAuthActivity.unbindService(TokenRefreshServiceConnection.this);
}
All three methods say, in the warning, that the method must override a superclass method. I have not modified the code at all yet. I checked that Eclipse recognizes the types as the same ones in the respective superclasses, and I have tried pressing control-shift-o to organize the imports, which was a fix suggested in this answer for a similar problem.
These overrides are part of the SDK, not any separate project. I set up the project to use Android SDK 2.2 as was shown on Facebook's instructions, and 4.0.3, which should be, theoretically, compatible with all previous versions. I have yet to get Facebook's own code to work. As a side note, is there a jar I can use instead? It would make this much easier.
Guessing your Project Properties -> Java Compiler Compiler compliance level is set to 1.5, not 1.6 (or higher).
Change this.
Why is javac failing on #Override annotation
The lazy, fast and easy fix is to remove the #Override annotations. The correct fix is to check that the project compiles to Java 1.5 or above, to use "fix project properties" from Eclipse, and possibly to check that the Facebook library project uses the same Android SDK for compiling against, as your project.