[英]Android AsyncTask runs multiple times
In my app ,there is an one button which get input from database.When I press it more than one in a short time it crashes . 在我的应用程序中,有一个按钮可以从数据库中获取输入。当我在短时间内按下多个 按钮时,它会崩溃 。 How can i avoid this error with using asynctask ?
如何使用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")));
}
thanks... 谢谢...
You can create a boolean flag (let's say bDiscardButtonAction
), and set it to true
in onPreExecute()
and set it to false
in onPostExecute()
, something like: 您可以创建一个布尔标志(比方说
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;
}
}
disable the show
button
in onPreExecute()
and enable it back onPostExecute()
. 禁用
onPreExecute()
的show
button
,并将其启用回onPostExecute()
。
public class getAsyncDataTask extends AsyncTask<Void, Void, Void>
{
@Override
public void onPreExecute()
{
show.setAlpha(0.5);
show.setEnable(false);
}
@Override
public void doInBackground(Void... params)
{
//retrieve the data from db;
}
@Override
public void onPostExecute()
{
show.setAlpha(1.0);
show.setEnable(true);
}
}
I hope this code will help u out. 我希望这段代码能对您有所帮助。
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
new AsynchTaskManualLocation().execute();
});
public class AsynchTaskGetData extends AsyncTask<String,Void,String>
{
@Override
protected String doInBackground(String... url) {
//showinf(); this method contains operation of getting data from //database OR ur logic to getdata
return showinf();
}
@Override
protected void onPostExecute(String result) {
//here u get result in resul var and process the result here
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.