2

I try to add two methods for getDrawable(), because this method is deprecated. What's wrong?

    public class Misc {

    @TargetApi(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
    public static Drawable getDrawable(Context context, int resource) {
        return context.getResources().getDrawable(resource, null);
    }

    @TargetApi(Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
    public static Drawable getDrawable(Context context, int resource) {
        return context.getResources().getDrawable(resource);
    }

}



Duplicate method getDrawable(Context, int) in type Misc line 11 Java Problem
Duplicate method getDrawable(Context, int) in type Misc line 16 Java Problem
Azcaq
  • 43
  • 1
  • 8
  • possible duplicate of [Android getResources().getDrawable() deprecated API 22](http://stackoverflow.com/questions/29041027/android-getresources-getdrawable-deprecated-api-22) – vincent091 May 21 '15 at 08:40

4 Answers4

2

You should use the following code from the support library instead:

ContextCompat.getDrawable(context, R.drawable.***)

Using this method is equivalent to calling:

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) 
   {
     return resources.getDrawable(id, context.getTheme()); 
   } 
 else 
  {
    return resources.getDrawable(id); 
  }
Smeet
  • 3,558
  • 1
  • 28
  • 42
1

You cannot have two methods with the same signature (same method name, same parameters, etc.).

Rewrite it as:

public class Misc {

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public static Drawable getDrawable(Context context, int resource) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
          return context.getResources().getDrawable(resource, null);
        }

        return context.getResources().getDrawable(resource);
    }

}
CommonsWare
  • 910,778
  • 176
  • 2,215
  • 2,253
  • I get The method getDrawable(int) from the type Resources is deprecated by the second return – Azcaq Mar 29 '15 at 21:44
0

The error is you used overload incorrectly! Specifically, it is not allow to have 2+ methods have the same name with same input params.

T D Nguyen
  • 5,353
  • 4
  • 38
  • 57
0

Because you have defined it twice.

public static Drawable getDrawable(Context context, int resource) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        return context.getResources().getDrawable(resource);
    } else {
        return context.getResources().getDrawable(resource, null);
    }
}

Should solve your problem.

Lachlan Goodhew-Cook
  • 1,071
  • 17
  • 29
  • context.getResources().getDrawable(resource, null); is showing that Call requires API level 21. I have to use minSDK 19. I cant set it to 21 in my app. – ravi Jun 20 '15 at 09:34