App crashes when getContext() is used to generate Toast inside fragment in API 23 but works on API 27 and more

huangapple go评论75阅读模式
英文:

App crashes when getContext() is used to generate Toast inside fragment in API 23 but works on API 27 and more

问题

ContestFragmentonCreateView方法中,我尝试使用从**getContext()获取的上下文来生成一个Toast。这在Android Oreo及以上版本上运行良好,但在Android Marshmallow上却导致应用程序崩溃。然而,将getContext()替换为getContext().getApplicationContext()**可以解决Marshmallow上的问题。有人能否解释为什么会发生这种情况?

注意:**getContext()**并没有返回null。我已经验证过了。

错误日志:

09-28 20:42:36.325 31550-31550/com.hitesh.codeforces E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.hitesh.codeforces, PID: 31550
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.hitesh.codeforces/com.hitesh.codeforces.MainActivity}: android.view.InflateException: Binary XML file line #27: Binary XML file line #27: Error inflating class TextView
    ...

XML(fragment_contest.xml):

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".ContestFragment">

    <androidx.appcompat.widget.SwitchCompat
        android:id="@+id/include"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimary"
        app:layout_constraintTop_toTopOf="parent"
        android:gravity="right"
        android:text="Show Finished"
        android:textStyle="italic"
        android:textColor="@color/white"
        android:textSize="18sp"/>

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycler"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="2dp"
        app:layout_constraintTop_toBottomOf="@id/include" />

</androidx.constraintlayout.widget.ConstraintLayout>
英文:

When I try to generate a toast in onCreateView method of ContestFragment using context from getContext(), the app crashes in Android Marshmallow while it works on Android Oreo and above. However, replacing getContext() with getContext().getApplicationContext() fixes the issue for Marshmallow. Can anyone please describe why is this happening?

Note: getContext() is not returning null. I have checked that.

public class ContestFragment extends Fragment {
      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
          View view = inflater.inflate(R.layout.fragment_contest, container, false);
          Toast.makeText(getContext(), &quot;No Internet&quot;, Toast.LENGTH_LONG).show(); //crashes at this line

         //Toast.makeText(getContext().getApplicationContext(), &quot;No Internet&quot;, Toast.LENGTH_LONG).show(); 
         //works

          return view;
      }
}

Error Log:

09-28 20:42:36.325 31550-31550/com.hitesh.codeforces E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.hitesh.codeforces, PID: 31550
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.hitesh.codeforces/com.hitesh.codeforces.MainActivity}: android.view.InflateException: Binary XML file line #27: Binary XML file line #27: Error inflating class TextView
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3319)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
        at android.app.ActivityThread.access$1100(ActivityThread.java:229)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:7331)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
     Caused by: android.view.InflateException: Binary XML file line #27: Binary XML file line #27: Error inflating class TextView
        at android.view.LayoutInflater.inflate(LayoutInflater.java:551)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:429)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:380)
        at android.widget.Toast.makeText(Toast.java:432)
        at com.hitesh.codeforces.ContestFragment.onCreateView(ContestFragment.java:66)
        at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2600)
        at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:881)
        at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1238)
        at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1303)
        at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:439)
        at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManagerImpl.java:2079)
        at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1869)
        at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1824)
        at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1727)
        at androidx.fragment.app.FragmentManagerImpl.dispatchStateChange(FragmentManagerImpl.java:2663)
        at androidx.fragment.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManagerImpl.java:2613)
        at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:246)
        at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:542)
        at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:210)
        at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1266)
        at android.app.Activity.performStart(Activity.java:6943)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3276)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)&#160;
        at android.app.ActivityThread.access$1100(ActivityThread.java:229)&#160;
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)&#160;
        at android.os.Handler.dispatchMessage(Handler.java:102)&#160;
        at android.os.Looper.loop(Looper.java:148)&#160;
        at android.app.ActivityThread.main(ActivityThread.java:7331)&#160;
        at java.lang.reflect.Method.invoke(Native Method)&#160;
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)&#160;
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)&#160;
     Caused by: android.view.InflateException: Binary XML file line #27: Error inflating class TextView
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:794)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:716)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:847)
        at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:810)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:527)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:429)&#160;
        at android.view.LayoutInflater.inflate(LayoutInflater.java:380)&#160;
        at android.widget.Toast.makeText(Toast.java:432)&#160;
        at com.hitesh.codeforces.ContestFragment.onCreateView(ContestFragment.java:66)&#160;
        at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2600)&#160;
        at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:881)&#160;
        at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1238)&#160;
        at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1303)&#160;
        at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:439)&#160;
        at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManagerImpl.java:2079)&#160;
        at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1869)&#160;
        at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1824)&#160;
        at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1727)&#160;
        at androidx.fragment.app.FragmentManagerImpl.dispatchStateChange(FragmentManagerImpl.java:2663)&#160;
        at androidx.fragment.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManagerImpl.java:2613)&#160;
        at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:246)&#160;
        at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:542)&#160;
        at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:210)&#160;
        at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1266)&#160;
        at android.app.Activity.performStart(Activity.java:6943)&#160;
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3276)&#160;
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)&#160;
        at android.app.ActivityThread.access$1100(ActivityThread.java:229)&#160;
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)&#160;
        at android.os.Handler.dispatchMessage(Handler.java:102)&#160;
        at android.os.Looper.loop(Looper.java:148)&#160;
        at android.app.ActivityThread.main(ActivityThread.java:7331)&#160;
        at java.lang.reflect.Method.invoke(Native Method)&#160;
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)&#160;
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)&#160;
     Caused by: java.lang.ArrayIndexOutOfBoundsException: length=16; index=528
        at android.content.res.StringBlock.get(StringBlock.java:66)
        at android.content.res.XmlBlock$Parser.getPooledString(XmlBlock.java:459)
        at android.content.res.TypedArray.loadStringValueAt(TypedArray.java:1167)
        at android.content.res.TypedArray.getString(TypedArray.java:197)
        at androidx.appcompat.widget.TintTypedArray.getString(TintTypedArray.java:150)
        at androidx.appcompat.widget.AppCompatTextHelper.updateTypefaceAndStyle(AppCompatTextHelper.java:397)
        at androidx.appcompat.widget.AppCompatTextHelper.loadFromAttributes(AppCompatTextHelper.java:209)
    	at androidx.appcompat.widget.A

XML (fragment_contest.xml) :

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;androidx.constraintlayout.widget.ConstraintLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    xmlns:tools=&quot;http://schemas.android.com/tools&quot;
    android:layout_width=&quot;match_parent&quot;
    android:layout_height=&quot;match_parent&quot;
    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;
    tools:context=&quot;.ContestFragment&quot;&gt;

    &lt;androidx.appcompat.widget.SwitchCompat
        android:id=&quot;@+id/include&quot;
        android:layout_width=&quot;match_parent&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:background=&quot;@color/colorPrimary&quot;
        app:layout_constraintTop_toTopOf=&quot;parent&quot;
        android:gravity=&quot;right&quot;
        android:text=&quot;Show Finished&quot;
        android:textStyle=&quot;italic&quot;
        android:textColor=&quot;@color/white&quot;
        android:textSize=&quot;18sp&quot;/&gt;

    &lt;androidx.recyclerview.widget.RecyclerView
        android:id=&quot;@+id/recycler&quot;
        android:layout_width=&quot;match_parent&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:layout_marginTop=&quot;2dp&quot;
        app:layout_constraintTop_toBottomOf=&quot;@id/include&quot; /&gt;

&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;

答案1

得分: 1

你的问题出现在字体样式文件中

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- 在此处自定义主题。 -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimary</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="title">Code Forces</item>
    <item name="android:letterSpacing">0.08</item>
    <item name="android:fontFamily">sans-serif</item>
</style>

你不能使用 <item name="android:fontFamily">sans-serif</item>

你可以使用

1- 更改为 <item name="android:fontFamily">@string/font</item>

2- 在字符串文件中添加行 <string name="font" translatable="false">sans-serif-light</string>

结果:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- 在此处自定义主题。 -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimary</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="title">Code Forces</item>
    <item name="android:letterSpacing">0.08</item>
    <item name="android:fontFamily">@string/font</item>
</style>
英文:

your problem is in font style file

&lt;style name=&quot;AppTheme&quot; parent=&quot;Theme.AppCompat.Light.DarkActionBar&quot;&gt;
    &lt;!-- Customize your theme here. --&gt;
    &lt;item name=&quot;colorPrimary&quot;&gt;@color/colorPrimary&lt;/item&gt;
    &lt;item name=&quot;colorPrimaryDark&quot;&gt;@color/colorPrimary&lt;/item&gt;
    &lt;item name=&quot;colorAccent&quot;&gt;@color/colorAccent&lt;/item&gt;
    &lt;item name=&quot;title&quot;&gt;Code Forces&lt;/item&gt;
    &lt;item name=&quot;android:letterSpacing&quot;&gt;0.08&lt;/item&gt;
    &lt;item name=&quot;android:fontFamily&quot;&gt;sans-serif&lt;/item&gt;
&lt;/style&gt;

you can not use of &lt;item name=&quot;android:fontFamily&quot;&gt;sans-serif&lt;/item&gt;

you can use

1- change to &lt;item name=&quot;android:fontFamily&quot;&gt;@string/font&lt;/item&gt;

2- in string file add line &lt;string name=&quot;font&quot; translatable=&quot;false&quot;&gt;sans-serif-light&lt;/string&gt;

result:

    &lt;style name=&quot;AppTheme&quot; parent=&quot;Theme.AppCompat.Light.DarkActionBar&quot;&gt;
    &lt;!-- Customize your theme here. --&gt;
    &lt;item name=&quot;colorPrimary&quot;&gt;@color/colorPrimary&lt;/item&gt;
    &lt;item name=&quot;colorPrimaryDark&quot;&gt;@color/colorPrimary&lt;/item&gt;
    &lt;item name=&quot;colorAccent&quot;&gt;@color/colorAccent&lt;/item&gt;
    &lt;item name=&quot;title&quot;&gt;Code Forces&lt;/item&gt;
    &lt;item name=&quot;android:letterSpacing&quot;&gt;0.08&lt;/item&gt;
    &lt;item name=&quot;android:fontFamily&quot;&gt;@string/font&lt;/item&gt;
&lt;/style&gt;

huangapple
  • 本文由 发表于 2020年9月28日 21:47:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/64103488.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定