Fea*_*hal 5 android android-asynctask
我一直在使用异步任务来访问Web服务器并使用结果更新控件.这有缺点,即它使异步方法特定于控制并使我再次使用返回的字符串.
如何从异步调用onPostExecute返回结果字符串?我怎么称呼它?我似乎无法让我的代码能够做到这一点.线程应该没有问题,因为我有一个冻结UI的对话框,直到完成工作.
我的典型asyncTask代码如下
class GetDataFromServer extends AsyncTask<String, String, String>
{
* */
// Progress Dialog
private ProgressDialog qDialog;
private Context context;
private String dialogString;
private ArrayList<String[]> newLoginResult;
// JSON parser class
String url_newGame ="http://xxxxxx.php";
public myAsyncMethos(String dialogMessage, Context con)
{
this.qDialog = new ProgressDialog(con);
this.dialogString = dialogMessage;
this.context = con;
}
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute()
{
super.onPreExecute();
qDialog = new ProgressDialog(this.context);
qDialog.setMessage(this.dialogString);
qDialog.setIndeterminate(false);
qDialog.setCancelable(false);
qDialog.show();
}
@Override
protected JSONObject doInBackground(String... args)
{
//MAKE SERVER CALL and cast to JSONOBject
return jsonNewUser;
}
public void onPostExecute(JSONObject jsonString)
{
// dismiss the dialog after getting response
qDialog.dismiss();
//I WANT TO RETURN A STRING HERE BUT KEEP GETTING SYNTAX ERRORS BEFORE RUNTIME
}
}
Run Code Online (Sandbox Code Playgroud)
我个人会向您的类添加一个回调,然后一旦onPostExecute运行,就向主类上的侦听器触发回调。
class GetDataFromServer extends AsyncTask<String, String,JSONObject>
{
// Progress Dialog
private ProgressDialog qDialog;
private Context context;
private String dialogString;
private ArrayList<String[]> newLoginResult;
private InformComplete myCallback;
public GetDataFromServer(String dialogMessage, Context con,InformComplete callback)
{
this.qDialog = new ProgressDialog(con);
this.dialogString = dialogMessage;
this.context = con;
this.myCallback=callback;
}
@Override
protected void onPreExecute()
{
// set up your dialog
}
@Override
protected JSONObject doInBackground(String... args)
{
JSONObject jsonNewUser=new JSONObject();
return jsonNewUser;
}
public void onPostExecute(JSONObject jsonString)
{
qDialog.dismiss();
myCallback.PostData(jsonString);
}
public interface InformComplete
{
public void PostData(JSONObject result);
}
}
Run Code Online (Sandbox Code Playgroud)
然后从你的调用类中,你会得到这样的东西......
private void callTheAsyncThing
{
GetDataFromServer gds=new GetDataFromServer("please wait", this, letMeKnow);
gds.execute(params);
}
private InformComplete letMeKnow=new InformComplete()
{
public void PostData(JSONObject result)
{
// we now have the data in the calling class
}
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1147 次 |
| 最近记录: |