fdg g fdg g -4 years ago 108
Android Question

How to use Context in PagerAdapter on Android

I want set color for text and for this i should use

context.getResource.getColor
code in PagerAdapter, i write below codes :

public class HorizontalPagerAdapter extends PagerAdapter {

private Context mContext;
private LayoutInflater mLayoutInflater;

private boolean mIsTwoWay;

public HorizontalPagerAdapter(final Context context, final boolean isTwoWay) {
mContext = context;
mLayoutInflater = LayoutInflater.from(context);
mIsTwoWay = isTwoWay;
}

private final Utils.LibraryObject[] LIBRARIES = new Utils.LibraryObject[]{
new Utils.LibraryObject(
R.drawable.logo_darham,
"Text",
mContext.getColor(R.color.colorDarham)
),
new Utils.LibraryObject(
R.drawable.logo_manavi,
"text",
mContext.getResources().getColor(R.color.colormanavi)
),
new Utils.LibraryObject(
R.drawable.logo_monasebati,
"text",
mContext.getResources().getColor(R.color.colormonasebati)
),
new Utils.LibraryObject(
R.drawable.logo_ayad,
"text",
mContext.getResources().getColor(R.color.colorAyad)
)
};


But when running application, show me this error :

how can i fix it? please help me

Answer Source

Your variable LIBRARIES is initializing before constructor invocation, so mContext in this moment is null. Try this:

public class HorizontalPagerAdapter extends PagerAdapter {
    private Context mContext;
    private LayoutInflater mLayoutInflater;
    private boolean mIsTwoWay;

    private final Utils.LibraryObject[] LIBRARIES;

    public HorizontalPagerAdapter(final Context context, final boolean isTwoWay) {
        mContext = context;
        mLayoutInflater = LayoutInflater.from(context);
        mIsTwoWay = isTwoWay;
        LIBRARIES = new Utils.LibraryObject[]{
            new Utils.LibraryObject(
                R.drawable.logo_darham,
                "Text",
                ContextCompat.getColor(mContext, R.color.colorDarham)
            ),
        // ...
    };
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download