如何从从Firebase数据库获取的列表视图中查看PDF?

huangapple 未分类评论49阅读模式
英文:

how to view PDF from a list view which is fetch from Firebase database?

问题

我从Firebase数据库中获取了一个PDF列表视图

这是我用来获取的代码

public class ViewFiles extends AppCompatActivity {

    ListView myViewFiles;
    DatabaseReference databaseReference;
    List<uploadFiles> uploadDOCS;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_files);

        myViewFiles = (ListView) findViewById(R.id.myViewFiles);
        uploadDOCS = new ArrayList<uploadFiles>();

        viewAllFiles();

        myViewFiles.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                uploadFiles uploadFiles = uploadDOCS.get(position);

                Intent intent = new Intent();
                intent.setType(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(uploadFiles.getUrl()));
                intent = new Intent(ViewFiles.this, ViewPdfFiles.class);
                startActivity(intent);
            }
        });
    }

    private void viewAllFiles() {

        databaseReference = FirebaseDatabase.getInstance().getReference("HNDIT").child("1st Year 2nd Sem").child("ENGLISH");
        databaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                for (DataSnapshot postSnapshot: dataSnapshot.getChildren()){

                    uploadFiles uploadFiles = postSnapshot.getValue(com.example.lms.fileupload.uploadFiles.class);
                    uploadDOCS.add(uploadFiles);
                }

                String[] uploads = new String[uploadDOCS.size()];

                for (int i=0; i < uploads.length; i++){
                    uploads[i] = uploadDOCS.get(i).getName();

                }
                ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,uploads){
                    @NonNull
                    @Override
                    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                        View view = super.getView(position, convertView, parent);
                        TextView myText = (TextView) view.findViewById(android.R.id.text1);
                        myText.setTextColor(Color.BLACK);

                        return view;
                    }
                };
                myViewFiles.setAdapter(adapter);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });

    }
}

这是它的显示方式
点击这里查看

我已经为在Android中查看这些文件创建了一个意图,但它不会显示,保持空白,这是它显示的错误

E/PDFView: 加载PDF错误
java.lang.NullPointerException: 尝试在空对象引用上调用'int java.io.InputStream.read(byte[])'
在com.github.barteksc.pdfviewer.util.Util.toByteArray(Util.java:36)
在com.github.barteksc.pdfviewer.source.InputStreamSource.createDocument(InputStreamSource.java:37)
在com.github.barteksc.pdfviewer.DecodingAsyncTask.doInBackground(DecodingAsyncTask.java:53)
在com.github.barteksc.pdfviewer.DecodingAsyncTask.doInBackground(DecodingAsyncTask.java:25)
在android.os.AsyncTask$2.call(AsyncTask.java:333)
在java.util.concurrent.FutureTask.run(FutureTask.java:266)
在java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
在java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
在java.lang.Thread.run(Thread.java:764)

这是那个代码

public class ViewPdfFiles extends AppCompatActivity {

    private PDFView pdfView;
    private String url;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_pdf_files);

        pdfView=(PDFView) findViewById(R.id.pdfView);

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            url = getIntent().getStringExtra("url");
        }
        new RetrievePDFStream().execute(url);
    }

    class RetrievePDFStream extends AsyncTask<String,Void, InputStream> {
        @Override
        protected InputStream doInBackground(String... strings) {
            InputStream inputStream = null;

            try{

                URL url=new URL(strings[0]);
                HttpURLConnection urlConnection=(HttpURLConnection) url.openConnection();
                if(urlConnection.getResponseCode()==200){
                    inputStream=new BufferedInputStream(urlConnection.getInputStream());

                }
            }catch (IOException e){
                return null;
            }
            return inputStream;

        }

        @Override
        protected void onPostExecute(InputStream inputStream) {
            pdfView.fromStream(inputStream).load();
        }
    }
}

这是视图部分的XML代码 XML文件

我该如何修复这个错误并在Android中查看文件...

如何从从Firebase数据库获取的列表视图中查看PDF?
如何从从Firebase数据库获取的列表视图中查看PDF?
如何从从Firebase数据库获取的列表视图中查看PDF?

这是我的Firebase数据库中文件的样子
数据库视图

英文:

I have fetched a PDF list view from Firebase Database

This is the code that i used to fetch

public class ViewFiles extends AppCompatActivity {

ListView myViewFiles;
DatabaseReference databaseReference;
List&lt;uploadFiles&gt; uploadDOCS;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_view_files);

    myViewFiles = (ListView) findViewById(R.id.myViewFiles);
    uploadDOCS = new ArrayList&lt;uploadFiles&gt;();

    viewAllFiles();

    myViewFiles.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView&lt;?&gt; parent, View view, int position, long id) {
            uploadFiles uploadFiles = uploadDOCS.get(position);

            Intent intent = new Intent();
            intent.setType(Intent.ACTION_VIEW);
            intent.setData(Uri.parse(uploadFiles.getUrl()));
            intent = new Intent(ViewFiles.this, ViewPdfFiles.class);
            startActivity(intent);
        }
    });
}

private void viewAllFiles() {

    databaseReference = FirebaseDatabase.getInstance().getReference(&quot;HNDIT&quot;).child(&quot;1st Year 2nd Sem&quot;).child(&quot;ENGLISH&quot;);
    databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

            for (DataSnapshot postSnapshot: dataSnapshot.getChildren()){

                uploadFiles uploadFiles = postSnapshot.getValue(com.example.lms.fileupload.uploadFiles.class);
                uploadDOCS.add(uploadFiles);
            }

            String[] uploads = new String[uploadDOCS.size()];

            for (int i=0; i &lt; uploads.length; i++){
                uploads[i] = uploadDOCS.get(i).getName();

            }
            ArrayAdapter&lt;String&gt; adapter = new ArrayAdapter&lt;String&gt;(getApplicationContext(),android.R.layout.simple_list_item_1,uploads){
                @NonNull
                @Override
                public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                    View view = super.getView(position, convertView, parent);
                    TextView myText = (TextView) view.findViewById(android.R.id.text1);
                    myText.setTextColor(Color.BLACK);

                    return view;
                }
            };
            myViewFiles.setAdapter(adapter);
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });

}

}

This is how it displays
Click here to View

And i have create a intent for view these file in PDF view in android but it won't display keep blank this is the error it shows

E/PDFView: load pdf error
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.io.InputStream.read(byte[])' on a null object reference
at com.github.barteksc.pdfviewer.util.Util.toByteArray(Util.java:36)
at com.github.barteksc.pdfviewer.source.InputStreamSource.createDocument(InputStreamSource.java:37)
at com.github.barteksc.pdfviewer.DecodingAsyncTask.doInBackground(DecodingAsyncTask.java:53)
at com.github.barteksc.pdfviewer.DecodingAsyncTask.doInBackground(DecodingAsyncTask.java:25)
at android.os.AsyncTask$2.call(AsyncTask.java:333)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:764)

this is the code of that

public class ViewPdfFiles extends AppCompatActivity {

private PDFView pdfView;
private String url;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_view_pdf_files);

    pdfView=(PDFView) findViewById(R.id.pdfView);


    Bundle bundle = getIntent().getExtras();
    if (bundle != null) {
        url = getIntent().getStringExtra(&quot;url&quot;);
    }
    new RetrievePDFStream().execute(url);
}


class RetrievePDFStream extends AsyncTask&lt;String,Void, InputStream&gt; {
    @Override
    protected InputStream doInBackground(String... strings) {
        InputStream inputStream = null;

        try{

            URL url=new URL(strings[0]);
            HttpURLConnection urlConnection=(HttpURLConnection) url.openConnection();
            if(urlConnection.getResponseCode()==200){
                inputStream=new BufferedInputStream(urlConnection.getInputStream());

            }
        }catch (IOException e){
            return null;
        }
        return inputStream;

    }

    @Override
    protected void onPostExecute(InputStream inputStream) {
        pdfView.fromStream(inputStream).load();
    }
}

}

This view parts xml code The Xml file

how can i fix this error and view files in android...

如何从从Firebase数据库获取的列表视图中查看PDF?
如何从从Firebase数据库获取的列表视图中查看PDF?
如何从从Firebase数据库获取的列表视图中查看PDF?

This is how the files in my firebase database
the database view

答案1

得分: 0

我想从你在这里的错误开始回答:

Intent intent = new Intent();
intent.setType(Intent.ACTION_VIEW);
intent.setData(Uri.parse(uploadFiles.getUrl()));
intent = new Intent(ViewFiles.this, ViewPdfFiles.class);
startActivity(intent);

你在 intent 对象中做了所有重要的设置,比如设置了它的 typedata,然后最终却将那个 实例 抛弃了,创建了一个新的 Intent 实例。所以现在你的 intent 对象知道要去哪里,即 ViewPdfFiles.class,但它的 datatype 并未设置。将代码的第一行改为

Intent intent = new Intent(ViewFiles.this, ViewPdfFiles.class);

并移除 第四行 应该可以解决问题。
编辑后的答案:

Intent intent = new Intent(ViewFiles.this, ViewPdfFiles.class);
// 如果 uploadFiles.getUrl() 是字符串,则使用 putExtra(String, String) 方法发送数据
intent.putExtra("url", uploadFiles.getUrl());
startActivity(intent);

空对象错误
如何从从Firebase数据库获取的列表视图中查看PDF?

英文:

I want to start my answer with what you did wrong here :

        Intent intent = new Intent();
        intent.setType(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(uploadFiles.getUrl()));
        intent = new Intent(ViewFiles.this, ViewPdfFiles.class);
        startActivity(intent);  

You did all the important stuff in your intent object like setting it's type and data and then finally you ditched that instance for a new Intent instance. So now your intent object does know where to go i.e. ViewPdfFiles.class but does not have data or type set to it. Changing first line of code to
Intent intent = new Intent(ViewFiles.this, ViewPdfFiles.class);
and removing 4th line should work.
Edited answer :

Intent intent = new Intent(ViewFiles.this, ViewPdfFiles.class);;
//send data using putExtra(String, String) method if uploadFiles.getUrl() is string
intent.putExtra(&quot;url&quot;, uploadFiles.getUrl());
startActivity(intent);

the null object
如何从从Firebase数据库获取的列表视图中查看PDF?

huangapple
  • 本文由 发表于 2020年5月4日 17:22:34
  • 转载请务必保留本文链接:https://java.coder-hub.com/61588920.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定