0

我在 setPositiveButton onClick() 方法中的 EditText() 上使用 getText() 方法,并且在执行操作时出现 RuntimeException。这是代码:

protected Dialog onCreateDialog(int id) {
     switch(id) {
     case NICKNAME_DIALOG_ID:
         LayoutInflater nicknameInflater = (LayoutInflater) 
             getSystemService(Context.LAYOUT_INFLATER_SERVICE);
         final View nicknameLayout = nicknameInflater.inflate
            (R.layout.nickname_dialog, (ViewGroup) findViewById
             (R.id.linearLayout_root));
         final EditText nickname = (EditText)findViewById(R.id.editText_nickname);   

            AlertDialog.Builder nicknameBuilder = new AlertDialog.Builder(this);
            nicknameBuilder.setView(nicknameLayout);                

            nicknameBuilder.setNegativeButton
               (R.string.nickname_dialog_cancel, new DialogInterface.OnClickListener()
               {                    
                @SuppressWarnings("deprecation")
                public void onClick(DialogInterface dialog, 
                                                    int whichButton) {                      
                    SettingsActivity.this.removeDialog(NICKNAME_DIALOG_ID);
                }
            });

            nicknameBuilder.setPositiveButton(R.string.nickname_dialog_ok, 
                                    new DialogInterface.OnClickListener() {                
                @SuppressWarnings("deprecation")
                public void onClick(DialogInterface dialog, 
                                                    int which) {
                    Editor editor = m_GameSettings.edit();
                    editor.putString
                            (VolimHrvatsku.GAME_PREFERENCES_NICKNAME, 
                            nickname.getText().toString());//here's the error
                    editor.commit();
                    SettingsActivity.this.removeDialog(NICKNAME_DIALOG_ID);
                }
            });

            AlertDialog nicknameDialog = nicknameBuilder.create();
            return nicknameDialog;

我曾经在 button.getText() 方法中遇到过类似的问题,它显示了一些 int 值,比如这个。


我仍然遇到 getText() 的问题。这是一个例外:

!SettingsActivity$4.onClick(DialogInterface, int) line: 110 
AlertDialog(AlertController$ButtonHandler).handleMessage(Message) line: 158 
AlertController$ButtonHandler(Handler).dispatchMessage(Message) line: 99    
Looper.loop() line: 123
ActivityThread.main(String[]) line: 4633    
Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: 
not   available [native method] 
Method.invoke(Object, Object...) line: 521  
ZygoteInit$MethodAndArgsCaller.run() line: 858  
ZygoteInit.main(String[]) line: 616 
NativeStart.main(String[]) line: not available [native method]  
4

1 回答 1

3

我猜这是一个空指针异常,因为他的视图膨胀似乎关闭了。

试试这条线而不是你的线

final EditText nickname = (EditText)nicknameLayout.findViewById(R.id.editText_nickname);   
于 2013-09-21T21:16:20.490 回答