Не могу открыть PDF после загрузки из Firebase - PullRequest
1 голос
/ 19 февраля 2020

Я использую этот код для загрузки и показа PDF в упражнении. Он успешно загружен, но не открывается после завершения загрузки.

public class PdfView extends AppCompatActivity {
    private PDFView pdfView;
    private TextView textView;
    private String pdfName = "";
    private String pdfUrl = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(pdf_activity);

   pdfView = findViewById(R.id.pdfView);
    pValue = findViewById(R.id.pValue);
    down =findViewById(R.id.down);

        if(getIntent().getExtras() != null){
            pdfName = getIntent().getExtras().getString("pdf_name");
            pdfUrl = getIntent().getExtras().getString("pdf_url");

            if(pdfName != null)
                pdfName = pdfName.replace("", "")+".pdf";
            downloadFile();
        }
    }

    private void downloadFile() {
        new AsyncTask<Void, Integer, Boolean>(){
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }

            @Override
            protected Boolean doInBackground(Void... params) {
                return downloadFile();
            }

            @Nullable
            private Boolean downloadFile(){
                try {
                    File file = getFileStreamPath(pdfName);
                    if(file.exists())return true;
                    try {
                        FileOutputStream fileOutputStream =
                                openFileOutput(pdfName, Context.MODE_PRIVATE);
                        URL u = new URL(pdfUrl);
                        URLConnection conn = u.openConnection();
                        int contentLength = conn.getContentLength();
                        InputStream input = new BufferedInputStream(u.openStream());
                        byte data[] = new byte[contentLength];
                        long total =0;
                        int count;
                        while((count = input.read(data)) != -1){
                            total+= count;
                            publishProgress((int)((total * 100) / contentLength));
                            fileOutputStream.write(data,0,count);
                        }
                        fileOutputStream.flush();
                        fileOutputStream.close();
                        input.close();
                        return true;
                    } catch (final Exception e) {
                        e.printStackTrace();
                        return false;
                    }
                }catch (Exception e) {
                    e.printStackTrace();
                    return false;
                }
            }

            @Override
            protected void onProgressUpdate(Integer... values) {
                super.onProgressUpdate(values);
            }
            @Override
            protected void onPostExecute(Boolean aBoolean){
                if (aBoolean){
                    openPdf(pdfName);
                }else {
                    Toast.makeText(PdfView.this, "unable to download ", Toast.LENGTH_SHORT).show();
                }
            }
        }.execute();
    }
    private void openPdf(String pdfName) {
        try {
            final File file = getFileStreamPath(pdfName);
            if (file != null){
                Log.e("file","file"+file.getAbsolutePath());
                pdfView.setVisibility(View.VISIBLE);
                pdfView.fromFile(file).enableSwipe(true).swipeHorizontal(false).onError(new OnErrorListener() {
                    @Override
                    public void onError(Throwable t) {
                        Log.e("file", "file" + t.toString());
                        try {
                            if (file.exists())
                                file.delete();

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).enableAntialiasing(true).spacing(2).pageFitPolicy(FitPolicy.WIDTH).load();

            }

        } catch (Exception e){
            e.printStackTrace();
        }
    }
}

Класс адаптера

public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {
MainActivity mainActivity;
ArrayList<DownModel> downModels;

public MyAdapter(MainActivity mainActivity, ArrayList<DownModel> downModels) {
    this.mainActivity = mainActivity;
    this.downModels = downModels;
}

@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {

    LayoutInflater layoutInflater = LayoutInflater.from(mainActivity.getBaseContext());
    View view = layoutInflater.inflate(R.layout.elements, viewGroup, false);

    return new MyViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull final MyViewHolder myViewHolder, final int i) {

    myViewHolder.mName.setText(downModels.get(i).getName());
    myViewHolder.mLink.setText(downModels.get(i).getLink());
    myViewHolder.mDownload.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(myViewHolder.mDownload.getContext(),PdfView.class);

            intent.putExtra("pdf_url", downModels.get(i).getLink());
            intent.putExtra("pdf_name",downModels.get(i).getName());
            myViewHolder.mDownload.getContext().startActivity(intent);

        }
    });




}


@Override
public int getItemCount() {
    return downModels.size();
}
}

2020-02-19 23: 08: 35.130 1919-1919 / com.solutions.rsaggarwal I / Хронология: Временная шкала: Activity_launch_request time : 163047167

2020-02-19 23: 08: 35.173 1919-1919 / com.solutions.rsaggarwal W / ActivityThread: handleWindowVisibility: нет активности для токена android .os. BinderProxy@281d3b6

2020-02-19 23: 08: 35.250 1919-1919 / com.solutions.rsaggarwal D / com.shockwave.pdfium.PdfiumCore: Исходный Pdfium Android 1.9.0

2020-02-19 23: 08: 35.317 1919-1919 / com.solutions.rsaggarwal E / file: file / data / user / 0 / com.solutions.rsaggarwal / files / Глава 1: Органическая химия.pdf

2020-02 -19 23: 08: 35.317 1919-1919 / com.solutions.rsaggarwal W / System.err: java .lang.NullPointerException: попытка вызвать виртуальный метод void com.github.barteks c .pdfviewer.PDFView. setVisibility (int) 'для ссылки на пустой объект

2020-02-19 23: 08: 35.317 1919-1919 / com.solutions.rsaggarwal W / System.err: at com.solutions.rsaggarwal.PdfView. openP df (PdfView. java: 116)

2020-02-19 23: 08: 35.317 1919-1919 / com.solutions.rsaggarwal W / System.err: at com.solutions.rsaggarwal.PdfView. доступ $ 200 (PdfView. java: 27)

2020-02-19 23: 08: 35.317 1919-1919 / com.solutions.rsaggarwal W / System.err: at com.solutions.rsaggarwal.PdfView $ 1.onPostExecute (PdfView. java: 104)

2020-02-19 23: 08: 35.317 1919-1919 / com.solutions.rsaggarwal W / System.err: at com.solutions.rsaggarwal. PdfView $ 1.onPostExecute (PdfView. java: 52)

2020-02-19 23: 08: 35.317 1919-1919 / com.solutions.rsaggarwal W / System.err: at android .os .AsyncTask.fini sh (AsyncTask. java: 695)

2020-02-19 23: 08: 35.317 1919-1919 / com.solutions.rsaggarwal W / System.err: at android .os.AsyncTask.access $ 600 (AsyncTask. java: 180)

2020-02-19 23: 08: 35.317 1919-1919 / com.solutions.rsaggarwal W / System.err: at android .os.AsyncTask $ InternalHandler.handleMessage (AsyncTask. java: 712)

2020-02-19 23: 08: 35.317 1919-1919 / com.solutions.rsaggarwal W / System.err: at android .os.Handler.dispatchMessage (Обработчик. java: 106)

2020-02-19 23: 08: 35.317 1919-1919 / com.solutions.rsaggarwal W / System.err: at android .os.Looper.l oop (Looper. java: 201)

2020-02-19 23: 08: 35.317 1919-1919 / com. solutions.rsaggarwal W / System.err: at android .app.ActivityThread.main (ActivityThread. java: 6823)

2020-02-19 23: 08: 35.317 1919-1919 / com. solutions.rsaggarwal W / System.err: at java .lang.reflect.Method.invoke (родной метод)

2020-02-19 23: 08: 35.317 1919-1919 / com.solutions.rsaggarwal W / System.err: at com. android .internal.os.RuntimeInit $ MethodAndArgsCaller.run (RuntimeInit. java: 547)

2020-02-19 23: 08: 35.317 1919-1919 /com.solutions.rsaggarwal W / System.err: at com. android .internal.os.ZygoteInit.main (ZygoteInit. java: 873)

2020-02-19 23:08: 39,223 1919-1995 / com.solutions.rsaggarwal I / ion.rsaggarwa: ProcessProfilingInfo new_methods = 5526 сохранено сохранено_диск_ = 1 resol_classes_delay = 8000

...