gpt4 book ai didi

android - 是否可以从 AsyncTask 内部调用另一个函数?

转载 作者:行者123 更新时间:2023-11-29 18:21:28 25 4
gpt4 key购买 nike

我有一个从服务器检索数据的 AsyncTask。我需要的是在对话框中显示检索到的数据。如何调用该函数以从 AsyncTask 中创建对话框?如果我做不到,那我有什么选择?是否可以知道 AsyncTask 是否已完成?

这是我的代码:

//Function calling the AsyncTask
public void getData(int pos)
{
new DBTask().execute();
//Is it possible to know here if the AsyncTask has ended or not??
}

private class DBTask extends AsyncTask<Long, Boolean, Integer>{
ProgressDialog ServerPD = new ProgressDialog(MRRankingActivity.this);

@Override
protected void onPreExecute()
{
ServerPD = ProgressDialog.show (MRRankingActivity.this, "", "Connecting to server...", true, false);
}//End of onPreExecute

@Override
protected Integer doInBackground(Long... params)
{
publishProgress(isOnline());

if(isOnline())
{
getDBData();
if(isOK)
{
//I want to show the result by calling this function..
showResult();
//Calling this function will trow error..So how can i show my result??
Log.d("LIST","DONE..Reached Final Destination");

}
}
}

return null;
}

@Override
protected void onProgressUpdate(Boolean... isConnection) {
// TODO Auto-generated method stub

super.onProgressUpdate(isConnection);
if(isOnline())
{
ServerPD.setMessage("Retreving Data");
}
}

@Override
protected void onPostExecute(Integer result) {
if (ServerPD.isShowing())
{
ServerPD.dismiss();
}


}//End of onPostExecute
}//End of DBTask

public void getDBData()
{

try{
//Code foe connecting to database and retreive data.
//If everything is ok then isOK is set to True..
//else its set to false

isOK=true;
}
catch(Exception e)
{
isOK=false;
}//End if catch
}

public void showResult()
{
//I want to show result here in a new Dialog ...
}

//Checking is connection available
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}

在这种情况下如何显示结果?有什么方法可以判断 AsyncTask 是否已经结束?

最佳答案

简化 Mathew 建议的内容..只需像这样修改您的代码首先通过初始化一个 int 变量 isSuccess 来修改 doInBackgroud,然后在 isOK if 语句中将 isSucces 的值更改为 1。现在返回 isSuccess.like this

 @Override
protected Integer doInBackground(Long... params)
{
int isSuccess=0;
publishProgress(isOnline());

if(isOnline())
{

getDBData();
if(isOK)
{
isSuccess=1;
}
}
}

return isSuccess;
}

现在修改您的 PostExecute() 以处理在 onPostExecute 中返回的 isSuccess 值

@Override
protected void onPostExecute(Integer result) {
if (ServerPD.isShowing())
{
ServerPD.dismiss();
}
if(result==1)
{
showResult();
}

}//End of onPostExecute

希望这对您有所帮助。

关于android - 是否可以从 AsyncTask 内部调用另一个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5150258/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com