我有下面的代码。
public class Start extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
ArrayList<String> aPlayerList = getIntent().getStringArrayListExtra("playerList");
static ArrayList<Integer> aScores = getIntent().getIntegerArrayListExtra("scores");
...当我试图将ArrayList<Integer> aScores变成静态的:Non-static method getIntent() cannot be referenced from a static context时,我遇到了一个错误,我不知道如何修复它。
如果有帮助的话,这就是传递意图的方式:
Bundle bund = new Bundle();
bund.putStringArrayList("playerList", playerList);
bund.putIntegerArrayList("scores", scores);
Intent intent = new Intent(Players.this, Start.class);
intent.putExtras(bund);
startActivity(intent);任何帮助都将不胜感激,如果你能添加代码来修复它,那就太好了。谢谢,
发布于 2014-06-09 22:52:23
因为你的语法错了。
您不能在方法static中创建一个变量,这有什么用呢?静态意味着字段与类相关,因此您可以在没有任何引用(ClassName.staticField)的情况下访问它。
方法内部的变量与方法相关,所以不能在方法之外访问它们,所以这里如何使用静态?
你确定你不会和final混淆吗?在这里是有效的。
要解决您的问题,只需要将static ArrayList<Integer> aScores作为类的字段,这样您就可以在代码中的任何地方访问它。然后将您的onCreate方法编辑为
aScores = getIntent().getIntegerArrayListExtra("scores");因此,它将保存aScores字段中的数组列表。
发布于 2014-06-09 22:45:31
这是因为getIntent()是一个非静态方法,不应该引用一个静态字段。
解决方案:
删除arrayList的静态。
发布于 2014-06-09 22:50:49
静态方法只创建一次,因此不能引用getIntent(),因为Java不知道要引用的方法的哪个实例。
有关静态方法如何工作的更多信息,请查看here。
https://stackoverflow.com/questions/24130213
复制相似问题