0

In MainActivity I have interface

   public interface MyListener{
        void myMethod(boolean done);
    }

but when I trying cast in onCreate

myListener = (MyListener) this;

I got java.lang.ClassCastException

I also have variable in MainActivity:

private MyListener mylistener;

What I should fix here ?

purcha
  • 371
  • 3
  • 12

1 Answers1

0

You MainActivity must implement your interface if you want to do :

myListener = (MyListener) this;

So your code should be like this

public class MainActivity extends AppCompatActivity implements MyListener {}

EDIT

In your Fragment add this :

public class MyFragment extends Fragment {

private MyListener mListener;

@Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try {
            mListener = (MyListener) context;
        } catch (ClassCastException e) {
            throw new ClassCastException(context.toString()
                    + " must implement MyListener");
        }
    }

Then in your MainActivity

public class MainActivity extends AppCompatActivity implements MyListener {
...
@Override
    public void myMethod(Boolean done) {
        //Stuff with this 
    }
Skizo-ozᴉʞS ツ
  • 19,464
  • 18
  • 81
  • 148
  • if Android Studio generated interface in Fragment, we don't need to implement interface in Fragment but in MainActivity - yes, so if i generate interface in MainActivity I should implement interface in Fragment ? – purcha Oct 04 '18 at 08:39
  • check here, he don't implement: https://stackoverflow.com/questions/51641902/update-textview-in-fragment-from-activity – purcha Oct 04 '18 at 08:42
  • In theory you want to modify the views on MainActivity not in Fragment, but if you want to do it, see my answer and do the other way arround – Skizo-ozᴉʞS ツ Oct 04 '18 at 08:45
  • but I want the opposite, call back from MainActivity to fragment, not a fragment to MainActivity :) way arround give me error – purcha Oct 04 '18 at 08:47