EditText.setText() Null Pointer Exception

2019-09-07 06:16发布

问题:

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:

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