Sabir Hossain Sabir Hossain -4 years ago 196
Android Question

android.app.Application cannot be cast to android.support.v7.app.AppCompatActivity

I'm trying to start a Fragment inside my RecycleAdapter but when cast my Context with the AppCompatActivity the App crashed and inside logcat I got the message that android.app.Application cannot be cast to android.support.v7.app.AppCompatActivity.

here is my onClickListener inside RecycleAdapter.

holder.ItemClickButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FragmentTransaction fragmentTransaction;
Toast.makeText(CTX,"Row Clicked id : "+homeCycleDataProvider.getId(),Toast.LENGTH_SHORT).show();

ItemsFragment fragobj = new ItemsFragment();
FragmentManager manager = ((AppCompatActivity) CTX).getSupportFragmentManager();
fragmentTransaction = manager.beginTransaction()
fragmentTransaction.replace(R.id.main_container, fragobj);
fragmentTransaction.commit();
}
});


here is my Adapter Initialization where I pass the context.

adapter = new ItemsRecycleAdapter(arrayList,getContext());


LOGCAT.

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.a1appstudio.sabirhossain.xpresdelivery, PID: 3109
java.lang.ClassCastException: android.app.Application cannot be cast to android.support.v7.app.AppCompatActivity
at com.a1appstudio.sabirhossain.xpresdelivery.ItemsListViewPackage.ItemsRecycleAdapter$1.onClick(ItemsRecycleAdapter.java:66)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Answer Source

A context is not always an Activity, even when you're in an Activity. It could be an Application, or a wrapper around another context. It's almost always wrong to cast a Context to an Activity. If you absolutely need one, you should pass in an Activity as a parameter, rather than a Context. Or better yet, pass in the support fragment manager directly rather than the activity, since that's all you need it for.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download