Reputation: 13
I'm trying to make my first Android app and I'm stuck with the following problem:
I implemented an interface in my host activity, which I have created. The problem is that I get a NullPointerException
when I call the method in my fragment.
Interface
public interface GameInterface {
public void gameOver();
}
Fragment
public class GameFragment extends Fragment implements View.OnClickListener {
...
GameInterface gameInterface;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Button trueButton = (Button) getView().findViewById(R.id.button_true);
trueButton.setOnClickListener(this);
}
@Override
public void onClick(View view) {
...
gameInterface.gameOver();
}
}
Activity
public class MainActivity extends Activity implements GameInterface {
...
private void showStartFragment() {
StartFragment startFragment = new StartFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.container, startFragment);
ft.commit();
}
@Override
public void gameOver() {
showStartFragment();
}
}
I get the NullPointerException
in the fragment on the line where I call gameInterface.gameOver();
.
Upvotes: 1
Views: 1246
Reputation: 5105
The variable was not initialized. Add that in onActivityCreated
gameInterface = (GameInterface) getActivity();
Assuming GameFragment
is created in MainActivity
Edit (thanks @Squonk):
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
gameInterface = (GameInterface) activity
}
Upvotes: 2