android - 当我为警告对话框中的编辑文本执行 getText() 时获取空指针 (Android)

标签 android nullpointerexception android-edittext

我为我的应用程序制作了一个自定义警报对话框,用作注册屏幕。除了当我输入我的数据并单击提交它时,我的应用程序由于空指针异常而崩溃 这是我的主要 Activity 代码:

package com.picknchew.companionapp;


import java.io.File;
import java.io.FileOutputStream;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;


public class MainActivity extends Activity {

Button savedListsButton;
Button pickIngredientsButton;
Button submitButton;
Button signUpButton;
Button loginButton;
Button saveAListButton;
Button viewSelectedButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    savedListsButton =(Button) findViewById(R.id.savedListsButton);
    pickIngredientsButton =(Button) findViewById(R.id.pickIngredientsButton);
    submitButton =(Button) findViewById(R.id.submitButton);
    signUpButton =(Button) findViewById(R.id.signUpButton);
    loginButton =(Button) findViewById(R.id.loginButton);
    saveAListButton =(Button) findViewById(R.id.saveAListButton);
    viewSelectedButton =(Button) findViewById(R.id.viewSelectedButton);


}


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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}


public void signUp(View view){
    displayAlertSignUp("Sign Up", "Sign Up");
}
private void displayAlertSignUp(String title, String positiveButton) {
    final EditText username = (EditText) findViewById(R.id.username2);
    final EditText password1 = (EditText) findViewById(R.id.password3);
    final EditText password2 = (EditText) findViewById(R.id.password4);


    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    LayoutInflater inflater = MainActivity.this.getLayoutInflater();
    builder.setView(inflater.inflate(R.layout.dialog_signup, null));
    builder.setTitle(title);

    builder.setPositiveButton(positiveButton, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int id) {
            String sendUser = (username.getText().toString());
            String pass1 = (password1.getText().toString());
            String pass2 = (password2.getText().toString());

            doTheSignUpThing(sendUser,pass1,pass2);
        }
    });
    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {

        }
    });
    AlertDialog theAlertDialog = builder.create();
    theAlertDialog.show();
}


private void displayAlert(String title, String message, String positiveButton) {

    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    builder.setTitle(title);
    builder.setPositiveButton(positiveButton, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {

        }
    });

    //builder.setNegativeButton("Cancel", null);

    builder.setMessage(message);
    AlertDialog theAlertDialog = builder.create();
    theAlertDialog.show();
}


protected void doTheSignUpThing(String sendUser, String pass1, String pass2) {
    if(pass1.equals(pass2)){
        String filePath = createUserDirectory(sendUser);
        if (filePath.equals("exists")){
            displayAlert("Error","User Already Exists","OK");
        }
        else{
            createUserInfoFile(filePath, sendUser,pass1);
            displayAlert("Done","Sign Up Succesful","OK");
        }

    }
    else{
        displayAlert("Error","Passwords Do Not Match\nPlease Try Again","OK");
    }
}


private void createUserInfoFile(String path, String user, String pass)  {
    File file = new File(path+"/user");
    String data = (user + " " + pass);

    FileOutputStream outputStream;


    try {
        outputStream = openFileOutput(file.getAbsolutePath(), Context.MODE_PRIVATE);
        outputStream.write(data.getBytes());
        outputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

}


private String createUserDirectory(String user) {
    boolean bool;
    File filePath = this.getFilesDir();
    String path = filePath.getAbsolutePath();
    File file = new File(path+"/"+user); 
    bool = file.mkdir();
    if (bool==false){
        return "exists";
    }
    else{
        return file.getAbsolutePath();
    }
}



}

这是对话框的 xml 文件

<EditText
    android:id="@+id/username2"
    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:hint="@string/username"
    android:inputType="textEmailAddress" />

<EditText
    android:id="@+id/password3"
    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="15dp"
    android:hint="@string/password"
    android:inputType="textPassword" />

<EditText
    android:id="@+id/password4"
    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:hint="@string/password2"
    android:inputType="textPassword" />

这是 logcat:

 12-06 12:06:45.284: W/dalvikvm(8911): threadid=1: thread exiting with uncaught exception (group=0x416ced40)
12-06 12:06:45.288: E/AndroidRuntime(8911): FATAL EXCEPTION: main
12-06 12:06:45.288: E/AndroidRuntime(8911): Process: com.picknchew.companionapp, PID: 8911
12-06 12:06:45.288: E/AndroidRuntime(8911): java.lang.NullPointerException
12-06 12:06:45.288: E/AndroidRuntime(8911):     at com.picknchew.companionapp.MainActivity$1.onClick(MainActivity.java:85)
12-06 12:06:45.288: E/AndroidRuntime(8911):     at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
12-06 12:06:45.288: E/AndroidRuntime(8911):     at android.os.Handler.dispatchMessage(Handler.java:102)
12-06 12:06:45.288: E/AndroidRuntime(8911):     at android.os.Looper.loop(Looper.java:136)
12-06 12:06:45.288: E/AndroidRuntime(8911):     at android.app.ActivityThread.main(ActivityThread.java:5086)
12-06 12:06:45.288: E/AndroidRuntime(8911):     at java.lang.reflect.Method.invokeNative(Native Method)
12-06 12:06:45.288: E/AndroidRuntime(8911):     at java.lang.reflect.Method.invoke(Method.java:515)
12-06 12:06:45.288: E/AndroidRuntime(8911):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
12-06 12:06:45.288: E/AndroidRuntime(8911):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
 12-06 12:06:45.288: E/AndroidRuntime(8911):    at dalvik.system.NativeStart.main(Native Method)

我已经查了几个小时了,但我似乎无法弄清楚我到底做错了什么。

最佳答案

您需要从您扩充的对话 View 中获取对话对象:

View dialogView = inflater.inflate(R.layout.dialog_signup, null)
final EditText username = (EditText) dialogView.findViewById(R.id.username2);
final EditText password1 = (EditText) dialogView.findViewById(R.id.password3);
final EditText password2 = (EditText) dialogView.findViewById(R.id.password4);

关于android - 当我为警告对话框中的编辑文本执行 getText() 时获取空指针 (Android),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27334389/

相关文章:

android - EditText 结果基于 Spinner 选择 Sqlite (2 Way Selection)

安卓工作室 : Creating a normal xml file in assests folder?

android - 所有 EditText 框中的非 Activity InputConnection 警告

android - 在没有互联网和谷歌服务器的情况下将语音转换为Android中的文本

c# - 为什么 NullReferenceException 比 CLR 中的任何其他异常都昂贵?

android - SwitchPreference (PreferenceAtivity) - Android NULL

java - EMDK 安卓工作室

android - 在edittext android中设置光标位置

android - ImageView 超出父边界?

java - Android、Foursquare 和 &#8212;特点