问题描述:

This is the code I wrote:

// create a view in dialog box

final View fileView = getLayoutInflater().inflate(R.layout.filename, null);

String[] array_spinner = new String[5];

array_spinner[0]="1";

array_spinner[1]="2";

array_spinner[2]="3";

array_spinner[3]="4";

array_spinner[4]="5";

Spinner s = (Spinner) findViewById(R.id.sp_CAT);

ArrayAdapter adapter = new ArrayAdapter(this,

android.R.layout.simple_spinner_item, array_spinner);

s.setAdapter(adapter);

s.setSelection(2);

//Spinner mCAT = (Spinner) findViewById(R.id.sp_CAT);

//ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(

//fileView.getContext(), R.array.a_CAT, android.R.layout.simple_spinner_item);

//adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

//mCAT.setAdapter(adapter);

EditText mSID = (EditText) fileView.findViewById(R.id.et_SID);

EditText mSCD = (EditText) fileView.findViewById(R.id.et_SCD);

EditText mNUM = (EditText) fileView.findViewById(R.id.et_NUM);

final String tSID=mSID.getText().toString();

final String tSCD=mSCD.getText().toString();

final String tNUM=mNUM.getText().toString();

// show dialog box

new AlertDialog.Builder(CameraActivity3.this).setTitle("Set FileName")

.setView(fileView)

.setPositiveButton("OK", new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int whichButton) {

Toast.makeText(CameraActivity3.this, tSID+tSCD+tNUM, Toast.LENGTH_SHORT).show();

}// public void onClick

}) // setPositiveButton

.setNegativeButton("Cancel", null).show();

However, I am receiving a null pointer exception. After some testing (commenting out some lines), it seems to be related to the spinner adapter. Did I get something wrong?

网友答案:

Use this:

Spinner s = (Spinner) fileView.findViewById(R.id.sp_CAT);
网友答案:

write below code line

Spinner s = (Spinner) fileView.findViewById(R.id.sp_CAT);

instead of

Spinner s = (Spinner) findViewById(R.id.sp_CAT);
网友答案:

For anyone looking at this in the future using DialogFragment to build the AlertDialog, you can't use just this in the ArrayAdapter. My solution is below:

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    LayoutInflater inflater = getActivity().getLayoutInflater();
    View myView = inflater.inflate(R.layout.program_num_spinner_popup, null);

    builder.setView(myView);

    programNumbers = (Spinner) myView.findViewById(R.id.prog_num_spinner_list);
    ArrayAdapter<CharSequence> numbersAdapter = ArrayAdapter.createFromResource(this.getActivity(), R.array.program_numbers, android.R.layout.simple_spinner_item);
    numbersAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    programNumbers.setAdapter(numbersAdapter);

I replaced this with this.getActivity() combined with Zaz Gmy's answer and Dipak Keshariya's answer (which are the same).

相关阅读:
Top