[英]Variable 'i' is accessed from within inner class, needs to be declared final
I'm trying to send value to another activity intent.putExtra("doctor",String.valueOf(items.get(i)));
我正在尝试将值发送到另一个活动intent.putExtra("doctor",String.valueOf(items.get(i)));
but it gives error.但它给出了错误。 That's " Variable 'i' is accessed from within inner class, needs to be declared final ".那就是“变量'i'是从内部类中访问的,需要声明为final ”。 The code is running in the for loop so I can't give final value because it's iterator .代码在 for 循环中运行,所以我不能给出最终值,因为它是iterator 。
How can we solve it?我们该如何解决?
Part of code部分代码
for (int i = 0; i < c; i++) {
items.add(options[i]);
spinnerDialog=new SpinnerDialog(NewActivity.this,items,"Search","Close");// With No Animation
spinnerDialog=new SpinnerDialog(NewActivity.this,items,"Search",R.style.DialogAnimations_SmileWindow,"Close");// With Animation
spinnerDialog.setCancellable(true); // for cancellable
spinnerDialog.setShowKeyboard(false);// for open keyboard by default
spinnerDialog.bindOnSpinerListener(new OnSpinerItemClick() {
@Override
public void onClick(String item, int position) {
Intent intent = new Intent(NewActivity.this,PrescriptionActivity.class);
intent.putExtra("doctor",String.valueOf(items.get(i)));
NewActivity.this.startActivity(intent);
}
});
findViewById(R.id.show).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
spinnerDialog.showSpinerDialog();
}
});
} }
The variables used in the anonymous classes implementations (or lambda expressions) must be effectively final, or else the undefined behavior would happen.匿名类实现(或 lambda 表达式)中使用的变量必须是有效的 final,否则会发生未定义的行为。
I suppose that you want to handle on click action the item
at the position obtained from the method using the int position
, not from the outer loop.我想您想在单击操作时使用int position
从方法获得的位置处的item
,而不是从外部循环。 Do the following:请执行下列操作:
spinnerDialog.bindOnSpinerListener(new OnSpinerItemClick() {
@Override
public void onClick(String item, int position) {
Intent intent = new Intent(NewActivity.this,PrescriptionActivity.class);
intent.putExtra("doctor",String.valueOf(items.get(position))); // here
NewActivity.this.startActivity(intent);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.