对话框中 FindViewById 处的 Android java.lang.NullPointerException

标签 android nullpointerexception

我看到很多类似的问题,但仍然无法解决我的问题。

这是日志:

01-26 00:30:49.714: ERROR/AndroidRuntime(616): FATAL EXCEPTION: main
        java.lang.NullPointerException
        at com.app.newItemList.onDialogPositiveClick(newItemList.java:39)
        at com.app.itemDialog$2.onClick(itemDialog.java:39)
        at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:4745)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
        at dalvik.system.NativeStart.main(Native Method)

这里是相关的 Java 文件:

 package com.app;

import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;

import java.util.ArrayList;

/**
 * Created with IntelliJ IDEA.
 * User: Aljarhi
 * Date: 1/24/13
 * Time: 10:22 PM
 * To change this template use File | Settings | File Templates.
 */

public class newItemList extends FragmentActivity
        implements itemDialog.NoticeDialogListener{

    public void showNoticeDialog() {
        // Create an instance of the dialog fragment and show it
        DialogFragment dialog = new itemDialog();
        dialog.show(getFragmentManager(), "NoticeDialogFragment");
    }

    // The dialog fragment receives a reference to this Activity through the
    // Fragment.onAttach() callback, which it uses to call the following methods
    // defined by the NoticeDialogFragment.NoticeDialogListener interface
    @Override
    public void onDialogPositiveClick(DialogInterface dialog, int id) {
        // User touched the dialog's positive button
        EditText et = (EditText) findViewById(R.id.editText1);
        adapter.add(et.getText().toString());
    }

    @Override
    public void onDialogNegativeClick(DialogInterface dialog, int id) {
        // User touched the dialog's negative button
        dialog.cancel();
    }

    ArrayAdapter<String> adapter;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.new_list);

        ListView lvc = (ListView) findViewById(R.id.listView3);

        adapter = new ArrayAdapter<String>(this, R.id.textView2, new ArrayList<String>());
        lvc.setAdapter(adapter);
    }

    public void addItem(View clickedButton)
    {
        showNoticeDialog();
    }
}

package com.app;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.widget.EditText;

/**
 * Created with IntelliJ IDEA.
 * User: Aljarhi
 * Date: 1/25/13
 * Time: 3:11 PM
 * To change this template use File | Settings | File Templates.
 */
public class itemDialog extends DialogFragment
{

    public interface NoticeDialogListener {
        public void onDialogPositiveClick(DialogInterface dialog, int id);
        public void onDialogNegativeClick(DialogInterface dialog, int id);
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        // Get the layout inflater
        LayoutInflater inflater = getActivity().getLayoutInflater();

        // Inflate and set the layout for the dialog
        // Pass null as the parent view because its going in the dialog layout
        builder.setView(inflater.inflate(R.layout.dialog_item, null))
                // Add action buttons
                .setPositiveButton("ok", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        mListener.onDialogPositiveClick(dialog, id);
                    }
                })
                .setNegativeButton("cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        mListener.onDialogNegativeClick(dialog, id);
                    }
                });
        return builder.create();
    }

    // Use this instance of the interface to deliver action events
    NoticeDialogListener mListener;

    // Override the Fragment.onAttach() method to instantiate the NoticeDialogListener
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        // Verify that the host activity implements the callback interface
        try {
            // Instantiate the NoticeDialogListener so we can send events to the host
            mListener = (NoticeDialogListener) activity;
        } catch (ClassCastException e) {
            // The activity doesn't implement the interface, throw exception
            throw new ClassCastException(activity.toString()
                    + " must implement NoticeDialogListener");
        }
    }
}

这里是相关的xml文件:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent" android:orientation="vertical" android:gravity="center_horizontal|top">

    <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Mezzo List"
            android:id="@+id/textView2" android:layout_gravity="center_horizontal|top"/>
    <ListView
            android:layout_width="wrap_content"
            android:layout_height="263dp"
            android:id="@+id/listView3" android:layout_gravity="center_horizontal|top" android:choiceMode="none"/>

    <Button
            android:layout_width="81dp"
            android:layout_height="wrap_content"
            android:text="Add Item"
            android:id="@+id/button4" android:onClick="addItem"/>

</LinearLayout>

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <TextView
            android:layout_width="wrap_content"
            android:layout_height="25dp"
            android:text="Mezzo List"
            android:id="@+id/textView4" android:layout_gravity="center"/>
    <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Enter Item Name:"
            android:id="@+id/textView5" android:layout_gravity="center" android:textSize="20dp"/>
    <EditText
            android:layout_width="205dp"
            android:layout_height="wrap_content"
            android:text="New EditText"
            android:id="@+id/editText1" android:layout_gravity="center" android:inputType="text"
            android:hint="Item Name"
            />
</LinearLayout>

我发现问题出在 edittext1 id 无法识别或作为 edittext 尽管它出现在选项列表中并且我从那里选择了它。我正在使用 intellij Idea 12.0.2。任何帮助将不胜感激。提前致谢。

最佳答案

实际上,我找到了解决问题的方法。

为了使 findViewById 正常工作,您必须首先选择膨胀的 View 或首先将其内容设置为 corresondong xml 文件。所以,这里是解决方案:

final View textEntryView = inflater.inflate(R.layout.dialog_item, null);
EditText et = (EditText) textEntryView.findViewById(R.id.editText1);

感谢大家的帮助。

关于对话框中 FindViewById 处的 Android java.lang.NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14530690/

相关文章:

android - dispose 后订阅 observable

android - 如何使用 Cast Companion LIbrary 实现音量控制?

android - Phonegap - 构建后出现错误 404

java - 添加到 HashMap 给出 NPI

java - 当互联网连接丢失时,优雅地处理 NPE 并在 OnPostExecute/AsyncTask 中显示 AlertDialog - Android/Java

android - 即使在启用 Places API 后,Android 中的自动建议也无法正常工作

java - 任务定义/gradle中的定义

java - 为什么这段代码不抛出 NullPointerException?

java - 如果在这种情况下列表为空,我如何避免 java 中的空指针异常?

android - 寻找 Android 电子书编程的开源引用