我正在尝试使用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
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);
}
});
Run Code Online (Sandbox Code Playgroud)
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 = …Run Code Online (Sandbox Code Playgroud) 我想要做的是:我希望我的应用程序从Internet下载图像并将其保存到手机的内部存储器中,该位置是应用程序专用的位置.如果列表项没有可用的图像(即无法在Internet上找到),我想要显示默认的占位符图像.这是我在list_item_row.xml文件中定义的默认图像.
在我的ListActivity文件中,我正在调用我编写的CustomCursorAdapter类的实例.它在CustomCursorAdapter中,我遍历所有列表项并定义需要映射到视图的内容,包括尝试从内部存储器读取它的图像文件.
我已经看到了关于这个主题的几个问题,但这些例子要么特定于外部手机内存(例如SDCard),涉及保存字符串而不是图像,要么涉及使用Bitmap.CompressFormat来降低文件的分辨率(这是不必要的)我的情况,因为这些图像将是已经很小分辨率的小缩略图).试图将每个示例中的代码拼凑起来一直很困难,因此我询问了我的具体示例.
目前,我相信我已经编写了有效的代码,但没有显示我的列表项的图像,包括默认的占位符图像.我不知道问题是由无效的下载/保存代码或无效的读取代码引起的 - 我不知道如何检查内部存储器以查看图像是否存在.
无论如何,这是我的代码.任何帮助将不胜感激.
ProductUtils.java
public static String productLookup(String productID, Context c) throws IOException {
URL url = new URL("http://www.samplewebsite.com/" + productID + ".jpg");
URLConnection connection = url.openConnection();
InputStream input = connection.getInputStream();
FileOutputStream output =
c.openFileOutput(productID + "-thumbnail.jpg", Context.MODE_PRIVATE);
byte[] data = new byte[1024];
output.write(data);
output.flush();
output.close();
input.close();
}
Run Code Online (Sandbox Code Playgroud)
CustomCursorAdapter.java
public class CustomCursorAdapter extends CursorAdapter {
public CustomCursorAdapter(Context context, Cursor c) {
super(context, c);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
ImageView thumbnail …Run Code Online (Sandbox Code Playgroud)