Android-Can';t从onCreate()方法访问int
我有以下Android-Can';t从onCreate()方法访问int,android,Android,我有以下int: protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); setContentView(R.layout.activity_score); // Show the Up button in th
int
:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setContentView(R.layout.activity_score);
// Show the Up button in the action bar.
setupActionBar();
Intent i = getIntent();
String max = i.getStringExtra(MainActivity.EXTRA_MAX);
final int maxInt = Integer.parseInt(max);
我想从这里访问它:
public void plus1 (View V)
{
maxInt ++;
}
但是当int
在类中时,即使不使用final
,我也会得到一个错误:
public class ScoreActivity extends Activity {
我崩溃了。你的应用程序崩溃了,因为plus1中的变量
maxInt
未定义maxInt
的作用域是onCreate的本地作用域。另外,final
变量类似于C语言中的constant
变量。它们只能在初始化时获得一个值,这意味着不能更改它们的值
maxInt不应为final,而应为全局变量:
public class ScoreActivity extends Activity {
int maxInt;
protected void onCreate(Bundle savedInstanceState) {
...
maxInt = Integer.parseInt(max);
...
}
public void plus1 (View V) {
maxInt ++;
}
...
}
您的应用程序正在崩溃,因为plus1中的变量
maxInt
未定义maxInt
的作用域是onCreate的本地作用域。另外,final
变量类似于C语言中的constant
变量。它们只能在初始化时获得一个值,这意味着不能更改它们的值
maxInt不应为final,而应为全局变量:
public class ScoreActivity extends Activity {
int maxInt;
protected void onCreate(Bundle savedInstanceState) {
...
maxInt = Integer.parseInt(max);
...
}
public void plus1 (View V) {
maxInt ++;
}
...
}
声明
intmaxint代码>在onCreate()之前,但在类内部
并更改您的代码
final int maxInt=Integer.parseInt(max)代码>
至
maxInt = Integer.parseInt(max);
声明intmaxint代码>在onCreate()之前,但在类内部
并更改您的代码
final int maxInt=Integer.parseInt(max)代码>
至
maxInt = Integer.parseInt(max);
无法在另一个方法中访问maxInt
,原因是您在onCreate方法中创建了它。它的作用域是该方法的局部,所以它对类的其余部分不可见。此外,一旦OnCreate()超出范围,maxInt
将被销毁,其中存储的数据将丢失
如果要访问整个类中的对象/变量,请将其设置为global
int maxInt;
protected void onCreate(Bundle savedInstanceState) {
maxInt = Integer.parseInt(max);
...
....
}
public void plus1 (View V) {
.....
maxInt ++;
..........
}
无法在另一个方法中访问maxInt
,原因是您在onCreate方法中创建了它。它的作用域是该方法的局部,所以它对类的其余部分不可见。此外,一旦OnCreate()超出范围,maxInt
将被销毁,其中存储的数据将丢失
如果要访问整个类中的对象/变量,请将其设置为global
int maxInt;
protected void onCreate(Bundle savedInstanceState) {
maxInt = Integer.parseInt(max);
...
....
}
public void plus1 (View V) {
.....
maxInt ++;
..........
}
崩溃的堆栈跟踪是什么?它可能是由完全不同的问题引起的。崩溃的堆栈跟踪是什么?它可能是由一个完全不同的问题引起的。