How do I get rid of obsolete code?

I am working on an Android project in Android Studio that supports 8 to 19. I want to use this getBlockSizeLong () method. Now if I use getBlockSize () I can see the deprecated cancel line as you can see in the attached picture. If I use getBlockSizeLong () I get an error saying this method cannot be used for version 8! Even if I use version check, the undo line still persists. This is ugly coding. How should I do now?

enter image description here

+3


source to share


2 answers


Well, there are several ways on how you can handle this. 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();
}

      

To remove the red underline for new API calls you can use Annotation @TargetAPI(int)



Example

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

      

To determine which method you can call, you can use a Method Helper as shown below:

public static boolean isVersionOrGreaterThan(int version){
    return Build.VERSION.SDK_INT >= version;
}

      

+5


source


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();
    }
}

      

+2


source







All Articles