这是我到目前为止的代码。
playername.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:fontFamily="sans-serif"
android:paddingTop="@dimen/fab_margin"
android:text="Choose the server: "
android:textAlignment="center"
android:textColor="@color/black"
android:textStyle="bold" />
<Spinner
android:id="@+id/serverspinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="@array/servers_array">
</Spinner>
</LinearLayout>
<EditText
android:id="@+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:hint="@string/insert_name"
android:maxLines="1" />
</LinearLayout>
MainActivity.java
....
public void playerStats(final View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final LayoutInflater inflater = getLayoutInflater();
final View inflator = inflater.inflate(R.layout.playername, null);
final Spinner spinner = (Spinner) findViewById(R.id.serverspinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(v.getContext(),
android.R.layout.simple_spinner_item, getResources()
.getStringArray(R.array.servers_array));
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
builder.setView(inflator)
.setPositiveButton(R.string.done, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
String server = spinner.getSelectedItem().toString();
EditText userNameText = (EditText) inflator.findViewById(R.id.username);
String userName = userNameText.getText().toString();
Intent intent = new Intent(MainActivity.this,PlayerStats.class);
intent.putExtra("nume",userName);
intent.putExtra("sever",server);
startActivity(intent);
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
})
;
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
在我的layout.xml中(未显示,因为它并不重要),我有一个按钮启动&#34; playerStats&#34;从我的活动中启动一个alertdialog窗口,我给出了一些输入。在这个窗口中,我有一个微调器和一个edittext,我无法让微调器正常工作(正常工作意味着能够从数组中选择字符串 - servers_array)。
从MainActivity中标记的行,我收到此错误:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Spinner.setAdapter(android.widget.SpinnerAdapter)' on a null object reference
答案 0 :(得分:2)
我设法让它发挥作用。
替换此行:
final Spinner spinner = (Spinner) findViewById(R.id.serverspinner);
有了这个:
final Spinner spinner = (Spinner) inflator.findViewById(R.id.serverspinner);