18

I was using this method to resize markers in a Google Maps activity:

public Bitmap resizeMapIcons(String iconName,int width, int height){
    Bitmap imageBitmap = BitmapFactory.decodeResource(getResources(),getResources().getIdentifier(iconName, "drawable", getPackageName()));
    Bitmap resizedBitmap = Bitmap.createScaledBitmap(imageBitmap, width, height, false);
    return resizedBitmap;
}

Now I wanted to use it in a fragment with MapView, but I get the error "error: cannot find symbol method getPackageName()". What could be the problem?

kefir500
  • 4,184
  • 6
  • 42
  • 48
Tamas Koos
  • 1,053
  • 3
  • 15
  • 35

7 Answers7

58

Try this instead of getPackageName()

getActivity().getPackageName()
Zoe
  • 27,060
  • 21
  • 118
  • 148
steve
  • 876
  • 8
  • 8
5

Here's to get package name for Kotlin in a Fragment

context!!.packageName

Ade
  • 363
  • 3
  • 13
5

BuildConfig.APPLICATION_ID


The easiest way is probably:

String PkgName = BuildConfig.APPLICATION_ID

Notes:

  • You can access BuildConfig from anywhere on your code.
  • Doesn't work on libraries
Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
3
getPackageName()

is defined in Activity . you can not directly use it in your Fragment. Try use:

    if(getActivity()!=null){
         Bitmap imageBitmap = BitmapFactory.decodeResource(getResources(),getResources().getIdentifier(iconName, "drawable", getActivity().getPackageName()));
         //rest of your code
   }

It is best practice to check if getActivity is null or not. So your app will not crash.Read this SO question

You can also create a static variable in your main activity, instantiated to be the package name. Then just use that variable in fragment.

    public static String PACKAGE_NAME;

    @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    PACKAGE_NAME = getApplicationContext().getPackageName();
}

Now you can access it using:

MainActivity.PACKAGE_NAME
Community
  • 1
  • 1
rafsanahmad007
  • 23,683
  • 6
  • 47
  • 62
  • And how can I put the if statement in the method? I don't want to use static variables, because this way I can use this method for different bitmaps. – Tamas Koos Feb 13 '17 at 19:42
  • My problem is that if I close the end statement before the return I can't use the resizedBitmap variable, but if I close it after the return, than the method misses the return statement. – Tamas Koos Feb 13 '17 at 20:00
1

Another way to get PackageManager in Fragment onCreateView()

view.getContext().getPackageName()
Anonymous
  • 2,184
  • 15
  • 23
0

Kotlin Extension Solution

Add this somewhere in your code:

val Fragment.packageName get() = activity?.packageName

And then simply use packageName directly in your Fragment code

val name = packageName
Gibolt
  • 42,564
  • 15
  • 187
  • 127
0

Try this instead:

requireActivity().getPackageName()
cigien
  • 57,834
  • 11
  • 73
  • 112