EditText.setText() Null Pointer Exception

≯℡__Kan透↙ 提交于 2019-12-25 03:55:15

问题


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



来源:https://stackoverflow.com/questions/25416743/edittext-settext-null-pointer-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!