我在Android开发方面相当新,我在使用Spinners时遇到了一些麻烦。 我的活动有2个Spinners,我试图在选择第一个之后填充第二个。
第一个Spinner的填充方法工作正常,第二个Spinner的返回数组也正常,但是当我spin2.setAdapter(adapter)
时,抛出NullPointerException
。
我放了一个Toast.show()
来查看给我第二个spinner
上的值的方法是否有效。就在我删除setAdapter()
时,应用程序不会崩溃。但是,第二个spinner
是空的。
我把片段的代码放在我看错的地方:
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_info_de_lineas,
container, false);
return rootView;
}
@Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
Spinner spin = (Spinner)getActivity().findViewById(R.id.spEmpresa);
AccesoADatos db = new AccesoADatos(getActivity().getApplicationContext());
SQLiteDatabase database = db.getWritableDatabase();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Cursor cursor = db.getAllEmpresas();
if(cursor.moveToFirst()){
do{
adapter.add(cursor.getString(1));
} while(cursor.moveToNext());
}
spin.setAdapter(adapter);
Spinner spin2 = (Spinner)getActivity().findViewById(R.id.spEmpresa);
spin2.setOnItemSelectedListener(new OnItemSelectedListener(){
@Override
public void onItemSelected(AdapterView<?> parent, View v, int pos,
long id) {
Spinner spinLineas = (Spinner)parent.findViewById(R.id.spLinea);
Spinner spinEmpresa = (Spinner)parent.findViewById(R.id.spEmpresa);
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(parent.getContext(),android.R.layout.simple_spinner_item);
//
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
int posicion = spinEmpresa.getSelectedItemPosition();
int idpos = (int) spinEmpresa.getItemIdAtPosition(posicion);
AccesoADatos db = new AccesoADatos(parent.getContext());
SQLiteDatabase database = db.getWritableDatabase();
Cursor cursor2 = db.getAllLineas(idpos);
if(cursor2.moveToFirst()){
do{
adapter2.add(cursor2.getString(1));
Toast.makeText(parent.getContext(), "Linea "+ cursor2.getString(1), Toast.LENGTH_LONG).show();
} while(cursor2.moveToNext());
}
spinLineas.setAdapter(adapter2);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
答案 0 :(得分:1)
替换:
Spinner spin = (Spinner)getActivity().findViewById(R.id.spEmpresa);
使用:
Spinner spin = (Spinner)getView().findViewById(R.id.spEmpresa);
也适用于spin2 ......