Исключить указатель на исключение .setOnClickListener
У меня возникла проблема с прослушивателем кликов для кнопки отправки модальности входа.
Это ошибка.
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
У меня есть разумное понимание того, что такое исключение нулевого указателя, и я тщательно искал проблему, подобную моей. Я попытался переформатировать прослушиватель кликов несколькими способами, удостоверился, что у меня есть правильный идентификатор вида и т.д.
package...
import...
public class MainActivity extends ActionBarActivity implements NavigationDrawerFragment.NavigationDrawerCallbacks {
//Variables
String currentPage = "";
Stack<String> crumbs = new Stack<String>();
//Fragment managing the behaviors, interactions and presentation of the navigation drawer.
private NavigationDrawerFragment mNavigationDrawerFragment;
// Used to store the last screen title. For use in {@link #restoreActionBar()}.
public CharSequence mTitle;
//temp
AuthenticateUserTokenResult authenticateUserTokenResult;
String loginErrorMessage = "";
String loginErrorTitle = "";
Boolean logonSuccessful = false;
Dialog loginDialog;
// Login EditTexts
EditText Username;
EditText CompanyID;
EditText Password;
Button Submit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle(); // Set up the drawer.
mNavigationDrawerFragment.setUp(R.id.navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout));
if(authenticateUserTokenResult == null) {
attemptLogin();
}
}
public void attemptLogin() {
loginDialog = new Dialog(this,android.R.style.Theme_Translucent_NoTitleBar);
loginDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
loginDialog.setContentView(R.layout.login_modal);
loginDialog.setCancelable(false);
//loginDialog.setOnCancelListener(cancelListener);
loginDialog.show();
Submit = (Button)findViewById(R.id.Submit);
Submit.setOnClickListener(new View.OnClickListener() // the error is on this line (specifically the .setOnClickListener)
{
@Override
public void onClick(View v)
{
ClyxUserLogin user = new ClyxUserLogin();
Username = (EditText)findViewById(R.id.Username);
user.logon = Username.getText().toString();
CompanyID = (EditText)findViewById(R.id.CompanyID);
user.idCompany = Integer.parseInt(CompanyID.getText().toString());
Password = (EditText)findViewById(R.id.Password);
user.password = Password.getText().toString();
user.idApplication = 142;
authenticate(user);
}
});
}
Существует больше, очевидно, но не относящихся к теме, я думаю.
Вот файл XML для диалогового окна с кнопкой на нем.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#3366FF">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:background="#FFFFFF" >
<TextView
android:id="@+id/LoginTitle"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:layout_marginTop="10dp"
android:layout_marginStart="10dp"
android:textColor="#000000"
android:textSize="20sp"
android:text="Login" />
<EditText
android:id="@+id/Username"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_below="@+id/LoginTitle"
android:layout_margin="10dp"
android:hint="Username" />
<EditText
android:id="@+id/CompanyID"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_below="@+id/Username"
android:layout_alignStart="@+id/Username"
android:inputType="number"
android:hint="Company ID" />
<EditText
android:id="@+id/Password"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_below="@+id/CompanyID"
android:layout_alignStart="@+id/Username"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:inputType="textPassword"
android:hint="Password" />
<Button
android:id="@+id/Submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/Password"
android:layout_marginBottom="10dp"
android:layout_centerHorizontal="true"
android:text="Login" />
</RelativeLayout>
</RelativeLayout>
Любая помощь будет принята с благодарностью.
Ответы
Ответ 1
Submit
null
, потому что он не является частью activity_main.xml
Когда вы вызываете findViewById
внутри Activity
, он будет искать View
внутри вашего макета активности.
попробуйте это вместо:
Submit = (Button)loginDialog.findViewById(R.id.Submit);
Другое: вы используете
android:layout_below="@+id/LoginTitle"
но то, что вы хотите, вероятно,
android:layout_below="@id/LoginTitle"
См. этот вопрос о различии между @id
и @+id
.
Ответ 2
android.widget.Button.setOnClickListener(android.view.View $OnClickListener)" по ссылке нулевого объекта
Поскольку кнопка Submit
находится внутри login_modal
, поэтому вам нужно использовать кнопку loginDialog
для доступа:
Submit = (Button)loginDialog.findViewById(R.id.Submit);
Ответ 3
Попробуйте дать вашей Button в вашем main.xml более описательное имя, например:
<Button
android:id="@+id/buttonXYZ"
(используйте строчные буквы в ваших xml файлах, по крайней мере, первую букву)
И затем в своем классе MainActivity объявите его как:
Button buttonXYZ;
В вашем методе onCreate (Bundle savedInstanceState) определите его как:
buttonXYZ = (Button) findViewById(R.id.buttonXYZ);
Кроме того, переместите кнопки/текстовые элементы снаружи и поместите их перед .setOnClickListener - это делает код более чистым.
Username = (EditText)findViewById(R.id.Username);
CompanyID = (EditText)findViewById(R.id.CompanyID);