在Android上显示PDF文件

时间:2015-04-15 13:15:59

标签: java android pdf

我想加载并显示PDF文件。这些文件在列表视图中,我想显示一个选定的PDF文件。这是代码:

 public class MainActivity extends ActionBarActivity {

        final StringBuffer sb = new StringBuffer();
    private ListView mainListView ;  
        private ArrayAdapter<String> listAdapter ;  
    String filepath;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_firstactivity);
            mainListView = (ListView) findViewById( R.id.mainListView );  
            final ArrayList<String> List = new ArrayList<String>();  
        final File storage = Environment.getExternalStorageDirectory();
            File file = new File(storage,"/Folder/");
        if (file.exists() && file.isDirectory()) {
                for (String s : file.list()) {
                    sb.append(s + " ");
        List.addAll( Arrays.asList(s) );
                }
            }

            listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, R.id.rowTextView,List); 
            mainListView.setAdapter( listAdapter );  
    mainListView.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

                    String filepath = new File("/Folder/"+ List.get(arg2)).getAbsolutePath();
                     File file = new File(filepath);
                    openPdfIntent(file);


                }


            });
        }
        private void openPdfIntent(File file) {
               Uri path = Uri.fromFile(file);

                            Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
                            pdfIntent.setDataAndType(path, "application/pdf");
                            pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            try {
                                startActivity(pdfIntent);
                            } catch (Exception e) {
                            e.printStackTrace();
                        }
     }

此代码不起作用。 logcat错误是:“java.lang.NullPointerException”。 我怎么解决这个问题?

3 个答案:

答案 0 :(得分:0)

试试这段代码:

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("path-to-document"));
intent.setType("application/pdf");
PackageManager pm = getPackageManager();
List<ResolveInfo> activities = pm.queryIntentActivities(intent, 0);
if (activities.size() > 0) {
    startActivity(intent);
} else {
    // Do something else here. Maybe pop up a Dialog or Toast
}

答案 1 :(得分:0)

根据我的说法,你得到的错误是由于文件路径不正确,只需指定“/ Folder /”就会返回空指针异常。 尝试像

这样的东西
       String path=Environment.getExternalStorageDirectory().getAbsolutePath()+"/FolderName/"+"File name in list"

答案 2 :(得分:0)

尝试此示例,旧类型但代码是完美的 http://www.edumobile.org/android/pdf-list-example/