在我的应用程序中,有一个从数据库获取输入的按钮。当我在短时间内按多次时,它崩溃强>. 我如何使用asynctask避免这个错误?
show.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
showinf();
}
});
}
private String[] columns={"name","surname"};
private void showinf(){
SQLiteDatabase db=v1.getReadableDatabase();
Cursor c=db.query("infos",columns,null,null, null,null,null);
Random mn2=new Random();
int count=c.getCount();
String mn=String.valueOf(count);
int i1=mn2.nextInt(count+1);
c.move(i1);
t1.setText(c.getString(c.getColumnIndex("name")));
t2.setText(c.getString(c.getColumnIndex("surname")));
}
谢谢...
最佳答案
您可以创建一个 boolean 标志(比方说 bDiscardButtonAction
),并将其设置为 true
在onPreExecute()
并将其设置为 false
在onPostExecute()
,类似于:
public class FooTask extends AsyncTask<Foo, Foo, Foo>
{
private static boolean bDiscardButtonAction = false;
private boolean isDiscareded = false;
@Override
public void onPreExecute()
{
if(bDiscardButtonAction)
{
isDiscareded = true;
return;
}
bDiscardButtonAction = true;
}
@Override
public Foo doInBackground(Foo... params)
{
if(isDiscareded) return;
// ...
}
@Override
public void onPostExecute(Void result)
{
if(!isDiscareded) bDiscardButtonAction = false;
}
@Override
public void onCancelled(Foo result)
{
if(!isDiscareded) bDiscardButtonAction = false;
}
}
关于java - Android AsyncTask 运行多次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25863256/