【问题标题】:Changed listview item button after download file下载文件后更改了列表视图项目按钮
【发布时间】:2016-09-26 14:28:12
【问题描述】:

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

这是我的用户界面

但我想要的是在下载文件后更改按钮的图标。并使用此按钮打开下载的 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;
    }
}

下载任务.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();
    }

}

【问题讨论】:

  • 你试过下载管理器吗?
  • 但我在下载时没有遇到问题。下载代码完美无缺。
  • 那你怎么检测你的文件被下载了呢?
  • 它在特定的(试卷)文件夹中
  • 当您的文件成功下载时,您收到任何 toast 消息?就像File downloaded

标签: android listview


【解决方案1】:

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

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

【讨论】:

  • 欢迎@ArpitPatel :)
【解决方案2】:

只需使用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;
}
 }

【讨论】:

  • 对不起回家时间我明天试试再告诉你
  • 在您的点击事件中
  • 什么是下载参考??
  • 你可以在那儿给出从不使用的注释,那个类型是long变量。
【解决方案3】:

您必须在 AsyncTask 中将 View 作为参数传递, 例如,

1> 像这样调用异步任务, 如您所见,我传递了两个视图,holder.btn_download,holder.btn_purchse 作为参数,

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

2>像这样从你的异步任务中获取参数,

//async task..
public class pdfDownloading extends AsyncTask<Object, String, File> {
    private WeakReference vRef;

    String issuePdf,issue_ID ;
    LayoutInflater inflater;
    TextView view;
    LinearLayout ll_bg;
    int id;
    File file;
    public pdfDownloading(Context context,TextView v,LinearLayout ll,int layoutResId){
        this.view = v;
        this.ll_bg = ll;
        inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        this.id = layoutResId;
    }
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(activity);
        pDialog.setMessage("Downloading...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    @SuppressWarnings("deprecation")
    @Override
    protected File doInBackground(Object... args) {

        try {

            //  issuePdf=args[0];

            issuePdf = (String) args[0];
            File file = (File) args[1];
            issue_ID = (String) args[2];

            Log.e(TAG,"do in back issuePdf :: "+issuePdf);
            CM.DownloadFile(issuePdf, file);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return file;
    }

    @Override
    protected void onPostExecute(File file) {
        // TODO Auto-generated method stub
        super.onPostExecute(file);
        View yourLayout = inflater.inflate(id, null);

        view.setText("READ");

        ll_bg.setBackgroundResource(R.drawable.bg_button_fb);
        pDialog.dismiss();

        //add download api calls
        webcallAddDownload(issue_ID);


    }

}

就在这里!!

您可以在 onPostExecute 中访问它并随心所欲地与他们一起玩..

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-19
  • 1970-01-01
  • 1970-01-01
  • 2018-09-18
  • 1970-01-01
  • 2012-12-21
相关资源
最近更新 更多