Android:使用 AsyncClass 对象数组创建 ListView 适配器



>我需要存储几个不同的变量,然后将它们作为数组发送到ListViewAdapter,以便我可以创建自定义行。但是,由于来自 Array 的对象使用AsyncTask因为我正在使用JSoup并访问 Internet,因此在将自定义视图返回到主类之前,我需要一种方法在自定义适配器中检索这些变量。代码如下:

列表视图适配器代码:

public class CustomAdapter extends ArrayAdapter<getProductAttributes> implements OnCallCompleteCallBack{
String title;
String price;
Bitmap image;
//ArrayAdapter needs constructor, second parameter gets the layout for the list, third parameter is the array itself. "Context" always means background information.
CustomAdapter(Context context, getProductAttributes[]items){
super(context,R.layout.custom_row, items);
}
public void onCallComplete(int listSize, String title, String price, String imageSRC, String productURL){
this.title=title;
this.price = price;
//Get Bitmap for image
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(imageSRC).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
this.image=mIcon11;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(getContext());
//One custom view is going to be equal to one row
View customView = inflater.inflate(R.layout.custom_row,parent,false);
ImageView productImage = (ImageView)customView.findViewById(R.id.imageView);
TextView itemTitle = (TextView)customView.findViewById(R.id.itemTitle);
TextView itemPrice = (TextView)customView.findViewById(R.id.itemPrice);
productImage.setImageBitmap(image);
itemTitle.setText(title);
itemPrice.setText(price);
return customView;
}

}

扩展 AsyncTask 的 getProductAttributes 类:

public class getProductAttributes extends AsyncTask<Object, Object, Void> {
OnCallCompleteCallBack callback;
String url;
int index;
String productURL;
private String price;
private String title;
private String imageSRC;
ImageView productView;
int listSize;
int result;
public getProductAttributes(String url, int index, OnCallCompleteCallBack callback) {
this.url = url;
this.index = index;
this.callback = callback;
}
protected Void doInBackground(Object... voids) {
try{ 
(code that gets all of the attributes, I'm sure that this code is working fine)
}catch(Exception e){}
return null;
}
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (callback != null) {
callback.onCallComplete(listSize,title,price,imageSRC,productURL);
}
}

我认为问题似乎是当我在CustomAdapter中运行onCallComplete时,自定义视图已经返回。如果是这种情况,我该怎么做才能规避呢?

感谢您的时间和帮助!

你永远不会调用下面的构造函数:

public getProductAttributes(String url, int index, OnCallCompleteCallBack callback) {
this.url = url;
this.index = index;
this.callback = callback;
}

为了让侦听器对象工作,您必须设置callback对象。 也不要在班级的第一个字母以小写字母开头。

相关内容

  • 没有找到相关文章

最新更新