尝试调用虚方法' android.text.Editable android.widget.EditText.getText()'在null对象引用上

时间:2017-03-29 11:45:09

标签: android xml

我正在尝试构建一个应用程序,其中我从对话框中获取输入,然后在列表视图中对其进行充气。但得到下面提到的错误。是否是我使用编辑文本的问题?任何帮助都非常适合。

错误:                                                                                       -

-------- beginning of crash
03-29 16:55:09.080 17033-17033/com.example.sumeet.assignment4sess8 E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                     Process: com.example.sumeet.assignment4sess8, PID: 17033
                                                                                     java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
                                                                                         at com.example.sumeet.assignment4sess8.MainActivity$2.onClick(MainActivity.java:77)
                                                                                         at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:161)
                                                                                         at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                         at android.os.Looper.loop(Looper.java:135)
                                                                                         at android.app.ActivityThread.main(ActivityThread.java:5268)
                                                                                         at java.lang.reflect.Method.invoke(Native Method)
                                                                                         at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:902)
                                                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:697)

MainActivity.java

    package com.example.sumeet.assignment4sess8;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private ListView listView;
    private ArrayList<String> al_contactName, al_contactNumber, al_contactDOB;
    private EditText ev_diag_contactName, ev_diag_contactNumber, ev_diag_DOB;
    String diag_contactName, diag_contactNumber, diag_contactDOB;
    protected MyAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView) findViewById(R.id.lv_contacts);

        al_contactName = new ArrayList<>();
        al_contactNumber = new ArrayList<>();
        al_contactDOB = new ArrayList<>();
        adapter = new MyAdapter(getApplicationContext(), al_contactName,al_contactNumber,al_contactDOB);
        listView.setAdapter(adapter);
    }

    //attaching the menu to the main activity
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.options_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case R.id.admenu: {
                addItem();
                Toast.makeText(getApplicationContext(), "Item Added", Toast.LENGTH_LONG).show();
                return true;
            }
            default:
                return super.onOptionsItemSelected(item);
        }


    }

    private void addItem() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
        LayoutInflater inflater = this.getLayoutInflater();
        // Inflate and set the layout for the dialog
        // Pass null as the parent view because its going in the dialog layout
        alertDialog.setView(inflater.inflate(R.layout.dialoge_content, null))
                // Add action buttons
                .setPositiveButton("Save", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Toast.makeText(getApplicationContext(),"Hi",Toast.LENGTH_LONG).show();
                        // assign identifiers to the edittext in dialoge
                        ev_diag_contactName = (EditText) findViewById(R.id.diag_contact_name);
                        ev_diag_contactNumber = (EditText) findViewById(R.id.diag_phone_number);
                        ev_diag_DOB = (EditText) findViewById(R.id.diag_date_of_birth);

                        //get the string values
                        diag_contactName = ev_diag_contactName.getText().toString();
                        diag_contactNumber = ev_diag_contactNumber.getText().toString();
                        diag_contactDOB = ev_diag_DOB.getText().toString();

                        //add the string values to the arraylist variabe
                        al_contactName.add(diag_contactName);
                        al_contactNumber.add(diag_contactNumber);
                        al_contactDOB.add(diag_contactDOB);

                    }
                }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
            }
        });
        alertDialog.show();
    }
}

MyAdapter.java

package com.example.sumeet.assignment4sess8;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.ArrayList;

/**
 * Created by Sumeet on 29-03-2017.
 */

public class MyAdapter extends BaseAdapter {
    Context context;
    LayoutInflater inflater;

    private ArrayList<String> al_contactName, al_contactNumber, al_contactDOB;

    public MyAdapter(Context context, ArrayList al_contactName, ArrayList al_contactNumber, ArrayList al_contactDOB) {
        this.context = context;
        inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
        this.al_contactName = al_contactName;
        this.al_contactNumber = al_contactNumber;
        this.al_contactDOB = al_contactDOB;


    }

    public int getCount() {
        return al_contactName.size();
    }

    @Override
    public Object getItem(int i) {
        return null;
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    public class ViewHolder {
        TextView contactName, contactNumber, contactDOB;

        void bindView(View convertView) {
            //getting values from name_contacts_dob
            contactName = (TextView) convertView.findViewById(R.id.contact_name);
            contactNumber = (TextView) convertView.findViewById(R.id.contact_number);
            contactDOB = (TextView) convertView.findViewById(R.id.contact_DOB);
        }
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            // convertView = getLayoutInflater().inflate(R.layout.name_and_contacts, parent, false);
            // LayoutInflater inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.name_contacts_dob, parent);
            holder.bindView(convertView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.contactName.setText(al_contactName.get(position));
        holder.contactNumber.setText(al_contactNumber.get(position));
        holder.contactDOB.setText(al_contactDOB.get(position));
        return convertView;
    }
}

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:id="@+id/lv_contacts"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    </ListView>
</RelativeLayout>

options_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/admenu"
        android:title="Add" />
</menu>

dialoge_content.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/holo_red_dark"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="4dp"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="4dp"
        android:layout_marginTop="16dp"
        android:background="@android:color/holo_red_dark"
        android:text="Enter the Details"
        android:textColor="@android:color/background_dark"
        android:textSize="18dp" />

    <EditText
        android:id="@+id/diag_contact_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="16dp"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="4dp"
        android:layout_marginTop="4dp"
        android:background="@android:color/background_dark"
        android:hint="Name" />

    <EditText
        android:id="@+id/diag_phone_number"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="16dp"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="4dp"
        android:layout_marginTop="4dp"
        android:background="@android:color/background_dark"
        android:fontFamily="sans-serif"
        android:hint="Phone Number" />

    <EditText
        android:id="@+id/diag_date_of_birth"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="16dp"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="4dp"
        android:layout_marginTop="4dp"
        android:background="@android:color/background_dark"
        android:fontFamily="sans-serif"
        android:hint="Date of Birth" />

</LinearLayout>

name_contacts_dob.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout

        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:id="@+id/contact_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"

            android:background="@android:color/holo_blue_bright"
            android:paddingLeft="10dp"
            android:textColor="#000000"
            android:textSize="16sp"
            tools:ignore="NewApi" />

        <TextView
            android:id="@+id/contact_number"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@android:color/holo_blue_bright"
            android:paddingLeft="10dp"
            android:textColor="#000000"
            android:textSize="16sp"
            tools:ignore="NewApi" />

        <TextView
            android:id="@+id/contact_DOB"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@android:color/holo_blue_bright"
            android:paddingLeft="10dp"
            android:textColor="#000000"
            android:textSize="16sp"
            tools:ignore="NewApi" />

    </LinearLayout>

</LinearLayout>

1 个答案:

答案 0 :(得分:2)

ev_diag_contactName = (EditText) findViewById(R.id.diag_contact_name);
ev_diag_contactNumber = (EditText) findViewById(R.id.diag_phone_number);
ev_diag_DOB = (EditText) findViewById(R.id.diag_date_of_birth);

这是错误的。您为此对话框夸大了特定布局,并且所有这些EditTexts都驻留在那里。因此,膨胀视图并将其保存到View对象并在该视图中查找EditText。

所以,修改你的代码如下。

private View view;

private void addItem() {
  AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
  LayoutInflater inflater = this.getLayoutInflater();
  // inflate the View
  view = inflater.inflate(R.layout.dialoge_content, null);

  alertDialog.setView(view)
  .setPositiveButton("Save", new DialogInterface.OnClickListener() {

         @Override
         public void onClick(DialogInterface dialogInterface, int i) {
                 Toast.makeText(getApplicationContext(),"Hi",Toast.LENGTH_LONG).show();
                 // assign identifiers to the edittext in dialoge
/*
   findViewById is now view.findViewById
*/
                 ev_diag_contactName = (EditText) view.findViewById(R.id.diag_contact_name);
                 ev_diag_contactNumber = (EditText) view.findViewById(R.id.diag_phone_number);
                 ev_diag_DOB = (EditText) view.findViewById(R.id.diag_date_of_birth);

                 //Rest of the code


         }
  }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
        }
  });
  alertDialog.show();
}