Android通过Intent打开pdf文件

时间:2015-05-23 08:31:58

标签: android pdf android-intent

我在sdcard的某些文件夹中有一些pdf文件。我创建了一个将所有pdf显示为ListView的应用程序。当我点击任何pdf文件时,它在OfficeSuite应用程序中出错(UNSUPPORTED或CORRUPT FILE FORMAT。代码有问题。这是代码。

//显示为ListVIew的项目代码

public class Helper
{
    public static string Directory = "D:\\Desktop\\MusicDatabase\\";
    public static string ConcatDirectory(string input)
    {
        return string.Concat(Directory, input);
    }
}

//打开VIA Intent文件的代码

    ListView lv;
    ArrayList<String> FilesInFolder = GetFiles(Environment.getExternalStorageDirectory()
            + "/SOMEFOLDER");
    lv = (ListView) findViewById(R.id.filelist);

    lv.setAdapter(new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, FilesInFolder));



    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
            // Clicking on items
            open_File();
        }
    });

    public ArrayList<String> GetFiles(String DirectoryPath) {
    ArrayList<String> MyReports = new ArrayList<String>();
    File f = new File(DirectoryPath);

    f.mkdirs();
    File[] files = f.listFiles();
    if (files.length == 0)
        return null;
    else {
        for (int i=0; i<files.length; i++)
            MyReports.add(files[i].getName());
    }

    return MyReports;
}

错误:

损坏或不支持的文件格式

1 个答案:

答案 0 :(得分:1)

我想你忘了指定文件了。查看您的代码,您只将其指向该文件夹,但没有文件本身。我认为这就是为什么它告诉你它格式错误,因为它不以.pdf

结尾
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "SOMEFOLDER" + File.separator + "pdffile.pdf");

编辑:根据您的评论修改方法

lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
        // Clicking on items
        String fileName = FilesInFolder.get(position);
        open_File(fileName);
    }
});

public void open_File(String filename){
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/SOMEFOLDER", filename);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intent1 = Intent.createChooser(intent, "Open With");
try {
    startActivity(intent1);
} catch (ActivityNotFoundException e) {
    // Instruct the user to install a PDF reader here, or something
}