GetPackageName () in fragment

I used this method to resize markers in a Google Maps action:

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 getPackageName () symbol method". What could be the problem?

+5
source share
4 answers

Try this instead of getPackageName ()

getActivity().getPackageName()

+16
source
getPackageName()

defined in Activity. you cannot use it directly in yours Fragment. Try using:

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

, getActivity null . , . SO

, . .

    public static String PACKAGE_NAME;

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

    PACKAGE_NAME = getApplicationContext().getPackageName();
}

, :

MainActivity.PACKAGE_NAME
+3

Another way to get PackageManager in FragmentonCreateView ()

view.getContext().getPackageName()
0
source

Here to get the package name for Kotlin in snippet

context!!.packageName

0
source

Source: https://habr.com/ru/post/1669620/


All Articles