下载文件后更改了listview项目按钮

时间:2016-05-28 09:09:01

标签: android listview

我在这个项目中创建了一个项目,我下载了完美的PDF文件表单服务器。

这是我的用户界面

enter image description here

但我想要的是在下载文件后更改按钮的图标。然后使用此按钮打开下载的PDf文件。

请帮帮我

UserCustomAdapter.java

import java.io.File;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class UserCustomAdapter extends ArrayAdapter<User> {
    Context context;
    int layoutResourceId;
    ArrayList<User> data = new ArrayList<User>();
    static View row;
    static DownloadTask downloadTask;

    public UserCustomAdapter(Context context, int layoutResourceId,
                             ArrayList<User> data) {
        super(context, layoutResourceId, data);
        this.layoutResourceId = layoutResourceId;
        this.context = context;
        this.data = data;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        row = convertView;
        UserHolder holder = null;

        if (row == null) {
            LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            row = inflater.inflate(layoutResourceId, parent, false);
            holder = new UserHolder();
            holder.tv_paper_name = (TextView) row.findViewById(R.id.tv_paper_name);
//            holder.tv_paper_desc = (TextView) row.findViewById(R.id.tv_paper_desc);
            holder.bt_download = (Button) row.findViewById(R.id.bt_download);
            row.setTag(holder);
        } else {
            holder = (UserHolder) row.getTag();
        }
        User user = data.get(position);
        holder.tv_paper_name.setText(user.getName());
//        holder.tv_paper_desc.setText(user.getAddress());
//        holder.textLocation.setText(user.getLocation());
        final UserHolder finalHolder = holder;

        holder.bt_download.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Log.i("Download Button Clicked", "**********");
//                Toast.makeText(context, "Download  "+ finalHolder.tv_paper_name.getText().toString()+"  " + position,
//                        Toast.LENGTH_LONG).show();
                File extStore = Environment.getExternalStorageDirectory();
                File myFile = new File(extStore.getAbsolutePath() + "/Exam Papers/"+finalHolder.tv_paper_name.getText().toString()+".pdf");

                if (!myFile.exists()) {

                    // execute this when the downloader must be fired
                    downloadTask = new DownloadTask(context);
                  /*  downloadTask.execute("http://ia.tranetech.ae:82/upload/uploads/five-point-someone-chetan-bhagat_ebook.pdf",""+finalHolder.tv_paper_name.getText().toString()+".pdf");*/
                    downloadTask.execute("https://letuscsolutions.files.wordpress.com/2015/07/five-point-someone-chetan-bhagat_ebook.pdf",""+finalHolder.tv_paper_name.getText().toString()+".pdf");


                } else {

                    Toast.makeText(context, "File already Exists in "+myFile, Toast.LENGTH_SHORT).show();
                }

            }
        });
        return row;
    }

    static class UserHolder {
        TextView tv_paper_name;
//        TextView tv_paper_desc;
        Button bt_download;
    }
}

DownloadTask.java

    public class DownloadTask extends AsyncTask<String, Integer, String> {

    Context context;
    private PowerManager.WakeLock mWakeLock;
    ProgressDialog mProgressDialog;
    private static final int MEGABYTE = 1024 * 1024;
    DownloadTask downloadTask;
    String Name;

    public DownloadTask(Context context) {
        this.context = context;
    }


    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // take CPU lock to prevent CPU from going off if the user
        // presses the power button during download
        // instantiate it within the onCreate method
        mProgressDialog = new ProgressDialog(context);
        mProgressDialog.setMessage("Downloading....");
        mProgressDialog.setIndeterminate(true);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog.setCancelable(true);
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                getClass().getName());
        mWakeLock.acquire();
        mProgressDialog.show();

        mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {

                String sdcard_path = Environment.getExternalStorageDirectory().getPath();
                File file = new File(sdcard_path + "/Exam Papers/"+Name+".pdf");
                file.delete();

                Toast.makeText(context, "Download In Background", Toast.LENGTH_SHORT).show();
            }
        });

    }


    @Override
    protected String doInBackground(String... str) {

        String URL = str[0];
        Name = str[1];
        InputStream input = null;
        OutputStream output = null;
        HttpURLConnection connection = null;
        try {
            URL url = new URL(URL);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();

            // expect HTTP 200 OK, so we don't mistakenly save error report
            // instead of the file
            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                return "Server returned HTTP " + connection.getResponseCode()
                        + " " + connection.getResponseMessage();
            }

            // this will be useful to display download percentage
            // might be -1: server did not report the length
            int fileLength = connection.getContentLength();

            // download the file
            input = connection.getInputStream();

            String sdcard_path = Environment.getExternalStorageDirectory().getPath();
            Log.d("Path ------ ", " " + sdcard_path);
            // create a File object for the parent directory
            File PapersDiractory = new File(sdcard_path + "/Exam Papers/");
            // have the object build the directory structure, if needed.
            PapersDiractory.mkdirs();
            // create a File object for the output file
            File outputFile = new File(PapersDiractory, ""+Name);
            // now attach the OutputStream to the file object, instead of a String representation
            output = new FileOutputStream(outputFile);
//                 output = new FileOutputStream(Environment.getExternalStorageDirectory().getPath() + "/five-point-someone-chetan-bhagat_ebook.pdf");

            byte data[] = new byte[MEGABYTE];
            long total = 0;
            int count;
            while ((count = input.read(data)) != -1) {
                // allow canceling with back button
                if (isCancelled()) {
                    input.close();
                    return null;
                }
                total += count;
                // publishing the progress....
                if (fileLength > 0) // only if total length is known
                    publishProgress((int) (total * 100 / fileLength));
                int progress= (int) (total * 100 / fileLength);
                Log.d("Progress = ", "" + (int) (total * 100 / fileLength));
                output.write(data, 0, count);
            }
        } catch (Exception e) {
            return e.toString();
        } finally {
            try {
                if (output != null)
                    output.close();
                if (input != null)
                    input.close();
            } catch (IOException ignored) {
            }

            if (connection != null)
                connection.disconnect();
        }
        return null;
    }

    @Override
    protected void onProgressUpdate(Integer... progress) {
        super.onProgressUpdate(progress);
        // if we get here, length is known, now set indeterminate to false
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.setMax(100);
        mProgressDialog.setProgress(progress[0]);
    }

    @Override
    protected void onPostExecute(String result) {
        mWakeLock.release();
        mProgressDialog.dismiss();
        if (result != null)
            Toast.makeText(context, "Download error: " + result, Toast.LENGTH_LONG).show();
        else
            Toast.makeText(context, "File downloaded", Toast.LENGTH_SHORT).show();
    }

}

3 个答案:

答案 0 :(得分:2)

您可以修改getView()方法。尝试执行以下步骤。 1.首先,从本地文件夹中获取所有下载的PDF。 2.将获取的列表传递给适配器。 3.在get view方法中膨胀并创建视图时,首先尝试将当前名称与下载的文件名匹配。 4.如果已下载当前文件,则更改下载按钮以打开按钮。并且,如果之前没有下载,则只显示下载按钮。 当你重新打开应用程序时,你会得到你想要的输出。

对于您的情况,例如下载完成时,只需尝试执行notifySetDataChanged。它将根据上述模式自动重新创建列表视图。 希望你理解。:)

答案 1 :(得分:1)

只需使用DownloadManager ,请参阅下面的代码。

                String sdcard_path = Environment.getExternalStorageDirectory().getPath();
                DownloadManager downloadManager = (DownloadManager) activity
                                .getSystemService((Service.DOWNLOAD_SERVICE));
                Uri Download_Uri = Uri.parse("https://letuscsolutions.files.wordpress.com/2015/07/five-point-someone-chetan-bhagat_ebook.pdf");
                DownloadManager.Request request = new DownloadManager.Request(Download_Uri);
                request.setAllowedNetworkTypes(
                                DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
                request.setAllowedOverRoaming(true);
                request.setTitle("Download PDF");
                request.setDescription("Downloading book..");
                request.setDestinationInExternalPublicDir("/Exam Papers/",
                finalHolder.tv_paper_name.getText().toString()+".pdf");
                downloadReference = downloadManager.enqueue(request);
                DownloadManager.Query query = new DownloadManager.Query();
                Cursor cursor = downloadManager.query(query);
                BroadcastReceiver onComplete = new BroadcastReceiver() {
                            @Override
                            public void onReceive(Context context, Intent intent) {
                                pd.cancel();

                                if (pd.isShowing()) {
                                } else {
                                  pd.cancel();
                                   //Successful 
                                }

                            }
                        };
             activity.registerReceiver(onComplete,
                                new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

现在使用以下代码

更新您的代码

<强> UserCustomAdapter.java

public class UserCustomAdapter extends ArrayAdapter<User> {
Context context;
int layoutResourceId;
ArrayList<User> data = new ArrayList<User>();
static View row;
static DownloadTask downloadTask;

public UserCustomAdapter(Context context, int layoutResourceId,
                         ArrayList<User> data) {
    super(context, layoutResourceId, data);
    this.layoutResourceId = layoutResourceId;
    this.context = context;
    this.data = data;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    row = convertView;
    UserHolder holder = null;

    if (row == null) {
        LayoutInflater inflater = ((Activity) context).getLayoutInflater();
        row = inflater.inflate(layoutResourceId, parent, false);
        holder = new UserHolder();
        holder.tv_paper_name = (TextView) row.findViewById(R.id.tv_paper_name);
        holder.bt_download = (Button) row.findViewById(R.id.bt_download);
        row.setTag(holder);
    } else {
        holder = (UserHolder) row.getTag();
    }
    User user = data.get(position);
    holder.tv_paper_name.setText(user.getName());
    final UserHolder finalHolder = holder;

    holder.bt_download.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Log.i("Download Button Clicked", "**********");
            File extStore = Environment.getExternalStorageDirectory();
            File myFile = new File(extStore.getAbsolutePath() + "/Exam Papers/"+finalHolder.tv_paper_name.getText().toString()+".pdf");

            if (!myFile.exists()) {

   String sdcard_path = Environment.getExternalStorageDirectory().getPath();
                DownloadManager downloadManager = (DownloadManager) activity
                                .getSystemService((Service.DOWNLOAD_SERVICE));
                Uri Download_Uri = Uri.parse("https://letuscsolutions.files.wordpress.com/2015/07/five-point-someone-chetan-bhagat_ebook.pdf");
                DownloadManager.Request request = new DownloadManager.Request(Download_Uri);
                request.setAllowedNetworkTypes(
                                DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
                request.setAllowedOverRoaming(true);
                request.setTitle("Download PDF");
                request.setDescription("Downloading book..");
                request.setDestinationInExternalPublicDir("/Exam Papers/",
                finalHolder.tv_paper_name.getText().toString()+".pdf");
                downloadReference = downloadManager.enqueue(request);
                DownloadManager.Query query = new DownloadManager.Query();
                Cursor cursor = downloadManager.query(query);
                BroadcastReceiver onComplete = new BroadcastReceiver() {
                            @Override
                            public void onReceive(Context context, Intent intent) {
                                pd.cancel();

                                if (pd.isShowing()) {
                                } else {
                                  pd.cancel();
                                   //Successful 
                                   // change your button here...
                                }

                            }
                        };
             activity.registerReceiver(onComplete,
                                new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));



            } else {

                Toast.makeText(context, "File already Exists in "+myFile, Toast.LENGTH_SHORT).show();
            }

        }
    });
    return row;
}

static class UserHolder {
    TextView tv_paper_name;
    Button bt_download;
}
 }

答案 2 :(得分:1)

你必须在你的AsyncTask中传递View作为参数, 例如,

<强> 1&GT;像这样调用异步任务, 你可以看到,我传递了两个视图, holder.btn_download,holder.btn_purchse 作为参数,

gitlab-cal reconfigure

2&gt;从您的异步任务中获取参数

                      new pdfDownloading(activity,holder.btn_download,holder.btn_purchse,R.layout.recycler_item).execute(list.issuePdf, file,list.issueID);

这里是!!

您可以在onPostExecute中访问它并随意使用它们。