O
O
Orkhan Hasanli2020-04-30 04:52:39
Android
Orkhan Hasanli, 2020-04-30 04:52:39

Why is Attempt to invoke virtual method setArguments() on a null object reference thrown?

Good day!
I study android and try to transfer information from one fragment to another.
Implemented interface:

public interface DataPassListener {
    void passData(String data);
}


In the first snippet:
@Override
public void onAttach(@NonNull Context context) {
    super.onAttach(context);

    if(context instanceof DataPassListener) {
        dataPassListener = (DataPassListener) context;
    } else {
        throw new RuntimeException(context.toString() + " must implement dataPassListener");
    }
}


In Activity:
public class UserCreationActivity extends AppCompatActivity implements DataPassListener {

  @Override
    public void passData(String data) {

        Log.d(LOG, "Получили сообщение в UserCreationActivity:  "+ data);

        fragment_2 = (UserCreationActivityFragment_2) this.getSupportFragmentManager().findFragmentById(R.id.secondFragmentUserCreation);

        Bundle bundle = new Bundle();
        bundle.putString("age",data);
        fragment_2.setArguments(bundle);
    }

}


In the second snippet

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    	View rootView = inflater.inflate(R.layout.fragment_2_user_creation, container, false);
    	String age = null;
    	if (getArguments() != null) {
            age = getArguments().getString("age");
        }
        Log.d(LOG, "Возраст  " + age); 
}


Information is transferred from the first fragment to the Activity, but when setArguments is triggered, an NPE exception occurs:
java.lang.NullPointerException: Attempt to invoke virtual method 'void info.md7.lfk.fragments.UserCreationActivityFragment_2.setArguments(android.os.Bundle)' on a null object reference


How to resolve this exception? Thanks in advance for advice and tips.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2020-04-30
@azerphoenix

Obviously
(UserCreationActivityFragment_2) this.getSupportFragmentManager().findFragmentById(R.id.secondFragmentUserCreation);
Returns null.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question