How to download a pdf on android

Asked

Viewed 1,157 times

1

In my app will have a listview with pdf titles, when clicking wanted to download to the device, a way to open offline, how could do this?

3 answers

0


Below is an example

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;

public class DownloadAsync extends AsyncTask<String, String, String> {

    Context ctx;
    ProgressDialog loadingDialog;

    public DownloadAsync(Context ctx) {
        this.ctx = ctx;
    }

    @Override
    protected void onPreExecute() {
        loadingDialog = new ProgressDialog(ctx);
        loadingDialog.setTitle("Sistema");
        loadingDialog.setMessage("Baixando arquivo");
        loadingDialog.setCancelable(false);
        loadingDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        loadingDialog.setMax(100);
        loadingDialog.show();
    }

    @Override
    protected String doInBackground(String... params) {
        String PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pdfs/";
        String SITE = "http://www.site.com.br";
        String arquivoNome = params[0];

        try{
            URL url = new URL(SITE + "/" + arquivoNome);
            URLConnection connection = url.openConnection();
            connection.connect();
            int fileLength = connection.getContentLength();

            InputStream input = new BufferedInputStream(url.openStream());

            String FilePath = PATH + "/" + arquivoNome;

            File file = new File(PATH);
            file.mkdirs();

            OutputStream output = new FileOutputStream(FilePath);

            byte data[] = new byte[1024];
            long total = 0;
            int count;

            while ((count = input.read(data)) != -1) {
                total += count;
                loadingDialog.setProgress((int)total * 100 / fileLength);
                output.write(data, 0, count);
            }

            output.flush();
            output.close();
            input.close();

            return FilePath;
        }
        catch(Exception e){ }

        return "";
    }
    @Override
    protected void onPostExecute(String result) {

        //RESULT CONTEM O CAMINHO LOCAL DO ARQUIVO
        super.onPostExecute(result);
        loadingDialog.dismiss();
    }
}

Use

new DownloadAsync(this).execute("meu_pdf.pdf");
  • No way to post the code with the progress bar?

  • this obj.getString, create the obj

  • Sorry I forgot to change, there you put the name that will be saved the pdf

  • has the code complete with the progress bar?

  • and I want it to be the name of the file itself neh, I don’t want to change the name

  • I changed the code posted, check there... created inside an Asynctask :)

  • I believe in onPostExecute if you pass Uri result to Intent it will open the file locally :)

  • goes on bp pf...

  • not working, when using

Show 5 more comments

0

The simplest way would be to release a browser input with the PDF url

Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(pdf_url));
startActivity(browserIntent);
  • That’s not what I want, I want to click on the list, it download to the mobile phone the pdf, and open offline with the mobile reader.

  • That’s not all he asked.

0

I will not hold myself to the way you will save this pdf on your device, because I imagine you have a minimum of knowledge to at least create a way to put the title of the document in PDF in this variable: String tituloURIpdf;, THAT IS TO DOWNLOAD OR LEAVE THE FILE IN THE COMPILATION ITSELF, WHICH DEPENDS ON THE OBJECTIVE. @Milton Filho, gave a hint of how to download, is one of the ways to get the title of the file. This variable will be in the main activity, remember her.

We started coding for the most basic part, the Listview XML, the "main.xml". Let’s set in it only a Listview and configure a few things, for example: a background color for our Linearlayout (android:background) the color of the Listview item divider (android:Divider) its thickness (android:dividerHeight) and an id (android:id).

Listing 1: Code of main.xml

<?xml version="1.0" encoding="UTF-8"?> 
<LinearLayout 
xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:orientation="vertical" 
android:background="#FFFFFFFF"
 > 

<ListView 
android:id="@+id/list" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:divider="#FFECECEC" 
android:dividerHeight="2sp" 
/> 

</LinearLayout>

Now that we have our list, we need the items, for this we will create the XML responsible for them, the "item_list.xml". In our item we will insert an image and two texts in a horizontal line. One of the texts will be our URI, to download the pdf.

It was inserted a horizontal Linearlayout (android:orientation) for our line and within it an Imageview responsible for the image and a Textview that will have its text centered vertically (android:Gravity) with a left margin so that it does not stay next to the image (android:layout_marginLeft).

Listing 2: Code for item_list.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout 
xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:orientation="horizontal" 
android:padding="5sp"> 

<ImageView 
android:id="@+id/imagemview" 
android:layout_width="wrap_content" 
android:layout_height="match_parent"
android:src="@drawable/NOME_ICONE_DE_DOWNLOAD_NA_PASTA_drawable" /> 

<TextView 
android:id="@+id/text" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:layout_marginLeft="5sp" 
android:gravity="center_vertical" 
android:textColor="#FF000000" /> 


<TextView 
android:id="@+id/URI" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:layout_marginLeft="5sp" 
android:gravity="center_vertical" 
android:textColor="#FF000000" /> 
</LinearLayout> 

The whole part of the layout has already been defined with these two files, now the next step is to create our class that will popular the items and the adapter leaving last the one that will control all this.

Class 1: Mainactivity.class

public class MainActivity extends Activity implements OnItemClickListener {
    private String tituloURIpdf; //VARIÁVEL FALADA NO COMEÇO DA RESPOSTA
    private ListView listView;
    private AdapterListView adapterListView;
    private ArrayList<ItemListView> itens;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //carrega o layout onde contem o ListView
        setContentView(R.layout.main);

 //CRIANDO UMA PASTA PARA ARMAZENAR OS PDF
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
         File directory = new File(Environment.getExternalStorageDirectory()+File.separator+"/AppNOME/MeusPDF/");
            directory.mkdirs();

    }

        //Pega a referencia do ListView
        listView = (ListView) findViewById(R.id.list);
        //Define o Listener quando alguem clicar no item.
        listView.setOnItemClickListener(this);

        createListView();
    }

    private void createListView() {
        //Criamos nossa lista que preenchera o ListView
        //Está limitada em 4 itens, mas você pode implementar isso para mais itens
        //Criando um for, por exemplo, e ponde em array. ESTUDE!
        //Estou lhe dando o básico

        itens = new ArrayList<ItemListView>();

        //tituloURIpdfÉ A VARIÁVEL FALADA NO COMEÇO DA RESPOSTA
        //Poderíamos usar ela para não colocar os títulos dos PDF na "mão"
        //EXEMPLO, mas ela está vazia, pois você vai criar ainda alguma forma de por
        //textos nela, neh?
        /*
        ItemListView item1 = new ItemListView("Apostila Java", Uri.parse(Environment.getExternalStorageDirectory().getAbsolutePath() +
            "/AppNOME/MeusPDF/" + tituloURIpdf);
        */


        ItemListView item1 = new ItemListView("Apostila Java", Uri.parse(Environment.getExternalStorageDirectory().getAbsolutePath() +
            "/AppNOME/MeusPDF/" + "ApostilaJava.pdf");

        ItemListView item2 = new ItemListView("Desorientado por objeto", Uri.parse(Environment.getExternalStorageDirectory().getAbsolutePath() +
            "/AppNOME/MeusPDF/" + "Desorientado.pdf");

        ItemListView item3 = new ItemListView("Revista -Por que votei na Dilma?", Uri.parse(Environment.getExternalStorageDirectory().getAbsolutePath() +
            "/AppNOME/MeusPDF/" + "foraDilma.pdf");

        ItemListView item4 = new ItemListView("Stackoverflow bíblia", Uri.parse(Environment.getExternalStorageDirectory().getAbsolutePath() +
            "/AppNOME/MeusPDF/" + "StackoverflowBible.pdf");

        itens.add(item1);
        itens.add(item2);
        itens.add(item3);
        itens.add(item4);

        //Cria o adapter
        adapterListView = new AdapterListView(this, itens);

        //Define o Adapter
        listView.setAdapter(adapterListView);
        //Cor quando a lista é selecionada para ralagem.
        listView.setCacheColorHint(Color.TRANSPARENT);
    }

        //Aqui será onde o usuário irá baixar os seus PDF.
        //Lebrando que eu IMAGINO que você saiba como .
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        //Pega o item que foi selecionado.
        ItemListView item = adapterListView.getItem(arg2);

        Buscando caminho do arquivo
        Uri ArquivoPDF= Uri.parse(Environment.getExternalStorageDirectory().getAbsolutePath() +
            "/AppNOME/MeusPDF/" + item.getPdf() );

        //DOWNLOAD            
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(ArquivoPDF, "application/pdf");
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);

        //Demostração
        Toast.makeText(this, "Você baixou o arquivo : " + item.getPdf(), Toast.LENGTH_LONG).show();
    }
}

We will create our Object according to our item through the functions of the class below. Use your imagination to create the functions and return the values. Play!

Class 2: Itemlistview.class

public class ItemListView {


    private String titulo;
    private String pdfUri;


    public ItemListView() {
    }

    public ItemListView(String titulo, String iconeRid) {
        this.pdfUri = pdfUri;
        this.iconeRid = iconeRid;
    }


    public String getTitulo() {
        return titulo;
    }

    public void setTitulo(String titulo) {
        this.titulo = titulo;
    }

    public String getPdfUri() {
        return pdfUri;
    }

    public void setPdfUri(String pdfUri) {
        this.pdfUri = pdfUri;
    }
}

After created the Object we will create the Adapter, the heart of Listview.

getView() is our main method, it is the list updater, which is frequently updated and each time, this method is executed according to the amount of items in getCont(). It takes 3 parameters: the position, the view of the previous update which is our already loaded layout (outdated) and the Viewgroup which is (if any) the "parent" of the view.

Let’s create an internal class called Itemsuporte that will have the views of our layout. This class is created to give us a quick update so we don’t have to upload all the data again. If our view does not exist, we will inflate it (load) through the Layoutinflater attribute that was created in the class constructor. After the layout is loaded and assigned to the view, we will create the Itemsuporte by inserting the views of the item_list into its interior. Once inserted, we define it as a view tag by the setTag() method, because if the view already existed we would only upload Itemsuporte by getTag().

After loading or creating the view, we add the respective Itemlistview to the position of the list and update the data from our view by the data from our item and at the end of the method return the view with the updated data.

See how simple it is:

Class 3: Adapterlistview . class

public class AdapterListView extends BaseAdapter {
 
    private LayoutInflater mInflater;
    private ArrayList<ItemListView> itens;
 
    public AdapterListView(Context context, ArrayList<ItemListView> itens) {
        //Itens que preencheram o listview
        this.itens = itens;
        //responsavel por pegar o Layout do item.
        mInflater = LayoutInflater.from(context);
    }
 
    /**
     * Retorna a quantidade de itens
     *
     * @return
     */
    public int getCount() {
        return itens.size();
    }
 
    /**
     * Retorna o item de acordo com a posicao dele na tela.
     *
     * @param position
     * @return
     */
    public ItemListView getItem(int position) {
        return itens.get(position);
    }
 
    /**
     * Sem implementação
     *
     * @param position
     * @return
     */
    public long getItemId(int position) {
        return position;
    }
 
    public View getView(int position, View view, ViewGroup parent) {
        ItemSuporte itemHolder;
        //se a view estiver nula (nunca criada), inflamos o layout nela.
        if (view == null) {
            //infla o layout para podermos pegar as views
            view = mInflater.inflate(R.layout.item_list, null);
 
            //cria um item de suporte para não precisarmos sempre
            //inflar as mesmas informacoes
            itemHolder = new ItemSuporte();
            itemHolder.txtTitle = ((TextView) view.findViewById(R.id.text));
            itemHolder.txtURI = ((TextView) view.findViewById(R.id.URI));
            //itemHolder.imgIcon = ((ImageView) view.findViewById(R.id.imagemview));
 
            //define os itens na view;
            view.setTag(itemHolder);
        } else {
            //se a view já existe pega os itens.
            itemHolder = (ItemSuporte) view.getTag();
        }
 
        //pega os dados da lista
        //e define os valores nos itens.
        ItemListView item = itens.get(position);
        itemHolder.txtTitle.setText(item.getTitulo());
        itemHolder.txtURI.setText(item.getPdfUri());
        
        //Veja se isto torna invisível o texto da URI
        itemHolder.txtURI.setVisibility(View.GONE);
        //itemHolder.imgIcon.setImageResource(item.getIconeRid());
 
        //retorna a view com as informações
        return view;
    }
 
    /**
     * Classe de suporte para os itens do layout.
     */
    private class ItemSuporte {
 
        //ImageView imgIcon;
        TextView txtTitle;
        TextView txtURI;
    }
 
}

PERMISSION:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

DOUBTS??

Browser other questions tagged

You are not signed in. Login or sign up in order to post.