程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程綜合問答 >> edittext-Android - 無法從EditText Control讀取文本

edittext-Android - 無法從EditText Control讀取文本

編輯:編程綜合問答
Android - 無法從EditText Control讀取文本

程序中有一個AlertDialog對話框,使用了一個自定義布局。在OnClick事件中我想讀出用戶輸入的信息。使用了以下的代碼:

//Login Dialog
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            // Get the layout inflater
            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
            builder.setView(inflater.inflate(R.layout.dialog_signin, null))
            .setPositiveButton(R.string.tvLoginTitle, new DialogInterface.OnClickListener() {
                   @Override
                   public void onClick(DialogInterface dialog, int id) {
                       String username = ((EditText)findViewById(R.id.loginUsername)).getText().toString();
                       String password = ((EditText)findViewById(R.id.loginPassword)).getText().toString();
                       System.out.println(username);
                       System.out.println(password);
                       ConnectionID.loginToServer(cMainActivity, username, password);
                   }
               })
               .setNegativeButton(R.string.btnExit, new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                       System.exit(0);

                   }
               }).show(); 

但是當我想要讀出信息的時候,獲得一個來自dialog_signin的布局中NullPointerException異常。

<EditText
    android:id="@+id/loginUsername"
    android:inputType="textEmailAddress"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="16dp"
    android:layout_marginLeft="4dp"
    android:layout_marginRight="4dp"
    android:layout_marginBottom="4dp"
    android:hint="@string/tvUsername" />
<EditText
    android:id="@+id/loginPassword"
    android:inputType="textPassword"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="4dp"
    android:layout_marginLeft="4dp"
    android:layout_marginRight="4dp"
    android:layout_marginBottom="16dp"
    android:fontFamily="sans-serif"
    android:hint="@string/tvPassword"/>

最佳回答:


如果用戶名和密碼是對話框中的,你應該使用以下代碼:

View v = inflater.inflate(R.layout.dialog_signin, null);
 builder.setView(v);


String username = ((EditText)v.findViewById(R.id.loginUsername)).getText().toString();

String password = ((EditText)v.findViewById(R.id.loginPassword)).getText().toString();
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved