【问题标题】:Getting Null Pointer when accessing a component from another Class从另一个类访问组件时获取空指针
【发布时间】:2011-03-25 03:46:41
【问题描述】:

我开发了一个扩展 Dialog 的 A 类。

我使用以下代码对 A 类进行了膨胀:

View layout = inflater.inflate(R.layout.custom_alert, null, false);

custom_alert 布局文件中,我添加了一个带有android:id="@+id/edit" 的EditText。

场景是这样的:

用户点击特定的listitem 并打开一个对话框,用户在其中输入值(编辑文本)。

我有一个 Activity 屏幕,考虑扩展 Activity 的 B 类。

从 B 类,我调用 A 类。

当用户在对话框中输入值并单击“确定”按钮时,我需要检索该值并将其存储在数据库中。

下面提供代码sn-p

LayoutInflater inflater = getLayoutInflater();

inflater.inflate(R.layout.custom_dialog, null);


EditText txt = (EditText) findViewById(R.id.edit);

String value = txt.getText().toString();

但是,即使在膨胀 custom_dialog 之后,我也无法获取文本并且出现空指针异常。

我正在粘贴更新代码...仍然没有得到 EditText 值,只有 null

对话框生成器 = 新对话框(此)

视图视图 = LayoutInflater.from(SampleScreen.this).inflate(R.layout.custom_alert, null); builder.setContentView(view);

EditText nameEditTxt = (EditText) view.findViewById(R.id.edit);

字符串值 = nameEditTxt.getText().toString();

【问题讨论】:

    标签: android


    【解决方案1】:

    LayoutInflater#inflate 返回膨胀的视图,您应该调用 findViewById on。

    View view = LayoutInflater.from(this).inflate(R.layout.custom_dialog, null);
    EditText text = (EditText) view.findViewById(R.id.edit);
    

    确保以某种方式将其链接到视图层次结构:

    dialog.setContentView(view);
    

    或类似的。

    【讨论】:

    • 感谢您的回复,空指针异常消失了,但是返回的数据我得到了null,while是不正确的。未获取在 EditText 上输入的数据。 EditText lapNameEditTxt = (EditText) view .findViewById(R.id.edit);字符串值 = lapNameEditTxt.getText() .toString();
    • 您必须第二次调用 dialog.findViewById(R.id.edit) 。您不能为一个全新的视图充气并期望检索有关屏幕上内容的信息。
    • 你能详细解释一下.. dialog.findViewById(R.id.edit) 从哪里调用第二次......如果你粘贴伪/示例代码会很好吗?
    • 当然。你想在哪里称呼它?
    【解决方案2】:

    您的代码 sn-p 不提供调用它的上下文,但您还需要确保它是从存在 Android 对象的上下文中调用的 - 例如不是在您的构造函数中,而是在生命周期之一中Dialog 的方法(例如 onCreate)。

    【讨论】:

    • 认为这在 onCreateDialog 中使用 Activity 的上下文会很好。至少,我一直是这样的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-12
    • 2012-09-02
    • 2014-11-18
    • 2012-09-07
    • 2014-04-06
    • 1970-01-01
    • 2013-09-08
    相关资源
    最近更新 更多