3

I Create a one project in this project i download the PDF file form server which is work perfectly.

Here is my UI

enter image description here

But i want is after download file change the icon of the button. And open the downloaded PDf file using this button.

Please help me

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();
    }

}
Arpit Patel
  • 7,212
  • 5
  • 56
  • 67

3 Answers3

2

You can modify your getView() method. Try to implement following steps. 1. First, fetch all downloaded PDFs from your local folder. 2. Pass that fetched list to your Adapter. 3. when you inflate and create a view in your get view method, first, try to match the current name to downloaded file name. 4. If the current file is already downloaded then change download button to open button. And, if it is not downloaded before then just display download button. with this when you reopen the application you get the output what you want.

And for your situation like when download completes, just try to execute notifySetDataChanged. It will automatically recreate listview according to above pattern. Hope you understand.:)

Dhaval
  • 2,724
  • 2
  • 24
  • 33
1

Just use to DownloadManager see below code.

                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));

Now Update your code with belowcode

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;
}
 }
Ravi Vaghela
  • 3,420
  • 2
  • 23
  • 51
1

You have to pass View inside your AsyncTask as a argument , for example ,

1> call async task like this , as you can see ,I'm passing two views ,holder.btn_download,holder.btn_purchse as parameters ,

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

2>get params from your async task like this,

//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);


    }

}

And here it is !!

you can access it inside onPostExecute and play with them you as you want ..

Radhey
  • 2,139
  • 2
  • 24
  • 42