将onPostExecute值返回到RecyclerAdapter的onBindViewHolder

时间:2017-04-09 16:38:04

标签: java android android-asynctask android-recyclerview

我有聊天屏幕,我从FirebaeStorage下载附件。 我有各种格式的文件,可以发送doc,pdf,apk等,每个我有相同的TextViews和ImageViews。

在聊天屏幕的recyclerview适配器中,我设置了本地存储的文件路径,可以通过运行AsyncTask从Firebase存储下载文件并返回文件路径来获取。这个工作完美但问题是如何找回onBindViewHolder上的文件路径,否则为

这是我的RecyclerAdapter,我调用AsyncTask并将结果返回到相同的范围,等待下载完成然后根据返回的数据设置视图

public void onBindViewHolder(final Chat_Adapter.ViewHolder holder, int position) {


if (fileType.equals("pdf")){
 new DownloadFileFromFS(Download_URL,FileName+".pdf").execute();

//HERE I NEED THE RESULT FROM ASYNCTASK AND WAIT TILL DOWNLOAD COMPLETES
 //THEN SET THE VIEWS WITH RETURN RESULT FROM ASYNCTASK

    if (DownloadFilePath!=null){
        File file=new File(DownloadFilePath);
        long sizeFile=file.length()/1024; //In KB
        holder.Doc_FileName.setText(DownloadFilePath);
        holder.Doc_FileSize.setText(String.valueOf(sizeFile));
    }
    else {
        Log.d(TAG,"DOWNLOAD FILE PATH IS NULL");
    }

}

AsyncTask

public class DownloadAttachment extends AsyncTask<Void, String, String> {
    String DownloadUrl,fileName;
    File file;
    Context context;
    ProgressBar progressBar;
    public static final String TAG="###Download Attachment";

    public DownloadAttachment(Context context, String downloadUrl, String fileName) {
        DownloadUrl = downloadUrl;
        this.fileName = fileName;
        this.context=context;
    }


    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
    }

    @Override
    protected String doInBackground(Void... params) {
        int count;
        try {
            File root = android.os.Environment.getExternalStorageDirectory();

            Log.d(TAG,"DO IN BACKGROUND RUNNING");
            File dir = new File(root.getAbsolutePath() + "/Downloaded Files/");
            if (dir.exists() == false) {
                dir.mkdirs();
            }


            URL url = new URL(DownloadUrl); //you can write here any link
            file = new File(dir, fileName);

            long startTime = System.currentTimeMillis();
            Log.d(TAG, "download begining");
            Log.d(TAG, "download url:" + url);
            Log.d(TAG, "downloaded file name:" + fileName);

       /* Open a connection to that URL. */
            URLConnection ucon = url.openConnection();

            //this will be useful so that you can show a typical 0-100% progress bar
            int lengthOfFile=ucon.getContentLength();
       /*
        * Define InputStreams to read from the URLConnection.
        */
            InputStream is = ucon.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);

       /*
        * Read bytes to the Buffer until there is nothing more to read(-1).
        */
            ByteArrayOutputStream baf = new ByteArrayOutputStream(5000);
            int current = 0;
            long total=0;
            while ((current = bis.read()) != -1) {
                baf.write((byte) current);
                total=total+current;
                //PUBLISH THE PROGRESS
                //AFTER THIS onProgressUpdate will be called
                publishProgress(""+(int)(total*100)/lengthOfFile);
            }


       /* Convert the Bytes read to a String. */
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(baf.toByteArray());
            fos.flush();
            fos.close();
            Log.d("DownloadManager", "download ready in " + ((System.currentTimeMillis() - startTime) / 1000) + " sec");
            Log.d(TAG,"File Path "+file);

        } catch (IOException e) {
            Log.d("DownloadManager", "Error: " + e);
        }

        return file.toString();
    }    

}

更新正如@Atef Hares建议的那样,我确实在code.its中实现了正常工作但如果我有不同的格式会怎么样。如何在从asynctask cuz代码获得结果后调用特殊if else建议只调用pdf if语句。

if (fileType.equals("pdf")){
    final String nameFile=UUID.randomUUID().toString();
    new DownloadFileFromFS(chat_wrapper.getDocuments(),nameFile).execute();

     filePathInterface=new FilePath() {
        @Override
        public void LocalFilePath(final String Path) {
           //HERE I AM GETTING RESULT FROM ASYNCTASK
           //AND SETTING VIEWS ACCORDING TO IT            
        }
    };


}
else if (fileType.equals("doc")){
//HOW TO GET RESULT FROM ASYNCTASK HERE IF FILETYPE IS "doc"

}
else if (fileType.equals("ppt")){
//HOW TO GET RESULT FROM ASYNCTASK HERE IF FILETYPE IS "ppt"
}

2 个答案:

答案 0 :(得分:1)

好的,使用接口 - 您知道 - 将实现您的需求!

就这样做:

public interface AsyncTaskCallback {
    void onSuccess (String filePath);
}

并且在适配器中,除非从asyncTask获取数据,否则不要向视图设置任何数据,如下所示:

public void onBindViewHolder(final Chat_Adapter.ViewHolder holder, int position) {

         //Initialize filetype here

        new DownloadFileFromFS(Download_URL, FileName + "."+ filetype, new AsyncTaskCallback() {
            @Override
            public void onSuccess(String filePath) {
                //HERE I NEED THE RESULT FROM ASYNCTASK AND WAIT TILL DOWNLOAD COMPLETES
                //THEN SET THE VIEWS WITH RETURN RESULT FROM ASYNCTASK

                if (filePath != null) {
                    File file = new File(filePath);
                    long sizeFile = file.length() / 1024; //In KB
                    holder.Doc_FileName.setText(filePath);
                    holder.Doc_FileSize.setText(String.valueOf(sizeFile));
                } else {
                    Log.d(TAG, "DOWNLOAD FILE PATH IS NULL");
                }
            }
        }).execute();
    }

答案 1 :(得分:0)

您可以使用回调。

public interface FileDownloadCallback {
    void onSuccess (String filePath);
    void onFailed ();

}

将其传递给AsyncTask并从onPostExecute调用它。