等待一个字符串返回值
问题描述:
我试图用HttpManager从URL等待一个字符串返回值
public String request(Context context, String url){
page_requested = "empty";
HttpQuery query = new HttpQuery(context, mHttpClient);
query.execute(url);
return page_requested;
}
检索字符串,并用它在MainActivity
public void onClick(View v) {
Toast.makeText(MainActivity.this, HttpManager.getInstance().request(MainActivity.this, "http://myurl"), Toast.LENGTH_SHORT).show();
}
但public String request
不等待查询被执行并返回“空”,但如果我等待10秒显示吐司,它会返回正确的值。
显示期望值的最佳方式是什么?
答
使用AsyncTask显示您的文本。我认为这将是一种有效的方法..您可以在加载操作时显示您的进度条。
public class DisplayString extends AsyncTask<Void, Void, Void>
{
@Override
protected void onPreExecute()
{
super.onPreExecute();
dialog.setMessage("Please wait...");
dialog.setCancelable(false);
dialog.show();
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
// Things to be done while execution of long running operation is in progress. For example updating ProgessDialog
}
@Override
protected void onPostExecute(Void result)
{
//Post Execute
dialog.cancel();
//Display your string here
}
@Override
protected Void doInBackground(Void... params) {
// Your operation..Dont Edit Any Views here
return null;
}
}
希望它可以帮助