Android : error: incompatible types: cannot be converted to Context

สำหรับ error cannot be converted to Context สาเหตุหนึ่งที่พบบ่อยคือ มีการเรียกใช้ context ใน Fragment เช่น

 

public class Activity_About extends Fragment {

    private NativeExpressAdView mAdView;

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

        mNativeAdView = new NativeExpressAdView(this);

        ...

    }

}

หลังจากคอมไพล์แล้วเกิด error cannot be converted to Context ตรง “new NativeExpressAdView(this)”

Error:(59, 76) error: incompatible types: Activity_About cannot be converted to Context

ทางแก้ไขให้เราเรียกใช้ฟังก์ชัน getActivity().getApplicationContext() แทน “this” ดังตัวอย่าง

mNativeAdView = new NativeExpressAdView(getActivity().getApplicationContext());

คราวนี้คอมไพล์ใหม่ก็ผ่านละครับ

You may also like...