gpt4 book ai didi

java - spinner.setAdapter() 中的 NullPointerException

转载 作者:行者123 更新时间:2023-12-01 23:01:51 25 4
gpt4 key购买 nike

我想创建一个微调器来显示列表m。但以下代码在 spinner.setAdapter(spinner_adapter) 处给出了 NullPointerException。为什么会出现这种情况?

public class Request extends ListActivity {
private static final String[] m={"A","B","O","AB","others"};
private TextView view;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SimpleAdapter adapter = new SimpleAdapter(this, getData(),
R.layout.listitem, new String[] { "name", "quant" },
new int[] {R.id.name, R.id.quant });
setListAdapter(adapter);

view = (TextView) findViewById(R.id.spinnerText);
Spinner spinner = (Spinner) findViewById(R.id.spinner01);
ArrayAdapter<String> spinner_adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,m);
spinner_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinner_adapter);
spinner.setOnItemSelectedListener(new SpinnerSelectedListener());
spinner.setVisibility(View.VISIBLE);
}

class SpinnerSelectedListener implements OnItemSelectedListener{
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
view.setText(""+m[arg2]);
}
public void onNothingSelected(AdapterView<?> arg0) {
}
}
}

最佳答案

你的线路

    Spinner spinner = (Spinner) findViewById(R.id.spinner01);

最终 spinner 为空,因为没有内容 View 分配给您的 Activity 。

因此,当尝试与微调器交互时,会抛出 NPE。

在初始化其 View 之前,将 setContentView(R.layout.your_layout_content); 添加到 onCreate 方法。

关于java - spinner.setAdapter() 中的 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23308855/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com