EditText.setText()空指针异常 [英] EditText.setText() Null Pointer Exception

查看:78
本文介绍了EditText.setText()空指针异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个NPE令我发疯,也许只是隧道视野",但我无法解决.我在活动中有一个片段,在活动的 onCreate()中我实例化了片段.然后,当将片段添加到活动中时,我从活动中调用Fragments方法.代码在下面

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);

在片段中我有:

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

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

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

添加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);

    }

我已经检查了布局,并且那里有editText id.

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

推荐答案

问题在于 this.edtFullName 尚未初始化,因为 onActivityCreated 尚未被调用,因此 edtFullName 在调用 setText()方法

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

您可以在 loadUserData 中传递 EditText 的引用,而不是在 onActivityCreated

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

这篇关于EditText.setText()空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆