我有一个CardsParser类,它解析一个网页并返回一个带有WordCard对象的ArrayList。然后对象显示在TextView中。
第一个请求总是正常。但后来我得到的结果与第一次相同。我的TextView清除,新请求运行,我总是从第一个ArrayList获取对象。
我发现onPostExecute方法总是获取与参数相同的ArrayList,但我不知道为什么,因为我每次都创建新的CardsParser并且doInBackground方法获取正确的参数。
提前致谢。
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
EditText editText;
Button srchBtn;
TextView foundWords;
CardsParser cardsParser;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = findViewById(R.id.editText);
srchBtn = findViewById(R.id.srchBtn);
srchBtn.setOnClickListener(this);
foundWords = findViewById(R.id.foundWords);
foundWords.setMovementMethod(new ScrollingMovementMethod());
}
private class AsyncRequest extends AsyncTask<String, Void, ArrayList<WordCard>> {
@Override
protected ArrayList<WordCard> doInBackground(String... args) {
cardsParser = new CardsParser();
return cardsParser.parse(editText.getText().toString());
}
@Override
protected void onPostExecute(ArrayList<WordCard> cards) {
for (WordCard card : cards) {
foundWords.append(card.word);
foundWords.append("\n");
}
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.srchBtn:
foundWords.setText("");
new AsyncRequest().execute();
break;
}
}
我发现了错误。 CardsParser类每次都生成相同的URL,这就是它无法正常工作的原因。