user3854496 user3854496 - 28 days ago 7
Android Question

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

If I call

((MainActivity)getActivity()).clearApp();
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/com.my.blacky E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.my.blacky, PID: 13362
java.lang.ClassCastException: com.my.blacky.PrefsActivity cannot be cast to com.my.blacky.MainActivity
at com.gerpue.blacky.FragmentPrefs$2.onPreferenceClick(FragmentPrefs.java:62)
at android.preference.Preference.performClick(Preference.java:996)
at android.preference.PreferenceScreen.onItemClick(PreferenceScreen.java:214)
at android.widget.AdapterView.performItemClick(AdapterView.java:310)
at android.widget.AbsListView.performItemClick(AbsListView.java:1188)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3105)
at android.widget.AbsListView$3.run(AbsListView.java:4096)
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:5551)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)

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

MainActivity.clearApp();

clearApp method should be like this in MainActivty

public static void clearApp()
{
       // your implementation 
}