-1

I am absolutly new in Android and I am finding some dificulties to do the following thing related to the Context.

So I have an utility class that contain an utility method that create and return a Bitmap image, this is the code of my class:

public class ImgUtility {

    /**
     * Method that create the images related to the difficulty of a recepy
     * @param context
     * @param difficulty that represent the number of chef_hat_ok into the final image
     * @return a Bitmap representing the difficult of a recepy
     */
    public static Bitmap createRankingImg(Context context, int difficulty) {

        // Create a Bitmap image starting from the star.png into the "/res/drawable/" directory:
        Bitmap myBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.chef_hat_ok);


        // Create a new image bitmap having width to hold 5 star.png image:
        Bitmap tempBitmap = Bitmap.createBitmap(myBitmap.getWidth() * 5, myBitmap.getHeight(), Bitmap.Config.RGB_565);

        /* Attach a brand new canvas to this new Bitmap.
           The Canvas class holds the "draw" calls. To draw something, you need 4 basic components:
           1) a Bitmap to hold the pixels.
           2) a Canvas to host the draw calls (writing into the bitmap).
           3) a drawing primitive (e.g. Rect, Path, text, Bitmap).
           4) a paint (to describe the colors and styles for the drawing).
         */
        Canvas tempCanvas = new Canvas(tempBitmap);

        // Draw the image bitmap into the cavas:
        tempCanvas.drawBitmap(myBitmap, 0, 0, null);
        tempCanvas.drawBitmap(myBitmap, myBitmap.getWidth(), 0, null);
        tempCanvas.drawBitmap(myBitmap, myBitmap.getWidth() * 2, 0, null);
        tempCanvas.drawBitmap(myBitmap, myBitmap.getWidth() * 3, 0, null);
        tempCanvas.drawBitmap(myBitmap, myBitmap.getWidth() * 4, 0, null);

        return tempBitmap;

    }

}

As you can see this class contains the createRankingImg that take the Context object as parameter and use it to create an image. This object is used to retrieve an image from the resources (into the BitmapFactory.decodeResource() method). What exactly represent the Context object into an Android application?

I know that to obtain the context into an activity class I can use the getResources() method.

My problem is that I have to obtain the context into a class that exetends Fragment.

I have something like this:

public class ScreenSlidePageFragment extends Fragment {

    .......................................................................
    .......................................................................
    .......................................................................

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

        .....................................................................
        .....................................................................
        .....................................................................

        switch (mPageNumber + 1) {

            case 1:
                imgSlideView.setImageResource(R.drawable.carbonara);
                ((TextView) rootView.findViewById(android.R.id.text1)).setText(getString(R.string.carbonara));

                ImageView difficultyContainerImageView1 = (ImageView) rootView.findViewById(R.id.difficultyContainer);

                difficultyContainerImageView1.setImageDrawable(new BitmapDrawable(getResources(),     ImgUtility.createRankingImg(getApplicationContext(), 3)));

                break;

        .....................................................................
        .....................................................................
        .....................................................................

        }

        return rootView;
}

My problem is that when in the previous fragment class I call the method

ImgUtility.createRankingImg(getResources(), 3)

passing to it the getResources() output (that I thinked give me the Context, the IDE give me the following error message:

Wrong 1st argument type. Found: 'android.content.res.Resources', required: 'android.content.Context'

So it seems to me that into a class that extends a Fragment and not an Activity the getResources() method return a Resources object instead a Context object (as done into an Activity class). Is it true? Why?

How can I obtain the Context inside a class that extends Fragment? And what exactly represent the Context in an Android app?

AndreaNobili
  • 40,955
  • 107
  • 324
  • 596
  • 2
    Use getContext() instead of getResources(). Pay attention, getContext() may be null. – Alexey Rogovoy Aug 15 '16 at 10:48
  • If you look at the Android JavaDoc for the Context object, it explains exactly what it is. You'll also note that Activity classes extend Context – OneCricketeer Aug 15 '16 at 10:53
  • When using `getActivity` in fragment code, make sure you are correctly handling all attach/detach events, so you use the correct activity (and don't store it somewhere (bad practice), or crash on `null` when fragment is detached. For resource access quite often the application context is enough, which is a bit more reasonable to store locally inside fragment, allowing you to access them even when detached from activity (but still the best practice is to not rely on any stored context, but operate on the current one, handling detached mode correctly). – Ped7g Aug 15 '16 at 11:00

5 Answers5

0

If you are in a fragment you can for instance call getActivity(). Please make sure that you call it after the onActivityCreated callback otherwise the function will return null.

Lino
  • 5,084
  • 3
  • 21
  • 39
0

There are two ways for access to resources from Fragment class. For your utility method you need to call the Fragment#getContext() method as a parameter.

Be aware that you can access directly to resources class by this method Fragment#getResources()

MrOnyszko
  • 847
  • 9
  • 13
0

Create a BaseContext class, initialise it in your Application class

public final class BaseContext {

    private static Context CONTEXT;

    public static void initialise(Context context) {
        CONTEXT = context;
    }

    public static Context getContext() {
        synchronized (BaseContext.class) {
            if (BaseContext.CONTEXT == null)
                throw new NullPointerException("Base Context not initialised. Call BaseContext.initialise()");
            else
                return BaseContext.CONTEXT.getApplicationContext();
        }
    }
}

Now in non Activity and non Fragment class you can get context by simply calling BaseContext.getContext();

Atif Farrukh
  • 2,219
  • 2
  • 25
  • 47
0

Use onCreateView only to create root view and get instance of subviews:

private ImageView difficultyContainerImageView1;
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_layout, container, false);
        difficultyContainerImageView1 = (ImageView) rootView.findViewById(R.id.difficultyContainer);
        return rootView;
}

Use onViewCreated to set content. You can freely call getContext or getActivity methods in onViewCreated:

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        difficultyContainerImageView1.setImageDrawable(
                      new BitmapDrawable(getResources(), 
                               ImgUtility.createRankingImg(getContext(), 3)));

}
Volodymyr Kulyk
  • 6,455
  • 3
  • 36
  • 63
-1

what is context This is an abstract class whose implementation is provided by the Android system. It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc (read at https://developer.android.com/reference/android/content/Context.html

)

for getting context ,you can use getactivity method,it will return activity and from there you can get its context,something like

Context context = getActivity().getApplicationContext()
nullByte
  • 53
  • 1
  • 9