Open a selected file (image, pdf, . ) programmatically from my Android Application?

I'm working on an Android application which should be able to open a selected file from a specific folder. I already tried this, but after selecting which application I want to open it, I got this message:

Impossible loading
After trying a lot of thread 1 and thread 2, I use these lines of code to do it:
Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); intent.setDataAndType(Uri.parse("/mnt/sdcard/xxx/xxx/Pictures/xxx.jpg"), "image/*"); myContext.startActivity(intent); 
How can I figure this out? 2,759 1 1 gold badge 30 30 silver badges 46 46 bronze badges asked Oct 17, 2013 at 8:49 1,315 5 5 gold badges 24 24 silver badges 44 44 bronze badges This is a simple and effecting method: indyvision.net/2010/03/android-using-intents-open-files Commented May 12, 2016 at 10:03 Commented Nov 29, 2019 at 13:53

10 Answers 10

Try the below code. I am using this code for opening a PDF file. You can use it for other files also.

File file = new File(Environment.getExternalStorageDirectory(), "Report.pdf"); Uri path = Uri.fromFile(file); Intent pdfOpenintent = new Intent(Intent.ACTION_VIEW); pdfOpenintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); pdfOpenintent.setDataAndType(path, "application/pdf"); try < startActivity(pdfOpenintent); >catch (ActivityNotFoundException e)

If you want to open files, you can change the setDataAndType(path, "application/pdf") . If you want to open different files with the same intent, you can use Intent.createChooser(intent, "Open in. "); . For more information, look at How to make an intent with multiple actions.

1 1 1 silver badge answered Oct 17, 2013 at 9:05 2,759 1 1 gold badge 30 30 silver badges 46 46 bronze badges

Thanks @Ameer for your answer. It's really helpful. So in order to manage all type of file, I replace "application/pdf" by "*/*".

Commented Oct 17, 2013 at 13:30 what about images, or audio, or other file formats @Ameer? Commented Jan 16, 2021 at 18:39

Use this code ,which helped me to open all types of files .

 private void openFile(File url) < try < Uri uri = Uri.fromFile(url); Intent intent = new Intent(Intent.ACTION_VIEW); if (url.toString().contains(".doc") || url.toString().contains(".docx")) < // Word document intent.setDataAndType(uri, "application/msword"); >else if (url.toString().contains(".pdf")) < // PDF file intent.setDataAndType(uri, "application/pdf"); >else if (url.toString().contains(".ppt") || url.toString().contains(".pptx")) < // Powerpoint file intent.setDataAndType(uri, "application/vnd.ms-powerpoint"); >else if (url.toString().contains(".xls") || url.toString().contains(".xlsx")) < // Excel file intent.setDataAndType(uri, "application/vnd.ms-excel"); >else if (url.toString().contains(".zip")) < // ZIP file intent.setDataAndType(uri, "application/zip"); >else if (url.toString().contains(".rar")) < // RAR file intent.setDataAndType(uri, "application/x-rar-compressed"); >else if (url.toString().contains(".rtf")) < // RTF file intent.setDataAndType(uri, "application/rtf"); >else if (url.toString().contains(".wav") || url.toString().contains(".mp3")) < // WAV audio file intent.setDataAndType(uri, "audio/x-wav"); >else if (url.toString().contains(".gif")) < // GIF file intent.setDataAndType(uri, "image/gif"); >else if (url.toString().contains(".jpg") || url.toString().contains(".jpeg") || url.toString().contains(".png")) < // JPG file intent.setDataAndType(uri, "image/jpeg"); >else if (url.toString().contains(".txt")) < // Text file intent.setDataAndType(uri, "text/plain"); >else if (url.toString().contains(".3gp") || url.toString().contains(".mpg") || url.toString().contains(".mpeg") || url.toString().contains(".mpe") || url.toString().contains(".mp4") || url.toString().contains(".avi")) < // Video files intent.setDataAndType(uri, "video/*"); >else < intent.setDataAndType(uri, "*/*"); >intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); > catch (ActivityNotFoundException e) < Toast.makeText(context, "No application found which can open the file", Toast.LENGTH_SHORT).show(); >> 
553 4 4 silver badges 23 23 bronze badges answered Dec 27, 2016 at 9:58 Ameen Maheen Ameen Maheen 2,737 1 1 gold badge 30 30 silver badges 29 29 bronze badges

some advanced tips: perhaps you want to consider to use regex pattern to simplify the if..else condition there.

Commented Apr 8, 2021 at 15:51

and paste the below code in Activity in onCreate method : StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder(); StrictMode.setVmPolicy(builder.build());

Commented Apr 3, 2023 at 15:10

activity_main.xml:

MainActivity.java:

package com.pdffilefromsdcard; import android.Manifest; import android.app.ProgressDialog; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Environment; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.Toast; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class MainActivity extends AppCompatActivity < ListView lv_pdf; public static ArrayListfileList = new ArrayList(); PDFAdapter obj_adapter; public static int REQUEST_PERMISSIONS = 1; boolean boolean_permission; File dir; @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); >private void init() < lv_pdf = (ListView) findViewById(R.id.lv_pdf); dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath()); fn_permission(); lv_pdf.setOnItemClickListener(new AdapterView.OnItemClickListener() < @Override public void onItemClick(AdapterViewadapterView, View view, int i, long l) < Intent intent = new Intent(getApplicationContext(), PdfActivity.class); intent.putExtra(“position”, i); startActivity(intent); Log.e(“Position”, i + “”); >>); > public ArrayList getfile(File dir) < File listFile[] = dir.listFiles(); if (listFile != null && listFile.length >0) < for (int i = 0; i < listFile.length; i++) < if (listFile[i].isDirectory()) < getfile(listFile[i]); >else < boolean booleanpdf = false; if (listFile[i].getName().endsWith(“.pdf”)) < for (int j = 0; j < fileList.size(); j++) < if (fileList.get(j).getName().equals(listFile[i].getName())) < booleanpdf = true; >else < >> if (booleanpdf) < booleanpdf = false; >else < fileList.add(listFile[i]); >> > > > return fileList; > private void fn_permission() < if ((ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) < if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE))) < >else < ActivityCompat.requestPermissions(MainActivity.this, new String[], REQUEST_PERMISSIONS); > > else < boolean_permission = true; getfile(dir); obj_adapter = new PDFAdapter(getApplicationContext(), fileList); lv_pdf.setAdapter(obj_adapter); >> @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) < super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == REQUEST_PERMISSIONS) < if (grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) < boolean_permission = true; getfile(dir); obj_adapter = new PDFAdapter(getApplicationContext(), fileList); lv_pdf.setAdapter(obj_adapter); >else < Toast.makeText(getApplicationContext(), “Please allow the permission”, Toast.LENGTH_LONG).show(); >> > > 

activity_pdf.xml:

PdfActivity.java:

package com.pdffilefromsdcard; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.util.Log; import com.github.barteksc.pdfviewer.PDFView; import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener; import com.github.barteksc.pdfviewer.listener.OnPageChangeListener; import com.github.barteksc.pdfviewer.scroll.DefaultScrollHandle; import com.shockwave.pdfium.PdfDocument; import java.io.File; import java.util.List; public class PdfActivity extends AppCompatActivity implements OnPageChangeListener,OnLoadCompleteListener < PDFView pdfView; Integer pageNumber = 0; String pdfFileName; String TAG=”PdfActivity”; int position=-1; @Override protected void onCreate(@Nullable Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_pdf); init(); >private void init() < pdfView= (PDFView)findViewById(R.id.pdfView); position = getIntent().getIntExtra(“position”,-1); displayFromSdcard(); >private void displayFromSdcard() < pdfFileName = MainActivity.fileList.get(position).getName(); pdfView.fromFile(MainActivity.fileList.get(position)) .defaultPage(pageNumber) .enableSwipe(true) .swipeHorizontal(false) .onPageChange(this) .enableAnnotationRendering(true) .onLoad(this) .scrollHandle(new DefaultScrollHandle(this)) .load(); >@Override public void onPageChanged(int page, int pageCount) < pageNumber = page; setTitle(String.format(“%s %s / %s”, pdfFileName, page + 1, pageCount)); >@Override public void loadComplete(int nbPages) < PdfDocument.Meta meta = pdfView.getDocumentMeta(); printBookmarksTree(pdfView.getTableOfContents(), “-“); >public void printBookmarksTree(List tree, String sep) < for (PdfDocument.Bookmark b : tree) < Log.e(TAG, String.format(“%s %s, p %d”, sep, b.getTitle(), b.getPageIdx())); if (b.hasChildren()) < printBookmarksTree(b.getChildren(), sep + “-“); >> > >