我正在尝试从数据库中获取一些数据到微调器,但是它显示以下错误:-
07-21 05:54:42.450: E/AndroidRuntime(11918): FATAL EXCEPTION: main
07-21 05:54:42.450: E/AndroidRuntime(11918): Process: com.example.teste1, PID: 11918
07-21 05:54:42.450: E/AndroidRuntime(11918): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.teste1/com.example.teste1.MainActivity}: java.lang.NullPointerException
07-21 05:54:42.450: E/AndroidRuntime(11918): Caused by: java.lang.NullPointerException
07-21 05:54:42.450: E/AndroidRuntime(11918): at com.example.teste1.MainActivity.loadSpinnerData(MainActivity.java:79)
07-21 05:54:42.450: E/AndroidRuntime(11918): at com.example.teste1.MainActivity.onCreate(MainActivity.java:32)
第79行是:-
spinner.setAdapter(dataAdapter);
第32行是:-
loadSpinnerData();
我已经使用以下方法检查dataAdapter是否为null:
System.out.println(dataAdapter.getItem(5).toString());
但是它显示第5个索引处的值,这意味着dataAdapter不为null。
这是我的MainActivity类:
public class MainActivity extends Activity implements OnItemSelectedListener {
Button btnDisplay;
ImageButton btnAdd;
Spinner spinner;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnAdd = (ImageButton) findViewById(R.id.btnAdd);
btnDisplay = (Button) findViewById(R.id.btnDisplay);
spinner = (Spinner) findViewById(R.id.spinner1);
// Loading spinner data from database
try {
loadSpinnerData();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Spinner click listener
spinner.setOnItemSelectedListener(this);
MyLayoutOperation.add(this, btnAdd);
MyLayoutOperation.display(this, btnDisplay);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/**
* Function to load the spinner data from SQLite database
* @throws IOException
* */
private void loadSpinnerData() throws IOException {
// database handler
DBHelper db = new DBHelper(getApplicationContext());
// Spinner Drop down elements
List<String> products = db.getAllProducts();
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, products);
// Drop down layout style - list view with radio button
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//For testing purpose only
System.out.println(dataAdapter.getItem(5).toString());
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
}
最佳答案
您的微调框似乎为空。尝试两件事:-
1)检查您是否真的创建了ID为spinner
的spinner1
。
2)如果您已经创建了微调器,则尝试通过对它进行Sysout来检查其中的值。
关于java - 填充微调器dataAdapter时显示为空,但其中包含值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24862713/