5

I have a fragment which extends android.app.Fragment. Inside onCreateView in some case I have java.lang.ClassCastException when I try cast Application to my implementation of Application.

public class SketchFragment extends android.app.Fragment{
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.layout, container, false);
        ButterKnife.bind(this,inflate);

        MyApplication application = (MyApplication)  getActivity().getApplicationContext();

        //Previously, I tried to
        //MyApplication application = (MyApplication) getActivity().getApplication()

        }
    }

Actually I have this error in <5% of all users(My Crashlytics log say that) only in Android 6. My Crashlytics log below :

Fatal Exception: java.lang.ClassCastException: android.app.Application cannot be cast to com.example.app.MyApplication

   at com.example.app.ui.activity.main.MyFragment.onCreateView(MyFragment.java:95)
   at android.app.Fragment.performCreateView(Fragment.java:2281)
   at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:983)
   at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1163)
   at android.app.BackStackRecord.run(BackStackRecord.java:793)
   at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1552)
   at android.app.FragmentManagerImpl$1.run(FragmentManager.java:487)
   at android.os.Handler.handleCallback(Handler.java:739)
   at android.os.Handler.dispatchMessage(Handler.java:95)
   at android.os.Looper.loop(Looper.java:158)
   at android.app.ActivityThread.main(ActivityThread.java:7229)
   at java.lang.reflect.Method.invoke(Method.java)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

My application part from Manifest file:

<application android:name=".MyApplication" android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="..." android:largeHeap="true" android:supportsRtl="true" android:theme="@style/AppTheme" > </application >

Thanks in advance!

  • 1
    have you looked into this? http://stackoverflow.com/a/6760019/588532 – Uriel Frankel Oct 31 '16 at 16:16
  • Were you able to figure out the cause - I am getting the same exception for some users in Android 6.0 in my service class. Service.getApplication() no longer casts to . – adarsh May 25 '17 at 06:52
  • 2
    Looks like an android issue but no resolution or acknowledgement yet - https://issuetracker.google.com/issues/37137009 – adarsh May 25 '17 at 07:01

0 Answers0