我有这段代码。 当我启动调试时,我收到错误
java.lang.RuntimeException:无法实例化活动 ComponentInfo {nicola.pokerstarsleaguecalculator / nicola.pokerstarsleaguecalculator.MainActivity}: java.lang.NullPointerException:尝试调用虚方法 'android.view.Window $ Callback android.view.Window.getCallback()'上 null对象引用。
我想错误就在这里:
if (JTIscritti.getText().length()!=0)
我该如何纠正? 感谢
public class MainActivity extends AppCompatActivity {
public EditText JTIscritti = (EditText)findViewById(R.id.JTIscritti);
public TextView JLPremiati = (TextView) findViewById(R.id.JLPremiati);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
JTIscritti.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
premiati();
}
public void premiati() {
if (JTIscritti.getText().length()!=0) {
PuntiLeague aPunti = new PuntiLeague();
String strIscritti = String.valueOf(JTIscritti.getText());
int iscritti = Integer.parseInt((strIscritti));
int premiati = aPunti.aPremio(iscritti);
String strPremiati = Integer.toString(premiati);
JLPremiati.setText(strPremiati);
}
else JLPremiati.setText("0");
}
});
}
}
更新: 我解决了谢谢@ΦXocę웃Пepeúpaツ和@VishnuSP移动一些声明+作业
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText JTIscritti = (EditText)findViewById(R.id.JTIscritti);
final TextView JLPremiati = (TextView) findViewById(R.id.JLPremiati);
答案 0 :(得分:3)
你必须做这个初始化
public EditText JTIscritti = (EditText)findViewById(R.id.JTIscritti);
public TextView JLPremiati = (TextView) findViewById(R.id.JLPremiati);
在onCreate方法中,请记住在回调之前布局没有膨胀/初始化,因此 JTIscritti 和 JLPremiati 将被初始化为空引用,所以在空引用上执行此JTIscritti.getText()
将抛出NPE!
答案 1 :(得分:3)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
JTIscritti = (EditText)findViewById(R.id.JTIscritti);
JLPremiati = (TextView) findViewById(R.id.JLPremiati);
//----your code/logic----
}
只有在
之后才会创建视图super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
执行。之前`findViewById'将返回null。