从 RecyclerView 调用 dialogfragment 时出现 ClassCastException

ClassCastException on calling a dialogfragment from RecyclerView

我有一个 RecyclerView,我试图从中调用一个 dialogfragment,但我收到一个 class 转换异常。我在堆栈上尝试了很多解决方案,但没有帮助。请帮助我。

    java.lang.ClassCastException: android.app.Application cannot be cast to android.app.Activity
12-04 14:08:52.495 6146-    6146/com.opentok.example.efflorescence.myaudiotranscription W/System.err:     at com.opentok.example.efflorescence.myaudiotranscription.AllCallsRecyclerAdapter.showTranscriptionDialog(AllCallsRecyclerAdapter.java:249)
12-04 14:08:52.495 6146-6146/com.opentok.example.efflorescence.myaudiotranscription W/System.err:     at com.opentok.example.efflorescence.myaudiotranscription.AllCallsRecyclerAdapter.run(AllCallsRecyclerAdapter.java:210)
12-04 14:08:52.495 6146-6146/com.opentok.example.efflorescence.myaudiotranscription W/System.err:     at android.os.Handler.handleCallback(Handler.java:815)
12-04 14:08:52.495 6146-6146/com.opentok.example.efflorescence.myaudiotranscription W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:104)
12-04 14:08:52.495 6146-6146/com.opentok.example.efflorescence.myaudiotranscription W/System.err:     at android.os.Looper.loop(Looper.java:207)
12-04 14:08:52.495 6146-6146/com.opentok.example.efflorescence.myaudiotranscription W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5765)
12-04 14:08:52.495 6146-6146/com.opentok.example.efflorescence.myaudiotranscription W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
12-04 14:08:52.495 6146-6146/com.opentok.example.efflorescence.myaudiotranscription W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
12-04 14:08:52.496 6146-6146/com.opentok.example.efflorescence.myaudiotranscription W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)

我的适配器代码 onClick

public void showTranscriptionDialog() {
  try {
    FragmentManager fr = ((Activity) context).getFragmentManager();
    TranscriptionDialogFragment msgDialog = new TranscriptionDialogFragment();
    msgDialog.show(fr, "Dialog");
  }
    catch (Exception e) {
    e.printStackTrace();
    Log.e("error displaying dialog",e.getLocalizedMessage());
  }
}

我的片段

public class TranscriptionDialogFragment extends DialogFragment {

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_transcription, container, false);
    getDialog().setTitle("Simple Dialog");
    return rootView;
  }
}

我在适配器中的构造函数:

public AllCallsRecyclerAdapter(List<AllCallsData> list, Context context) {
  this.mInflater = LayoutInflater.from(context);
  this.list = list;
  this.context = context;
  mydb = new DBHelper(context);
}

这是因为您试图在以下代码中将应用程序上下文转换为 activity:

FragmentManager fr = ((Activity) context).getFragmentManager();

这是一个错误。

您需要确保 contextactivity 而不是 应用程序.