在我的应用中,有一个按钮从数据库获取输入。当我在短时间内按 一个崩溃。 如何使用 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")));
}
感谢...
答案 0 :(得分:3)
您可以创建一个布尔标志(让我们说bDiscardButtonAction
),并将其设置为true
中的onPreExecute()
并将其设置为false
onPostExecute()
1}},类似于:
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;
}
}
答案 1 :(得分:1)
停用show
中的button
onPreExecute()
并将其重新启用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);
}
}
答案 2 :(得分:0)
我希望这段代码可以帮助你。
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
}
}
}