Can't Open a File Using Intent - android

What I am trying to do here is that. I locate the Pdf file folder in my SD Card and click the file and it complete action using Adobe Reader. I successfully done the read SD card option and it shows all pdf file in layout as a gridview. But when I click the pdf file it opens Adobe reader but can't open the file. It says "The document can't be opened because it's not a valid pdf doc". Here is my Code-
Here is the code for locating File & folder in SD card
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState)
{
View view =inflater.inflate(R.layout.magica_pdf_layout, container, false);
// Check for SD Card
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
{
Toast.makeText(PdfFragment.this.getActivity(), "Error! No SDCARD Found!", Toast.LENGTH_LONG).show();
}
else
{
// Locate folder in your SD Card
file = new File(Environment.getExternalStorageDirectory()+ File.separator + "Book");
// Create a new folder if no folder named exist
file.mkdirs();
}
here is the part for onclick method
// Capture gridview item click
grid.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id)
{
// get clicked file name from gridview
String pdfname=(String)parent.getItemAtPosition(position);
//prepare pdf file url
selectedFile = new File(file.getAbsolutePath()+File.separator +pdfname+".pdf");
Intent pdfIntent = new Intent();
pdfIntent.setAction(android.content.Intent.ACTION_VIEW);
pdfIntent.setDataAndType(Uri.fromFile(selectedFile), "application/pdf");
startActivity(pdfIntent);
}
});

The document can't be opened because it's not a valid pdf doc
Because you are not passing pdf file path, currently passing only folder path in which all files are present. do it as:
#Override
public void onItemClick(AdapterView<?> parent,
View view,int position, long id)
{
// get clicked file name from gridview
String pdfname=(String)parent.getItemAtPosition(position);
// prepare pdf file url
File selectedFile = new File(file.getAbsolutePath()+"/"+pdfname+".pdf");
Intent pdfIntent = new Intent();
pdfIntent.setAction(android.content.Intent.ACTION_VIEW);
pdfIntent.setDataAndType(Uri.fromFile(selectedFile), "application/pdf");
startActivity(pdfIntent);
}

Related

Passing a file URI from sdcard to an ACTION_VIEW Intent

I'm updating one of my apps for Android 6 and above. The app lets you attach a file to its data to provide further information. This can be an Image from taken in-app with the camera, and Image from the gallery, or a random file from the file system. I have a ListView that shows the attached files and their metadata and with onItemClick I want to show them to the user. I used to get the URI for that file with
Uri.fromFile(f)
but this is no longer supported as I understand it. Now my code looks like this
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
doc = getItem(arg2);
File f = doc.getFile(context);
if (f.exists()) {
Intent myIntent = new Intent(Intent.ACTION_VIEW);
myIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
String mime = "";
try {
Uri uri = FileProvider.getUriForFile(context, android.support.v4.BuildConfig.APPLICATION_ID + ".provider", f);
mime = URLConnection.guessContentTypeFromStream(new FileInputStream(f));
if (mime == null) mime = URLConnection.guessContentTypeFromName(f.getName());
myIntent.setDataAndType(uri, mime);
context.startActivity(myIntent);
} catch (Exception e) {
e.printStackTrace();
}
} else {
//Error handling
}
}
This works fine with files on the phone storage. But since FileProvider does not work with files on mountable storage, it will throw an Exception. My question is: how do I get the file URI without using FileProvider?

I am downloading pdf's to internal storage but my pdf viewer can not find them

I download a pdf file to internal storage and then programmatically create buttons that take them to an action view. I can listFiles[] and Toast that they are there but the pdf viewer says file does not exist or file can not be viewed.
These are the main components of the write to internal storage during download.
private File file;
file = new File(mContext.getFilesDir(), filename+".pdf");
// Output stream to write file in internal storage
OutputStream output = new BufferedOutputStream(new FileOutputStream(file));
Then in another activity I get the filenames from the database and create a table with buttons
// ....Inside a for loop .....
Button c3 = new Button(this);
c3.setText("view");
c3.setId(p.getPosterID());
c3.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
File pdfFile = getBaseContext().getFileStreamPath(filename+".pdf");
if (pdfFile.exists()){
Uri path = Uri.fromFile(pdfFile);
//================================================================================
Log.d("path: ", path.toString());
//this will log: file:///data/data/com.myapp.posterviewer/files/5453b54b83b5f.pdf
//================================================================================
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try{
startActivity(pdfIntent);
}
catch(ActivityNotFoundException e){
Toast.makeText(ListPosters.this, "No Application Available", Toast.LENGTH_LONG).show();
}
}
else{
Toast.makeText(ListPosters.this, "The file does not exist", Toast.LENGTH_LONG).show();
}
}
});
Am I generating the path right with Uri path?
I am not able to see the files from windows explorer when in the app folder either.
But all my checks say file is exists and I thought that would be in the app root folder.
Internal Storage Only Visible to your Application. The OutSide Application(Pdf Viewer) Cannot Access it. Save you Pdf file in External Storage and then open it via Pdf Viewer

Making a GridView take images from a specific folder

I am a newbie to android app making and I am still a beginner with a little knowledge . I have been trying to make an android app that works like a gallery , but it only displays images under a specific folder. For the UI , I am starting with only a GridView (or TwoWayGridView which is derived from the latter) , and have been trying to let this GridView take its contents from this folder .
I have made this folder and copied an image to it for testing and failed. No image was displayed .Plus I am not very familiar with Cursors and ListAdapters . Somethings that I'm sure that are correct are permissions , manifest , and layout of the activity.Moreover , I believe my problem is around URIs . Please check my code below :
Some namings:
Uri contentUri;
Cursor mImageCursor;
TwoWayGridView mImageGrid;
ListAdapter mAdapter;
String sdCard = Environment.getExternalStorageDirectory().getAbsolutePath();
onCreate method :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery);
File motherDirectory = new File(sdCard+"/Favory");
if(!motherDirectory.exists()){
motherDirectory.mkdir();
}
MediaScannerConnection.scanFile(this, new String[]{motherDirectory.getAbsolutePath()} ,null, new MediaScannerConnection.OnScanCompletedListener() {
#Override
public void onScanCompleted(String path, Uri uri) {
// TODO Auto-generated method stub
contentUri = uri ;
initGrid(uri);
}
});
}
initGrid(Uri) method :
private void initGrid(Uri folderUri) {
mImageCursor = this.getContentResolver().query(folderUri,
ImageThumbnailAdapter.IMAGE_PROJECTION, null, null,
MediaStore.Images.ImageColumns.DISPLAY_NAME);
mImageGrid = (TwoWayGridView) findViewById(R.id.gridview);
mAdapter = new ImageThumbnailAdapter(this, mImageCursor);
mImageGrid.setAdapter(mAdapter);
mImageGrid.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(TwoWayAdapterView<?> parent, View v, int position, long id) {
Log.i(TAG, "showing image: " + mImageCursor.getString(ImageThumbnailAdapter.IMAGE_NAME_COLUMN));
Uri uri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
}
Thanks for your help , and please if there is an easier alternative way of doing this tell me, I care for the results more than the methods now . If you need anything or any more information please tell me in the comments below . Thanks again !
To Read the Files of a folder you can use this function ( from this post ):
String directoryName = Environment.getExternalStorageDirectory().toString()+"/YourFolder/";
public ArrayList<File> listf(String directoryName, ArrayList<File> files) {
File directory = new File(directoryName);
// get all the files from a directory
File[] fList = directory.listFiles();
for (File file : fList) {
Log.e("path : "," "+file);
if (file.isFile()) {
files.add(file);
} else if (file.isDirectory()) {
listf(file.getAbsolutePath(), files);
}
}
return files;
}
Then you should load this list of files to your GridView Adapter, i suggest you use Universal Image Loader
You just give your file path and Adapter ImageVIew at that position
loadImageUtil.loadBitmapToImageView(imageView, youArrayList.get(position));
For more informations how to use this library you can see examples, there is an example with grid view gridView

Android: display every image from a specific directory

Am am trying to work with this tutorial here which loads every image on the device into a grid view, but im not sure how to modify it to just display images from one particular directory in external storage.
Get the folder content with folder.listFiles() and create an Uri from every entry.
String folderName="Photos";
ArrayList<Uri> images = new ArrayList<Uri>();
File folder = new File(Environment.getExternalStorageDirectory() + File.separator
+ folderName);
File[] files = folder.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String filename) {
return filename.endsWith(".jpg") || filename.endsWith(".png");
}
});
for (File file : files) {
images.add(Uri.parse(file.getAbsolutePath()));
}
Then you could use the array list with uris to pass it to the adapter.

How can I get video thumbnails from R.raw folder?

The code below can not get the video thumbnails of videos which were located in R.raw folder.
I want to use a gallery to show the thumbnails of videos. Videos were put into R.raw folder (actually I'm new to Android, so I don't really know where to put these videos, so I put them in R.raw folder). Now I want to get the thumbnails of the videos. But someone told that thumbnails can only be got from the SD card. So is it true? And what should I do next? Thanks.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Gallery gallery = (Gallery) findViewById(R.id.gallery);
final String[] videoFileList = new String[] { "R.raw.01", "R.raw.02" };
BaseAdapter adapter = new BaseAdapter() {
public int getCount() {
return videoFileList.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(Select.this);
Bitmap bmThumbnail;
bmThumbnail = ThumbnailUtils.createVideoThumbnail("android.resource://" + getPackageName() + "/"
+ videoFileList[position], Thumbnails.MINI_KIND);
System.out.println(videoFileList[position]);
imageView.setImageBitmap(bmThumbnail);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
TypedArray typedArray = obtainStyledAttributes(R.styleable.Gallery);
imageView.setBackgroundResource(typedArray.getResourceId(
R.styleable.Gallery_android_galleryItemBackground, 0));
return imageView;
}
};
gallery.setAdapter(adapter);
gallery.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(Select.this, Play.class);
intent.putExtra("image", videoFileList[position]);
startActivity(intent);
Select.this.finish();
}
public void onNothingClick(AdapterView<?> parent) {
}
});
}
On Android 5, createVideoThumbnail() always returned null when asking for the thumbnail of a video in resources. Here's what worked for me in the end:
Uri videoURI = Uri.parse("android.resource://" + getActivity().getPackageName() + "/raw/animation");
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
retriever.setDataSource(getActivity().getApplicationContext(), videoURI);
Bitmap thumb = retriever.getFrameAtTime(10, MediaMetadataRetriever.OPTION_PREVIOUS_SYNC);
videoView.setBackground(new BitmapDrawable(getResources(), thumb));
Have you looked at, createVideoThumbnail() from ThumbnailUtils Class?
Actually, Your video files are in resource/raw directory so you have to create Thumbnails for it.
If your video files are in External Storage then Android Media Store itself creates for you. And you can get it by MediaStore.Video.Thumbnails Class.
Video on res/raw folder of your application isn't managed by Android Media Content Provider, so you cannot obtain their thumbnail from it.
Alternatively, you can try to save them as normal file in your SD and, then, ask to media provider for thumbnail or create it directly via ThumbnailUtils.createVideoThumbnail class (only Android 2.2 or above)

Categories

Resources