5

我有一个扩展android.app.Fragment的片段。在某些情况下,在 onCreateView 中,当我尝试将 Application 转换为我的 Application 实现时,我有java.lang.ClassCastException 。

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()

        }
    }

实际上,仅在Android 6中,我在 <5% 的所有用户中都有此错误(我的 Crashlytics 日志说)。我的 Crashlytics 日志如下:

致命异常:java.lang.ClassCastException:android.app.Application 无法转换为 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)

我的清单文件中的应用程序部分:

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

提前致谢!

4

0 回答 0