我正在尝试使用一个扩展了AsyncTask的类来处理连接到URL、解析JSON、在解析期间显示一个不确定的ProgressDialog,并将结果作为键值对存储在HashMap中返回给主Activity。然后,主Activity将读取HashMap的结果并将其放入表单字段中。然而,即使我在我的AsyncTask中填充了HashMap(通过println语句证明),调用主Activity中返回HashMap的方法仍然得到空结果。我无法确定这是我做错了什么,还是我误解了AsyncTask的功能。
我正在考虑将扩展了AsyncTask的类转换为一个Activity。基本上,在这个数据搜索/解析过程中,用户不应该能做任何其他事情,并且应该等待ProgressDialog消失后才能与应用程序交互(或通过按下返回按钮)。此外,我的应用程序需要能够处理AsyncTask中捕获异常的某些情况(无法连接到URL、错误的JSON、要搜索的产品ID找不到),并为这些异常量身定制错误对话框。如果这个类是一个Activity,我可以在调用finish()时发送不同的结果代码,具体取决于是否捕获到异常。
再次强调,我不确定AsyncTask是否是最佳解决方案,因为当收集和解析信息时,用户将不会做任何其他事情。请告诉我是否新建一个Activity会有意义,或者我只是在搞砸后台线程的实现。
MainActivity.java
我正在考虑将扩展了AsyncTask的类转换为一个Activity。基本上,在这个数据搜索/解析过程中,用户不应该能做任何其他事情,并且应该等待ProgressDialog消失后才能与应用程序交互(或通过按下返回按钮)。此外,我的应用程序需要能够处理AsyncTask中捕获异常的某些情况(无法连接到URL、错误的JSON、要搜索的产品ID找不到),并为这些异常量身定制错误对话框。如果这个类是一个Activity,我可以在调用finish()时发送不同的结果代码,具体取决于是否捕获到异常。
再次强调,我不确定AsyncTask是否是最佳解决方案,因为当收集和解析信息时,用户将不会做任何其他事情。请告诉我是否新建一个Activity会有意义,或者我只是在搞砸后台线程的实现。
MainActivity.java
mInitiateProductLookupButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ProductLookup pl = new ProductLookup(id, MainActivity.this);
pl.execute();
// The below variable is always empty!
HashMap<String, String> productInfo = pl.getProductInfo();
applyProductInfoToFormFields(productInfo);
}
});
ProductLookup.java
public class ProductLookup extends AsyncTask<Object, Void, HashMap<String, String>> {
private String mProductID;
private Context mContext;
HashMap<String, String> mProductInfo;
ProgressDialog mDialog;
public ProductLookup(String id, Context applicationContext) {
mProductID = id;
mContext = applicationContext;
mProductInfo = new HashMap<String, String>();
}
@Override
protected void onPreExecute() {
mDialog = new ProgressDialog(mContext);
mDialog.setMessage("Loading product info. Please wait...");
mDialog.setIndeterminate(true);
mDialog.setCancelable(false);
mDialog.show();
}
@Override
protected void onPostExecute(HashMap<String, String> result){
super.onPostExecute(result);
mDialog.dismiss();
mProductInfo = result;
}
@Override
protected HashMap<String, String> doInBackground(Object... params) {
try {
// Connect to URL, parse JSON, and add key-value pairs to mProductInfo...
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
finally {
try {
// Close input/output reader variables
} catch (IOException e) {
e.printStackTrace();
}
}
return mProductInfo;
}
public HashMap<String, String> getProductInfo(){
return this.mProductInfo;
}
}
setProductInfo(result)
的区别。setProductInfo
也可以是子类中的一个方法。 - Pentium10