我对Android有点新鲜。处理一个应用程序,让用户输入一个数字,然后计算斐波纳契数列,然后以1秒的间隔显示序列中的每个元素。但是当我尝试在for循环中使用线程进行显示时,我遇到了问题。我尝试从数组列表打印但它给我一个错误与我的计数器变量(j)。我尝试在一个更简单的应用程序中运行这个相同的方法,并且数组列表工作得很好。我不知道为什么这次不起作用。我希望这是一个简单明显的错误。谁能告诉我为什么?代码发布如下:
public class MainActivity extends Activity {
// primary widgets
private EditText editText;
private TextView textView;
private Button button1;
Thread thread;
static ArrayList<Integer> fibList = new ArrayList<Integer>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText1);
textView = (TextView) findViewById(R.id.textView2);
button1 = (Button) findViewById(R.id.button1);
//Attempt to clear TextView
textView.setText("");
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//Clear Textview
String array = " ";
fibList.clear();
textView.setText(array);
final String input = editText.getText().toString();
int number = Integer.parseInt(input);
int tmp = 0;
// confirm input
if (number < 20) {
Toast.makeText(getApplicationContext(),
"You entered: " + number, Toast.LENGTH_LONG).show();
for (int i = 0; i <= number; i++) {
fibList.add(fib(i));
// sum even numbers
if (fib(i) % 2 == 0) {
tmp += fib(i);
}
}
} else {
Toast.makeText(getApplicationContext(),
"Number is too Large: " + number, Toast.LENGTH_LONG)
.show();
}
Log.i("TEST", "ARRAY"+fibList);
thread = new Thread(new Runnable(){
@Override
public void run(){
for(int j = 0; j < fibList.size(); j++){
runOnUiThread(new Runnable(){
@Override
public void run(){
//ERROR OCCURS HERE: Cannot refer to a non-final variable j
//inside an inner class defined in a different method
textView.append(fibList.get(j).toString());
textView.append("");
}
});
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} //wait one second
}
}
});
thread.start();
}
});
}
// run fibonacci sequence
public static int fib(int n) {
if (n < 2) {
return n;
} else {
return fib(n - 1) + fib(n - 2);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
答案 0 :(得分:1)
解决问题的简单解决方法是以这种方式声明临时final
变量:
for(int j = 0; j < fibList.size(); j++){
final int finalJ = j;
runOnUiThread(new Runnable(){
@Override
public void run(){
//ERROR OCCURS HERE: Cannot refer to a non-final variable j
//inside an inner class defined in a different method
textView.append(fibList.get(finalJ).toString());
textView.append("");
}
});
答案 1 :(得分:0)
你有一个更严重的问题。 您正在尝试从线程中操作texView。这是不允许的。只有GUI线程可以操作屏幕对象或者Bad Things Happen。
看看AsyncTask。它旨在解决您正在尝试解决的问题。
http://developer.android.com/reference/android/os/AsyncTask.html