Save a PDF to Sqlite

Asked

Viewed 127 times

0

I’m beginner and I’m having trouble saving the pdf in the bank, I don’t even know how I can do it.

botaoBusca.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("application/pdf");
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                startActivityForResult(intent, 1);    
            }    
        });

        salvar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {    

                    //PDFViewToByte(imageView);
                    Toast.makeText(getApplicationContext(),"Salvo com Sucesso", Toast.LENGTH_SHORT).show();

                }catch (Exception e )
                {
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(),"Erro", Toast.LENGTH_SHORT).show();
                }    
            }
        });          
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK && requestCode==1)
        {
            Uri PDFSelecionada = data.getData();
            String [] colunas = {MediaStore.MediaColumns.DATA};
            Cursor cursor = getContentResolver().query(PDFSelecionada,colunas, null,null,null);
            cursor.moveToFirst();

            int indexColuna = cursor.getColumnIndex(colunas[0]);
            String pathPDF = cursor.getString(indexColuna);

            cursor.close();    
            textView.setText("PDF Carregado");        
        }    
    }

    private byte[] PDFViewToByte(File pdf) throws IOException {
        InputStream is = new FileInputStream( pdf );
        byte[] bytes = new byte[(int)pdf.length() ];
        int offset = 0;
        int numRead = 0;
        while (offset < bytes.length && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0)
        {
            offset += numRead;
        }          

        return bytes;

1 answer

1


Saving a pdf file in Android sqlite is not a very recommended practice.

The best and most recommended solution would be you save in the app’s internal storage and save in your Sqlite table only the reference to that file. Saving purchases in a database is not a good practice.

Here https://developer.android.com/training/data-storage/app-specific you will find the documentation to understand a little more about using this built-in app storage feature on Android.

Browser other questions tagged

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