In my app will have a listView with pdf titles, when I clicked wanted to download to the device, a way to open offline, how could I do that?
In my app will have a listView with pdf titles, when I clicked wanted to download to the device, a way to open offline, how could I do that?
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");
The simplest way would be to launch a browser intent with the document pdf url
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(pdf_url));
startActivity(browserIntent);
I'm not going to lock myself in the way that you'll save this pdf to your device, as I imagine you have a minimum of knowledge to at least create a way to by the title of the PDF document in that variable: String tituloURIpdf;
, OR DOWNLOAD OR LEAVE THE FILE IN THE COMPILATION, which depends on the purpose. @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 it .
We begin to encode by the most basic part, the ListView XML, the "main.xml". Let's define in it only a ListView and configure some things, for example: a background color for our LinearLayout (android: background) the color of the ListView (android: divider) item's its thickness (android: dividerHeight) and an id android: id).
Listing 1 : main.xml code
<?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, so we'll 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 be able to download the pdf.
A horizontal LinearLayout (android: orientation) has been inserted into our line and inside it an ImageView responsible for the image and a TextView that will have its text centered vertically (android: gravity) with a margin to the left so it is not next to the image (android: layout_marginLeft).
Listing 2: Item_list.xml code
<?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 layout part has already been defined with these two files, now the next step is to create our class that will populate the items and the adapter leaving the last one to control all that.
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 creating the Object we will create the Adapter, the heart of the ListView.
The getView () method is our main method, it is the list updater, which is frequently updated and each time, this method is executed according to the number of getCont () items. It has 3 parameters: the position, the view of the previous update that is our already loaded layout (outdated) and the ViewGroup which is (if any) the "parent" of the view.
Let's create an inner class called ItemSupport that will have the views of our layout. This class is designed to give us a quick update so we do not have to load 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 Support Item by inserting the item_list views inside it. I have created a viewTag () and I want to create a viewTag () method in the viewTag (). If the view already exists we would only load the SupportType through getTag ().
After loading or creating the view, we add the respective ItemListView to the position of the list and update the data of our view by the data of our item and at the end of the method we 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 ??