如何在 BaseAdapter class 中更新异步任务的 imageView 源 onPostResult

How to update an imageView source onPostResult of async task in BaseAdapter class

我想在 OnPostExecute 方法 async 方法

中下载后更新图像查看源

这是我的基本适配器的 getView 方法 class

public View getView(int position, View convertView, ViewGroup parent) {
    vi = convertView;
    ViewHolder holder;
    if(convertView==null){

        /****** Inflate tabitem.xml file for each row ( Defined below ) *******/
        vi = inflater.inflate(R.layout.activity_single_message, null);
        /****** View Holder Object to contain tabitem.xml file elements ******/

        holder = new ViewHolder();
        holder.chatText = (TextView) vi.findViewById(R.id.singleMessage);
        holder.imageView=(ImageView)vi.findViewById(R.id.image);
        holder.videoIcon=(ImageView)vi.findViewById(R.id.video_icon);
        holder.singleMessageContainer=(LinearLayout)vi.findViewById(R.id.singleMessageContainer);
        holder.singleMessageImageContainer=(LinearLayout)vi.findViewById(R.id.singleMessageImageContainer);
        holder.dwnld_btn = (Button)vi.findViewById(R.id.download_btn);

        /************  Set holder with LayoutInflater ************/
        vi.setTag( holder );
    }
    else
        holder=(ViewHolder)vi.getTag();

    if(data.size()<=0)
    {
        holder.chatText.setText("Start new conversation!");


    }
    else
    {
        /***** Get each Model object from Arraylist ********/
        tempValues=null;
        tempValues = (ChatMessage) data.get(position);
        //Toast.makeText(activity, "MimeType = " + tempValues.getMessageText(), Toast.LENGTH_LONG).show();
        String path = tempValues.getMediaURL();
        String mediaMIMEType = tempValues.getMediaMIMEType();
        int isDownload = tempValues.getIsDownloaded();
        String senderUserInfoId = tempValues.getSenderUserInfoId();

if(!tempValues.getSenderUserInfoId().equals(loginUserInfoId) && mediaMIMEType.contains("IMAGE"))
        {
            holder.chatText.setPadding(30,10,10,10);
            holder.chatText.setMaxWidth(550);
            holder.chatText.setBackgroundResource(R.drawable.chat_rightpng);
            holder.chatText.setTextColor(Color.parseColor("#FFFFFF"));//.setTextColor(R.color.white);
            holder.chatText.setText(tempValues.getMessageText());

            holder.singleMessageContainer.setGravity(true ? Gravity.LEFT : Gravity.RIGHT);

            try {
                holder.imageView.setVisibility(View.VISIBLE);
                holder.videoIcon.setVisibility(View.GONE);

                if(isDownload == 0) {
                    holder.dwnld_btn.setVisibility(View.VISIBLE);

                    holder.imageView.setPadding(10,10,10,10);
                    holder.imageView.setMaxWidth(450);
                    holder.imageView.setBackgroundColor(Color.parseColor("#005684"));
                    holder.imageView.setImageResource(R.drawable.blur);
                }
                else {
                    holder.dwnld_btn.setVisibility(View.GONE);

                    holder.imageView.setPadding(10,10,10,10);
                    holder.imageView.setMaxWidth(450);
                    holder.imageView.setMaxWidth(550);
                    holder.imageView.setBackgroundColor(Color.parseColor("#005684"));
                    holder.imageView.setImageDrawable(Drawable.createFromPath(path));
                }

                holder.singleMessageImageContainer.setGravity(true ? Gravity.LEFT : Gravity.RIGHT);
            } catch(Exception e) {
                //txtUrl.setText("Error: Exception");
            }
        }


            } catch(Exception e) {
                //txtUrl.setText("Error: Exception");
            }
        }

        /******** Set Item Click Listner for LayoutInflater for each row *******/
        holder.dwnld_btn.setOnClickListener(new OnDownloadBtnClickListener(position));
    }
    return vi;
}

这是我点击下载按钮时的点击功能

private class OnDownloadBtnClickListener  implements View.OnClickListener {
    private int mPosition;

    OnDownloadBtnClickListener(int position){
        mPosition = position;
    }

    @Override
    public void onClick(View arg0) {
        final ChatMessage val = ( ChatMessage ) data.get(mPosition);
        if(isInternetOn()) {
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
            downlodedMsgId = val.getId();
            if (val.getMediaMIMEType().contains("IMAGE")) {
                localFileURL = Environment.getExternalStorageDirectory() + File.separator + "/Planetskool/Media/Images/IMG_" + timeStamp + ".png";

                new DownloadFileFromURL().execute(val.getOnlineMediaURL());

        }
    }
}

这是 async 下载文件的方法,其中 OnPostExecute 我想更改 imageview

的来源
class DownloadFileFromURL extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread
     * Show Progress Bar Dialog
     * */
    @Override
    protected void onPreExecute() {
        progressDialog = new ProgressDialog(activity);
        progressDialog.setMessage("Downloading file. Please wait...");
        progressDialog.setIndeterminate(false);
        progressDialog.setMax(100);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setCancelable(true);
        progressDialog.show();
        super.onPreExecute();
    }

    /**
     * Downloading file in background thread
     * */
    @Override
    protected String doInBackground(String... f_url) {
        int count;
        try {
            URL url = new URL(f_url[0]);
            URLConnection conection = url.openConnection();
            conection.connect();
            // getting file length
            int lenghtOfFile = conection.getContentLength();

            // input stream to read file - with 8k buffer
            InputStream input = new BufferedInputStream(url.openStream(), 8192);

            // Output stream to write file
            OutputStream output = new FileOutputStream(localFileURL);

            byte data[] = new byte[1024];

            long total = 0;

            while ((count = input.read(data)) != -1) {
                total += count;
                // publishing the progress....
                // After this onProgressUpdate will be called
                publishProgress(""+(int)((total*100)/lenghtOfFile));

                // writing data to file
                output.write(data, 0, count);
            }

            // flushing output
            output.flush();

            // closing streams
            output.close();
            input.close();

        } catch (Exception e) {
            Log.e("Error: ", e.getMessage());
        }

        return null;
    }

    /**
     * Updating progress bar
     * */
    protected void onProgressUpdate(String... progress) {
        progressDialog.setProgress(Integer.parseInt(progress[0]));
    }

    /**
     * After completing background task
     * Dismiss the progress dialog
     * **/
    @Override
    protected void onPostExecute(String file_url) {
        db.updateDownlodedPath(downlodedMsgId, localFileURL);
        updateResults(data);
        localFileURL = "";
        downlodedMsgId = 0;
        progressDialog.dismiss();
    }

}

首先你必须检查你想要显示图像的位置是否在你的列表视图中可见,如果可见则更新它或者将它保存在你想要的任何首选位置(文件或 Lrucache )。

查看位置是否可见的方法如下

public synchronized void onThumbnailReceived(Bitmap thumnail, String path) {
    if(listview!= null)
    {
    final int numVisibleChildren = listview.getChildCount();
    final int firstVisiblePosition = listiew
            .getFirstVisiblePosition();

    for (int i = firstVisiblePosition; i < firstVisiblePosition + numVisibleChildren; i++) {

        if (data.get(i).get(IMAGEPATH).toString()
                .equals(path)) {
            View view = listview.getChildAt(i - firstVisiblePosition);
            getView(i, view, null);
        }
    }
    }
}

将您的 clickListner 更改为

@Override
    public void onClick(View arg0) {
        final ChatMessage val = ( ChatMessage ) data.get(mPosition);
        if(isInternetOn()) {
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
            downlodedMsgId = val.getId();
            if (val.getMediaMIMEType().contains("IMAGE")) {
                localFileURL = Environment.getExternalStorageDirectory() + File.separator + "/Planetskool/Media/Images/IMG_" + timeStamp + ".png";

                new DownloadFileFromURL(position).execute(val.getOnlineMediaURL());

        }
    }

并在 AsyncTask 中创建构造函数

 class DownloadFileFromURL(int mPosition){
         //get your imageViewByPosition here and change the url in OnPostExecute Method
}