gpt4 book ai didi

Android通过Intent打开pdf文件

转载 作者:行者123 更新时间:2023-11-30 02:08:42 25 4
gpt4 key购买 nike

我在 sdcard 的某个文件夹中有一些 pdf 文件。我创建了一个将所有 pdf 显示为 ListView 的应用程序。当我单击任何 pdf 文件时,它会在 OfficeSuite 应用程序中出现错误(不支持或损坏的文件格式。代码有问题。这是代码。

//项目显示为ListVIew的代码

    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;
}

//VIA Intent打开文件代码

    public void open_File(){
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/SOMEFOLDER");
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
}

错误:

损坏或不受支持的文件格式

最佳答案

我想你忘了指定文件。查看您的代码,您只将它指向文件夹,而不是文件本身。我认为这就是为什么它告诉您格式错误,因为它没有以 .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
}

关于Android通过Intent打开pdf文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30410615/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com