user3854496 user3854496 - 28 days ago 7
Android Question

ClassCastExeption ((MainActivity)getActivity()).clearApp();

If I call

in my PrefsFragment. I get this error... why?

How can I fix this iusse and get understand this error.

08-22 12:33:10.833 13362-13362/ E/AndroidRuntime: FATAL EXCEPTION: main
Process:, PID: 13362
java.lang.ClassCastException: cannot be cast to
at com.gerpue.blacky.FragmentPrefs$2.onPreferenceClick(
at android.preference.Preference.performClick(
at android.preference.PreferenceScreen.onItemClick(
at android.widget.AdapterView.performItemClick(
at android.widget.AbsListView.performItemClick(
at android.widget.AbsListView$
at android.widget.AbsListView$
at android.os.Handler.handleCallback(
at android.os.Handler.dispatchMessage(
at android.os.Looper.loop(
at java.lang.reflect.Method.invoke(Native Method)

Answer Source

Is the method clearApp(); is present in the MainActivity or PrefsActivity ?

If it is in PrefsActivity then you can try some thing like this

((PrefsActivity)getActivity()).clearApp();  // because You are currently in PrefsActivity

If the method is in MainActivity and still you want to use the method from PrefsFragment( PrefsFragment fragment inside the PrefsActivity ). Declare the clearApp() method as static and access like below


clearApp method should be like this in MainActivty

public static void clearApp()
       // your implementation