2015-05-23 4 views
0

У меня есть несколько файлов в формате pdf в некоторой папке на SD-карте. Я создал приложение, которое отображает все pdf как ListView. Когда я нажимаю на любой файл в формате PDF дает ошибку в приложении OfficeSuite (UNSUPPORTED испорченного или ФОРМАТ. Что-то не так с кодом. Вот код.Android открыть pdf-файл с помощью Intent

// Код для элементов, отображаемых в 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 
    } 

Ошибка:

формат Коррумпированные или неподдерживаемый файл

+1

Вы пытались их открыть из файла explorer, он работает? –

+0

Да, из приложения OfficeSuite он открывается. –

ответ

1

Я думаю, что вы забыли указать файл. Посмотрите на свой код, вы указали его только в папку, но не файл. Я думаю, что именно поэтому он говорит вам, что он находится в неправильном формате, потому что это не заканчивается в формате .pdf

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

EDIT: Изменить методы в соответствии с вашим комментарием

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 
} 
+0

SOMEFOLDER имеет много PDF. Я создал ListView, в котором все эти pdf-файлы видны. Мне нужно открыть этот файл pdf, щелкнув по нему. Поэтому в этом случае я могу указать конкретный файл. –

+0

Задание определенного имени файла заставит тот же файл открываться снова и снова. Но в моем случае мне нужно открыть файл, который я нажал –

+0

Да, я изменил свой ответ. Вам нужно немного изменить методы, вам нужно получить имя файла, который вы нажали, чтобы передать его в функцию открытого файла. См. Мое редактирование –

Смежные вопросы