Better way of upping my Minimum API Level? - android

So I just had to up my min API level to 11 for the Preference (addpreferenceresource was depreciated) - turns out 9-10 takes out like 50% of the market. So my question is, is it better to just suppress the warning to cater to the Gingerbread market or is there a different way to make my preference reference without using Preference Fragments?

I would implement both types (the one that works in 11+ and the one that works in 10-), then use conditional checks for them. This is written in quite a bit of detail in this answer.
Basically, you end up setting up OtherPreferencesActivity with PreferenceFragment, and then PreferencesActivity with the deprecated PreferenceActivity. (Your APK will not break by including this deprecated code, as long as you use a version check so that if/when it's removed in the future, it doesn't try to find it.)
if (Build.VERSION.SDK_INT < 11) {
startActivity(new Intent(this, PreferencesActivity.class);
} else {
startActivity(new Intent(this, OtherPreferencesActivity.class);
}
Keep in mind, you will want to have them use each others' methods as much as possible so that you don't end up duplicating code.
Last tip: #TargetApi(11) and #SuppressWarnings("deprecation") will come in handy here. Just be careful that you're not ignoring other deprecations by doing so.

"depreciated" doesn't mean you can't use it and will break your system if you run the code. It means that it is officially not recommended to use and this method maybe removed from the api. In the future but we don't know when. So I would say it is save to use in this case for now.

Related

putSerializable for Bundle OK but getSerializable depreciated (passing GregorianCalendar date)

So I'm using the following code to put values into a Bundle
val arguments = Bundle()
arguments.putSerializable(DATE_PICKER_DATE, viewModel.getFilterDate())
dialogFragment.arguments = arguments
getFilterDate() returns a GregorianCalendar.time.
This seems fine but when I unpack the bundle with
val givenDate = arguments.getSerializable(DATE_PICKER_DATE) as Date
It says getSerializable is depreciated.
Can live with this for now but would rather not use depreciates stuff.
Did a load of googling and the simplest way to do this seem to be to use a long to pass the date in milliseconds, which will work for this but does mean some extra date processing but wondered if there is a better alternative to pass complex objects, such as GregorianCalendar dates? Be good to have a nice generic solution. Did look at Parcelables and found https://developer.android.com/guide/components/activities/parcelables-and-bundles but it was not much help. Lacked example code that was useful to me. My search has led me here.
PS
I think the way to put the Date into bundle is
arguments.putLong(DATE_PICKER_DATE, viewModel.getFilterDate().time)
And to get it back to a date is
val givenDate = Date(arguments.getLong(DATE_PICKER_DATE))
Which I guess is a good solution this time but wondering if there is a more generic solution like Serialise.
Whenever you get a deprecated warning, look at the warning to see if there's any information about why it's deprecated and what you're supposed to use instead - or look at the documentation for the method (usually the same thing):
This method was deprecated in API level 33.
Use the type-safer getSerializable(java.lang.String, java.lang.Class) starting from Android Build.VERSION_CODES#TIRAMISU.
So basically, it's telling you to use a new getSerializable method instead, one where you explicitly provide the class of the object being deserialised. So if you're using the Date provided by GregorianCalendar#getTime, you'd do:
val givenDate = arguments.getSerializable(DATE_PICKER_DATE, Date::class.java)
Also note that this is an API 33 (Tiramisu) thing - that means it's not available on lower APIs (so you'd need to use the deprecated method for those, with an API check to work out which to use). It also means it's only just been deprecated, so it will stick around for a while yet - you have the option of just using it! It's your call, but it's unlikely to disappear for a few years.
The other option for this kind of thing is to use a Compat library that calls the relevant method depending on API, handling all the boilerplate for you. I can't see anything for this specific method (although I only checked BundleCompat to see if it was added) but maybe later - it's always worth a look for API-dependent methods though.

Implement multiple methods for different API levels and not do if else to decide which one to call

I wonder if it's possible to implement multiple methods to support different API levels and call the right one without if(android.os.Build.VERSION.SDK_INT >= ...) else if...?
I want to use android platform's newer features like streams etc. and still support backwards.
Example:
wrote a method
public void myMethod24() {
// some logic requires api level N(24) and above
}
but my app supports lower apis, so i need another method that's compatible with them.
here is a method compatible for older versions:
public void myMethod21() {
// the same logic, requires api level LOLLIPOP(21) and above
}
How to use the correct method for current running version without doing this ugly if else:
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
myMethod24();
} else if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
myMethod21();
}
Maybe annotate my methods with #RequiresApi(), #TargetApi or something else..?
i saw this question but the answer there is with if else.
How to use the correct method for current running version without doing this ugly if else
You can't. Somewhere, something needs to do the version check and route to the appropriate logic.
Maybe annotate my methods with #RequiresApi(), #TargetApi or something else..?
Those are there to help advise the compiler that you know what you are doing. They do not code-generate the version comparisons.
Depending on what you are doing, existing ...Compat classes might handle the version checks for you (e.g., NotificationCompat.Builder). If you were using Kotlin, we could come up with some funky code that hides the if checks. And there might be a third-party library that offers some annotation-based code generator that code-generates the if checks.

Canvas clipOutRect compatibility in AndroidX

I recently came across the deprecation of clipRect(Rect,Region.Op), which I would like to use with DIFFERENCE. This was replaced with clipOutRect(Rect) and thus I implemented:
#Suppress("DEPRECATION")
fun clipOutRect(canvas: Canvas, rect: Rect) =
if (SDK_INT >= O) canvas.clipOutRect(rect)
else canvas.clipRect(rect, DIFFERENCE)
Now this looks like it could be a compatibility method in AndroidX, but for some reason I was not able to figure out, where I could find it exactly.
Is there a class already providing a compatibility method for clipOutRect(Rect)?
Short answer is - no. The only thing related to Canvas in AndroidX is this file: https://github.com/aosp-mirror/platform_frameworks_support/blob/androidx-master-dev/core/core-ktx/src/main/java/androidx/core/graphics/Canvas.kt
Long answer.
First of all, Canvas is passed to view by native code, so it will be awkward to have something like onDrawCompat(canvas: CanvasCompat) in ViewCompat class. And I think there is no reason to do that at all.
Also, it's really not that type of deprecation you should worry about.
For example WifiManager.startScan() is noted with
This method was deprecated in API level 28. The ability for apps to
trigger scan requests will be removed in a future release.
That says Change this code now, or it will be broken year later
That not the case with clipRect, it will be kept for backward compatibility with apps that won't be ever updated for years or even tenth of years. Deprecation warning for this is just like Hey, we have new method with better functionality/name, if you target minimum is API 26 you can use that

What does TabActivity & getDrawable() is deprecated mean? And can it cause your application to close?

Here is the image that show the objects that are depreciated...?
What does this mean?
Deprecated means that you should not use it anymore but a new implementation of it, because it will be removed from framework / language whatever in future releases. In most cases there is a description at this method or documentation what you have to use instead.

Was PreferenceFragment intentionally excluded from the compatibility package?

I'm looking to write preferences that can be applied to both 3.0 and pre-3.0 devices. Discovering that PreferenceActivity contains deprecated methods (although these are used in the accompanying sample code), I looked at PreferenceFragement and the compatibility package to solve my woes.
It appears, though, that PreferenceFragment isn't in the compatibility package. Can anyone tell me whether this was intentional? If so, can I easily target a range of devices (i.e. < 3.0 and >=3.0) or will I have to jump through hoops? If it wasn't intentionally excluded, can we expect a new release of the compatibility package? Or is there another workaround that is safe to use?
Discovering that PreferenceActivity contains deprecated methods (although these are used in the accompanying sample code)
The deprecated methods are deprecated as of Android 3.0. They are perfectly fine on all versions of Android, but the direction is to use PreferenceFragment on Android 3.0 and higher.
Can anyone tell me whether this was intentional?
My guess is it's a question of engineering time, but that's just a guess.
If so, can I easily target a range of devices (i.e. < 3.0 and >=3.0) or will I have to jump through hoops?
I consider it to be done "easily". Have two separate PreferenceActivity implementations, one using preference headers and PreferenceFragments, the other using the original approach. Choose the right one at the point you need to (e.g., when the user clicks on the options menu item). Here is a sample project demonstrating this. Or, have a single PreferenceActivity that handles both cases, as in this sample project.
If it wasn't intentionally excluded, can we expect a new release of the compatibility package?
You will find out when the rest of us find out, which is to say, if and when it ships.
Or is there another workaround that is safe to use?
See above.
The subtle implication of the answer from #CommonsWare is that - your app must choose between the compatibility API or the built-in fragment API (since SDK 11 or so). In fact that's what the "easily" recommendation has done. In other words, if you want to use PreferenceFragment your app needs to use the built-in fragment API and deal with the deprecated methods on PreferenceActivity. Conversely, if it's important that your app use the compat. API you will be faced with not having a PreferenceFragment class at all. Thus, targeting devices is not a problem, but the hoop-jumping happens when you have to choose one or the other API and thus submit your design to unforeseen workarounds. I need the compat. API so I'm going to create my own PreferenceFragment class and see how that works. In the worst case scenario I'll just create a normal (fragment) layout and bind the view components to the sharedprefs manually...ugh.
EDIT:
After trying and looking at the code at http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.0.1_r1/android/preference/PreferenceFragment.java?av=h -- creating my own PreferenceFragment isn't going to happen. It appears the liberal use of package-private in PreferenceManager instead of 'protected' is the main blocker. It really doesn't look like there's any security or really good motivation to have done that and it isn't great for unit-testing but oh well...less typing I guess...
EDIT v2:
Actually it did happen and it worked. It was definitely a headache to make the code work with the Compatibility API JAR. I had to copy about 70% the com.android.preference package from the SDK to my app and then wrestle with typically mediocre-quality Java code in Android. I used v14 of the SDK. It would have been much easier for a Goog engineer to do what I did, contrary to what I've heard some lead Android engineers say about this topic.
BTW - did I say "targeting devices is not a problem"? It totally is...if you use com.android.preference you are not going to be able to swap out with the Compatibility API without major refactoring. Fun log!
Building upon CommonsWare's answer as well as Tenacious' observations, I have come up with a single descendant class solution capable of targeting all current Android API versions with minimal fuss and no code or resource duplication. Please see my answer to the related question over here:
PreferenceActivity Android 4.0 and earlier
or on my blog:
http://www.blackmoonit.com/2012/07/all_api_prefsactivity/
Tested on two tablets running 4.0.3 and 4.0.4 as well as a phone running 4.0.4 and 2.3.3 and also an emulator running 1.6.
See PreferenceFragment-Compat from Machinarius. It was easy to drop in with gradle and I forget that it's even there.
compile 'com.github.machinarius:preferencefragment:0.1.1'
Important Update: The latest revision of the v7 support library now has a native PreferenceFragmentCompat.
On August 2015 Google released the new Preference Support Library v7.
Now you can use the PreferenceFragmentCompat with any Activity or AppCompatActivity
public static class PrefsFragment extends PreferenceFragmentCompat {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
}
}
You have to set preferenceTheme in your theme:
<style name="AppTheme" parent="#style/Theme.AppCompat.Light">
...
<item name="preferenceTheme">#style/PreferenceThemeOverlay</item>
</style>
In this way you can customize the preferenceTheme to style the layouts used for each preference type without affecting other parts of your Activity.
Tenacious's answer is correct, but here are some more details.
The reason you can't "create a normal layout and bind the view components to the sharedprefs manually" is that there are some surprising omissions in the android.preferences API. PreferenceActivity and PreferenceFragment both have access to critical non-public PreferenceManager methods, without which you can't implement a preference UI of your own.
In particular, to construct a Preference hierarchy from an XML file you need to use a PreferenceManager, but all of PreferenceManager's constructors are either package-private or hidden. The method of attaching the Preference onClick listeners to your activity is also package-private.
And you can't work around this by sneakily putting your implementation in the android.preferences package, because non-public methods in Android APIs are actually omitted from the SDK. With a bit of creativity involving reflection and dynamic proxies, you can still get at them. The only alternative, as Tenacious says, is to fork the entire android.preference package, including at least 15 classes, 5 layouts, and a similar number of style.xml and attrs.xml elements.
So to answer the original question, the reason Google didn't include PreferenceFragment in the compatibility package is that they would have had exactly the same difficulty as Tenacious and myself. Even Google can't go back in time and make those methods public in the old platforms (though I hope they do that in future releases).
My app target is API +14 but due to using support library for some fancy navigation, I couldn't use the android.app.Fragment and had to use android.support.v4.app.Fragment, but I also needed to have PreferenceFragment in place without large changes to code behind.
So my easy fix for having both worlds of support library and PreferenceFragment:
private android.support.v4.app.Fragment fragment;
private android.app.Fragment nativeFragment = null;
private void selectItem(int position) {
fragment = null;
boolean useNativeFragment = false;
switch (position) {
case 0:
fragment = new SampleSupprtFragment1();
break;
case 1:
fragment = new SampleSupprtFragment2();
break;
case 2:
nativeFragment = new SettingsFragment();
useNativeFragment = true;
break;
}
if (useNativeFragment) {
android.app.FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, nativeFragment).commit();
} else {
if (nativeFragment != null) {
getFragmentManager().beginTransaction().remove(nativeFragment)
.commit();
nativeFragment = null;
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment).commit();
}
}
I needed integrate Preferences into application's design and keep support for 2.3 android. So I still needed PreferencesFragment.
After some search I found android-support-v4-preferencefragment lib. This lib save a lot of time for copying and refactoring original PreferencesFragment as Tenacious said. Works fine and users enjoy preferences.

Categories

Resources