0

This is the setter method in MainActivity class

public void setNumPlats(int numero){
this.numPlats = numero;
}

I'm trying to acces to this method from fragment class, but i dont know how i need to do this.

In the fragment class i'm trying to do this

I'm trying it, and it doesnt makes error when i put it into onAttach, but when i execute the app it crashes. @Override
public void onAttach(Activity activity) {
    super.onAttach(activity);

}

((MainActivity)getActivity()).setNumPlats(adapter.getNumPlats());
@Override
public void onDetach() {
    super.onDetach();
}
  • while hoomi answer is good ... i would choose something like this https://gist.github.com/SelvinPL/5003577e7bd8b4f67de9 – Selvin Mar 13 '15 at 16:54
  • where exactly `((MainActivity)getActivity()).setNumPlats(adapter.getNumPlats());` is called ... – Selvin Mar 13 '15 at 16:59

1 Answers1

0

Try this from the fragment: ((MainActivity)getActivity()).setNumPlats(20)

Selvin
  • 6,598
  • 3
  • 37
  • 43
hoomi
  • 1,882
  • 2
  • 16
  • 17
  • without those parenthesis you cast setNumPlats resutls not getActivity() :) – Selvin Mar 13 '15 at 16:37
  • 1
    also i would add some null checks ... there is a few moments in fragment life-cycle where getActivity() may returns null ... also ... there is a chcance that you will not use this fragment in MainActivity ... then you have to create interface and let the Activity implements it ... then check if getActivity() is instance of this interface and cast to it .. – Selvin Mar 13 '15 at 16:38
  • I'm trying to use this part of code, but i thing i'm using it bad. Where part of fragment class i will do that? –  Mar 13 '15 at 16:41
  • it should work ... when you wana use it in the fragment? could you add the sample usage of it in the fragment? ... this code can be use everywhere after onAttach – Selvin Mar 13 '15 at 16:42
  • It should work after `onAttach(Activity)` and before `onDetach(Activity)` is called. – hoomi Mar 13 '15 at 16:44
  • I'm trying it, and it doesnt makes error when i put it into onAttach, but when i execute the app it crashes. –  Mar 13 '15 at 16:56
  • Can you add the stacktrace? – hoomi Mar 13 '15 at 16:57
  • but please, not with the NPE :) ... if adapter is null i will have to downvote your question ... – Selvin Mar 13 '15 at 17:00