0

I have this NPE that is driving me crazy, maybe it's just "tunnel vision" but I can't solve it. I have a fragment inside an activity, and in the activity's onCreate() I instantiate fragment. Then later when the fragment is added to activity I call fragments method from the activity. The code is below

transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.ActionInputFragment, settingsFragment).addToBackStack(null);
transaction.commit();

if(jsonUserData != null)
  settingsFragment.loadUserData(jsonUserData);

In the fragment I have:

@Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        this.ctx = getActivity();

    edtFullName = (EditText) getActivity().findViewById(R.id.edtFullNameSettings);

    edtFullName.addTextChangedListener(new TextWatcher .....);
}

Adding the textwatcher works. Below (in the same fragment) is the method whose call generates the error:

public void loadUserData(JSONObject jsonUserData) {
        String fullName;
        try {
            fullName = String.format("%s %s", jsonUserData.getString("first_name"), jsonUserData.getString("last_name"));
        } catch (JSONException e) {
            fullName = "";
        }
        //if(edtFullName != null)
            this.edtFullName.setText(fullName);

    }

I have checked the layout and the editText id is there.

1 Answer 1

2

the problem is that this.edtFullName is not yet initialized because onActivityCreated is not called yet thus edtFullName is null upon calling setText() method

You can pass the reference of the EditText in the loadUserData instead in the onActivityCreated

Sign up to request clarification or add additional context in comments.

2 Comments

I think I got it. Thank you very much. I cannot pass in a reference but I can make the method call not necessary by taking the work to the fragment. Thank You. I will accept you answer as soon as I can, but consider expanding it a bit for future visitors :D
@Rod_Algonquin How to pass the reference of edittext to that method?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.