Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get rid of code deprecation?

Tags:

android

I am working on an Android project in Android Studio which supports from version 8 to 19. I want to use this method getBlockSizeLong(). Now if I use getBlockSize(), I see the deprecated cancellation line as you can see in the attached picture. If I use getBlockSizeLong(), I get error saying this method cannot be used for version 8! Even If I use a version check, the cancellation line will still persist. Thats ugly coding. How should I deal now?

enter image description here

like image 487
Prachi Avatar asked Sep 03 '25 07:09

Prachi


2 Answers

Well there're multiple ways how you can deal with this. In order to remove the "strikethrough" of deprecated methods you can use the Annotation @SuppressWarnings("deprecation").

Example

@SuppressWarnings("deprecation")
private void getBlockSize(StatFs stat){
   long blockSize = stat.getBlockSize();
}

In order to remove the red underlining for new API calls you can use the Annotation @TargetAPI(int)

Example

@TargetApi(18)
@SuppressLint("NewApi")
private void getBlockSizeNewApi(StatFs stat){
   long blockSize = stat.getBlockSizeLong();
}

To determine which method to call you have can use such a Helper-Method like the following:

public static boolean isVersionOrGreaterThan(int version){
    return Build.VERSION.SDK_INT >= version;
}
like image 66
reVerse Avatar answered Sep 04 '25 20:09

reVerse


You can use:

@SuppressWarnings("deprecation")
private void getBlockSize(StatFs stat){
   long blockSize = stat.getBlockSize();
}

Or

@TargetApi(18)
public void yourMethod()
{
    int currentapiVersion = android.os.Build.VERSION.SDK_INT;
    long blockSize;
    if (currentapiVersion >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2){
        // Do something for JELLY_BEAN_MR2 and above versions
        blockSize = stat.getBlockSizeLong();
    } else{
        // do something for phones running an SDK before JELLY_BEAN_MR2
        blockSize = stat.getBlockSize();
    }
}
like image 24
Sagar Pilkhwal Avatar answered Sep 04 '25 22:09

Sagar Pilkhwal