Java 错误尝试在空对象引用上调用虚拟方法“android.text.Editable android.widget.EditText.getText()”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36701022/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 18:34:50  来源:igfitidea点击:

Error Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference

javaandroidsqlite

提问by B L Λ C K

I have been trying to create a module in the app. This module is like create a new user profile. When user taps on the icon in the toolbar it shows the dialog box which has the form.

我一直在尝试在应用程序中创建一个模块。这个模块就像创建一个新的用户配置文件。当用户点击工具栏中的图标时,它会显示具有表单的对话框。

The form has 5 main input

表单有5个主要输入

  1. Name --> Used EditText
  2. Gender --> Used RadioGroup
  3. Height --> Used EditText
  4. Weight --> Used EditText
  5. Age --> Used EditText
  1. 名称 --> 使用的 EditText
  2. 性别 --> 使用的 RadioGroup
  3. 高度 --> 使用的 EditText
  4. 重量 --> 使用的 EditText
  5. 年龄 --> 使用过的 EditText

When I click on the dialog box donebutton it should save the information in the SQLite database and create a usercardin the phone at the sametime. User can create N number of profile in the app and for that user has to fill the info and tap on the done but whenever user taps on the done button it crashes the whole app. This much I have gone so far and encountered a problem -

当我单击对话框完成按钮时,它应该将信息保存在 SQLite 数据库中并同时在手机中创建用户。用户可以在应用程序中创建 N 个配置文件,并且该用户必须填写信息并点击完成,但每当用户点击完成按钮时,它就会使整个应用程序崩溃。到目前为止,我已经走了这么多,遇到了一个问题 -

add_form.xml

添加_form.xml

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

    <TextView
        android:id="@+id/form_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#3498DB"
        android:textColor="#FFF"
        android:textSize="21sp"
        android:padding="16dp"
        android:text="ADD PERSON"/>
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="16dp"
        android:layout_below="@+id/form_title">
        <EditText
            android:id="@+id/person_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingTop="16dp"
            android:paddingBottom="16dp"
            android:textSize="14sp"
            android:hint="PERSON NAME"
            android:inputType="text" />

        <RadioGroup
            android:id="@+id/gender_selection"
            android:layout_below="@+id/person_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:orientation="horizontal">
            <RadioButton
                android:id="@+id/male"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="MALE"
                android:onClick="RadioButtonClicked"
                />
            <RadioButton
                android:id="@+id/female"
                android:layout_marginLeft="16dp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="FEMALE"
                android:onClick="RadioButtonClicked"/>
        </RadioGroup>

        <LinearLayout
            android:id="@+id/person_metrics"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:layout_below="@+id/gender_selection">
            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:layout_weight="1">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:text="WEIGHT"/>
                <EditText
                    android:id="@+id/person_weight"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textAlignment="center"
                    android:padding="16dp"
                    android:textSize="21sp"
                    android:hint="KG"
                    android:inputType="text" />
            </LinearLayout>
            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:layout_weight="1">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:text="HEIGHT"/>
                <EditText
                    android:id="@+id/person_height"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textAlignment="center"
                    android:padding="16dp"
                    android:textSize="21sp"
                    android:hint="M"
                    android:inputType="text" />
            </LinearLayout>
            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:layout_weight="1">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:text="AGE"/>
                <EditText
                    android:id="@+id/person_age"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textAlignment="center"
                    android:padding="16dp"
                    android:textSize="21sp"
                    android:hint="Y"
                    android:inputType="text" />
            </LinearLayout>

        </LinearLayout>
    </RelativeLayout>

</RelativeLayout>

PersonDBHelper.java

PersonDBHelper.java

package com.example.kuro.bloodpressure;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.text.Editable;

/**
 * Created by Kuro on 4/18/2016.
 */
public class PersonDBHelper extends SQLiteOpenHelper{

    public static final String DATABASE_NAME = "person_profile.db";
    public static final String TABLE_NAME = "person_info_table";
    public static final String id = "ID";
    public static final String name = "NAME";
    public static final String gender = "GENDER";
    public static final String weight = "WEIGHT";
    public static final String height = "HEIGHT";
    public static final String age = "AGE";
//    public static final String blood_pressure_upper = "BPU";
//    public static final String blood_pressure_lowser = "BPL";
//    public static final String heart_beat = "HB";

    public PersonDBHelper(Context context) {
        super(context, DATABASE_NAME,null,1);
    }


    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table " + TABLE_NAME +
                "(ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
                " NAME STRING, " +
                " GENDER STRING," +
                " WEIGHT INTEGER," +
                " HEIGHT INTEGER, " +
                " AGE INTEGER)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXSITS"+TABLE_NAME);
        onCreate(db);
    }

    public boolean insertData(String name, String gender, String weight, String height, String age){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();

        contentValues.put(name,name);
        contentValues.put(gender,gender);
        contentValues.put(weight,weight);
        contentValues.put(height,height);
        contentValues.put(age, age);

        long result = db.insert(TABLE_NAME,null,contentValues);
        if (result==-1) return false;
        else return true;
    }

    public Cursor getAllData(){
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor res = db.rawQuery("select * from"+TABLE_NAME,null);
        return res;
    }
}

MainActivity.java

主活动.java

package com.example.kuro.bloodpressure;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.app.Fragment;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import org.w3c.dom.Text;

public class MainActivity extends AppCompatActivity {
    public Toolbar mtoolbar;
    public TabLayout mtabLayout;
    public ViewPager mviewPager;
    public ViewPagerAdapter viewPagerAdapter;
    PersonDBHelper mydb;

    EditText name, weight, height, age;
    RadioGroup mradioGroup;
    RadioButton male,female;
    TextView selectedGender;
    private String gender_value;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mtoolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(mtoolbar);

        mtabLayout = (TabLayout) findViewById(R.id.tablayout);
        mviewPager = (ViewPager) findViewById(R.id.viewpager);
        viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
        viewPagerAdapter.addFragments(new Measure(), "MEASURE");
        viewPagerAdapter.addFragments(new People(), "PEOPLE");
        mviewPager.setAdapter(viewPagerAdapter);
        mtabLayout.setupWithViewPager(mviewPager);

        mydb = new PersonDBHelper(this);


    }

    public void RadioButtonClicked(View view) {
        boolean checked = ((RadioButton) view).isChecked();
        switch (view.getId()) {
            case R.id.male:
                if (checked)gender_value = "male";
                else male.setChecked(false);
                break;
            case R.id.female:
                if (checked) gender_value = "female";
                else female.setChecked(false);
                break;
        }

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    public void viewAll(){

    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.add_person:
                AlertDialog.Builder add_people_form = new AlertDialog.Builder(MainActivity.this);
                add_people_form.setView(R.layout.add_form)
                        .setCancelable(false)
                        .setPositiveButton("DONE", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {


                                name = (EditText) findViewById(R.id.person_name);
                                mradioGroup = (RadioGroup)findViewById(R.id.gender_selection);
                                male = (RadioButton)findViewById(R.id.male);
                                female = (RadioButton)findViewById(R.id.female);
                                weight = (EditText) findViewById(R.id.person_weight);
                                height = (EditText) findViewById(R.id.person_height);
                                age = (EditText) findViewById(R.id.person_age);


                                String user_name = (String) name.getText().toString();
                                String user_gender = (String) gender_value;
                                String user_weight = (String) weight.getText().toString();
                                String user_height = (String) height.getText().toString();
                                String user_age = (String) age.getText().toString();

                                boolean isInserted = mydb.insertData(user_name,user_gender,user_weight,user_height,user_age);
                                if(isInserted==true)
                                    Toast.makeText(MainActivity.this,"ADDED",Toast.LENGTH_LONG).show();
                                else
                                    Toast.makeText(MainActivity.this,"NOT ADDED",Toast.LENGTH_LONG).show();
                            }
                        })
                        .setNegativeButton("CANCLE", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                            }
                        });
                AlertDialog alert = add_people_form.create();
                alert.show();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

}

Logcat

逻辑猫

04-18 23:22:44.207 28079-28079/com.example.kuro.bloodpressure E/AndroidRuntime: FATAL EXCEPTION: main
                                                                            Process: com.example.kuro.bloodpressure, PID: 28079
                                                                            java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
                                                                                at com.example.kuro.bloodpressure.MainActivity.onClick(MainActivity.java:111)
                                                                                at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:162)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5343)
                                                                                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:905)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)

采纳答案by Eugen Pechanec

You're mixing together dialog and activity views. findViewByIdis a method of Activitybut the view you're trying to use is not part of the activity.

您将对话框和活动视图混合在一起。findViewById是一种方法,Activity但您尝试使用的视图不是活动的一部分。

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.add_person: {
            createAddPersonDialog().show();
        }
        default: {
            return super.onOptionsItemSelected(item);
        }
    }
}

private Dialog createAddPersonDialog() {
    final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

    // Inflate using dialog themed context.
    final Context context = builder.getContext();
    final LayoutInflater inflater = LayoutInflater.from(context);
    final View view = inflater.inflate(R.layout.add_form, null, false);

    // Find widgets inside "view".
    final EditText name = (EditText) view.findViewById(R.id.person_name);
    final RadioGroup mradioGroup = (RadioGroup) view.findViewById(R.id.gender_selection);
    final RadioButton male = (RadioButton) view.findViewById(R.id.male);
    final RadioButton female = (RadioButton) view.findViewById(R.id.female);
    final EditText weight = (EditText) view.findViewById(R.id.person_weight);
    final EditText height = (EditText) view.findViewById(R.id.person_height);
    final EditText age = (EditText) view.findViewById(R.id.person_age);

    final View.OnClickListener listener = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            if (which == DialogInterface.BUTTON_NEGATIVE) {
                dialog.cancel();
                return;
            }

            String user_name = (String) name.getText().toString();
            String user_gender = (String) gender_value;
            String user_weight = (String) weight.getText().toString();
            String user_height = (String) height.getText().toString();
            String user_age = (String) age.getText().toString();

            boolean isInserted = mydb.insertData(user_name, user_gender, user_weight, user_height, user_age);
            if (isInserted == true)
                Toast.makeText(MainActivity.this, "ADDED", Toast.LENGTH_LONG).show();
            else
                Toast.makeText(MainActivity.this, "NOT ADDED", Toast.LENGTH_LONG).show();
        }
     };

     builder
         .setView(view)
         .setCancelable(false)
         .setPositiveButton(android.R.string.ok, listener)
         .setNegativeButton(android.R.string.cancel, listener);
     return builder.create();
}

You may want to assign on click listeners for radio buttons dynamically as well. android:onClickattribute in XML is a way to hell.

您可能还想为单选按钮动态分配点击侦听器。android:onClickXML 中的属性是一种地狱。

回答by Max

Might it be because you're initializing your EditText inside of onOptionsItemSelected than opposed to doing it in the onCreate?

可能是因为您在 onOptionsItemSelected 中初始化 EditText 而不是在 onCreate 中初始化?

回答by Shadab Ansari

Use

name = (EditText)alert.findViewById(R.id.person_name);

instead of

代替

name = (EditText) findViewById(R.id.person_name);

because the views you are accessing are a part of the AlertDialog and not your Activity. Do the same for all other views of your AlertDialog.

因为您正在访问的视图是 AlertDialog 的一部分,而不是您的 Activity。对 AlertDialog 的所有其他视图执行相同操作。

AlertDialog.Builder add_people_form = new AlertDialog.Builder(MainActivity.this);

                add_people_form.setView(getLayoutInflater().inflate(R.layout.add_form,null));
 final AlertDialog alert = add_people_form.create();
                        add_people_form.setCancelable(false)
                        .setPositiveButton("DONE", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {


                                name = (EditText) alert.findViewById(R.id.person_name);
                        })
                        .setNegativeButton("CANCLE", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                            }
                        });

                alert.show();