I have some pictures stored in the external SD card and I want to show their thumbnails in a GridView. I know that the media scanner has created the thumbnails because I can browse my pictures folder with the standard Gallery application but I don't know where those thumbnails are located so I don't know how to add them to my GridView.
I'm trying to get the thumbnails with:
MediaStore.Images.Thumbnails.getThumbnail(getContentResolver(), Long.parseLong(_imageUri.getLastPathSegment()), type, null)
The _imageUri must be a content-schema Uri so my problem is to find a way of converting the file-schema Uris of my images into content-schema Uris. Unfortunately I don't know how to do it. I've seen lots of SO threads recommending to use Uri.parse() but it just doesn't work so I'm looking for a different solution.
My current approach is to use the media scanner for scanning individual files and try to retrieve the content Uri from the onScanCompleted callback. The code is:
public class SimpleMediaScanner implements MediaScannerConnectionClient {
private MediaScannerConnection mMSC;
private File mFile;
private MyAdapter mAdapter;
public SimpleMediaScanner(Context c, File f, MyAdapter a) {
mAdapter = a;
mFile = f;
mMSC = new MediaScannerConnection(c, this);
mMSC.connect();
}
#Override
public void onMediaScannerConnected() {
mMSC.scanFile(mFile.getAbsolutePath(), null);
}
#Override
public void onScanCompleted(String path, Uri uri) {
// Store the content scheme Uri of the scanned file
// in a public field of the adapter
mAdapter.mThumbUri = uri;
mMSC.disconnect();
}
}
I instantiate this class from my extended SimplecursorAdapter:
SimpleMediaScanner sms = new SimpleMediaScanner(mContext, new File(filepath), this);
Unfortunately the returned mAdapter.mThumbUri value is always null. Could somebody tell me what am I doing wrong? TIA
Have you tried the MediaStorage.Images.Thumbnails class? It provides two static getThumbnail(...) methods that should fulfill your needs.
Related
I am developing an Android app which should display a list of video thumbnails in RecyclerView. A new activity will then play the video for selected thumbnail.
How do I set com.vimeo.networking.model.Picture to Android ImageView?
My code:
mVimeoClient.fetchNetworkContent(VIDEO_URI, new ModelCallback<VideoList>(VideoList.class) {
#Override
public void success(VideoList videoList) {
ArrayList<Video> videoArrayList = videoList.data;
Video video = videoArrayList.get(0);
ArrayList<com.vimeo.networking.model.Picture> arrayListPics = video.pictures.sizes;
// imageView.setImageDrawable((Drawable) pictureAL.get(0));
imageView.setImageBitmap( (Bitmap) arrayListPics.get(0));
}
#Override
public void failure(VimeoError error) {
}
});
}
The setImageBitmap() And setImageDrawable() throws
java.lang.ClassCastException
The Picture object (the one returned from arrayListPics.get(0)) in the vimeo-networking library isn't a Bitmap and therefore can't be cast to one. The Picture object has a field on it called mLink which can be access via Picture#getLink(). This will return a URI string which you then can set on your ImageView.
The simplest code you could use to get this working is:
// The ImageView you want to put the thumbnail in
ImageView yourImageView = <insert your ImageView here>;
// The video whose thumbnail you want
Video yourVideo = <insert your Video here>;
// The collection of `Picture` objects associated with this video.
// Each `Picture` in this "collection" is a different size
PictureCollection yourVideosPictures = yourVideo.getPictures();
// Get the first thumbnail/picture from this collection (not recommended)
Picture videoThumbnailPicture = yourVideosPictures.getPictures().get(0);
// The URI to the image of the thumbnail
String videoThumbnailUri = videoThumbnailPicture.getLink();
// Convert the String URI to an actual URI object
final Uri uri = Uri.parse(videoThumbnailUri);
yourImageView.setImageURI(uri);
I say this is the simplest because there are more things you should do when setting an image uri. One thing is you should base the Picture your grab from yourVideosPictures based on the width of your ImageView so that you're not needlessly pulling down a larger image than you need.
You should also probably not just set the image URI directly onto yourImageView, but instead you should use some image caching library (or some caching implementation).
I'd suggest looking into Picasso, Glide, or Fresco. Or just google "Image caching on Android".
Here's a solution using Glide 4.x.
First of all, import the lib on your project:
implementation 'com.github.bumptech.glide:glide:4.6.1'
Since the Pictures class contains an Uri as the others stated, you can use Glide to download the image for you effortlessly as follows.
// Get your ImageView
ImageView iv = findViewById(R.id.your_image_view);
// Get your thumbnails
ArrayList<com.vimeo.networking.model.Picture> arrayListPics = video.pictures.sizes;
// Load them using Glide
Glide.with(this) // Assuming "this" is your Activity, but you can also use any context here
.load(arrayListPics.get(0).getLink())
.into(iv);
That way it won't matter where is the thumbnail located (Network, file, resources), Glide will load it for you.
You can also apply some transformations or use placeholders by using Glide's RequestOptions class. Read more on how to use it here.
Please user Picasso library to load image in Image-view.
In gradle
implementation 'com.squareup.picasso:picasso:2.71828'
in your adapter class
mVimeoClient.fetchNetworkContent(VIDEO_URI, new ModelCallback<VideoList>(VideoList.class) {
#Override
public void success(VideoList videoList) {
ArrayList<Video> videoArrayList = videoList.data;
Video video = videoArrayList.get(0);
ArrayList<Pictures> arrayListPics = video.pictures.sizes;
Picasso.get().load(arrayListPics.get(0).getpath).into(view);
}
#Override
public void failure(VimeoError error) {
}
});
}
I generate a ImageView in my AndroidLauncher and need to use it in one of my screen classes, so I created an interface. How can I pass that image and use it in my screen class? Do I need to make it into a Bitmap first?
What I got right now is:
Uri selectedImage = data.getData();
selectedImagePath = getPath(selectedImage);
imageView.setImageURI(selectedImage);
and my interface:
public interface purchInterface{
public void getSelectedImage();
}
and in AndroidLauncher:
#Override
public void getSelectedImage() {
imageView.getDrawable();
}
Im in deep water here. Note that I need to be able to draw this Image in my screen class.
You need to return the image encoded in some format from getSelectedImage method. Otherwise your implementation is retrieving the drawable and dropping it immediately.
You should refer to Converting Android Bitmap to LibGdx's Texture
So your interface could be
public interface purchInterface {
public byte[] getSelectedImage();
}
And implementation could be
#Override
public byte[] getSelectedImage() {
// Convert image into bitmap, encode in a byte array.
}
You can call the interface's method and decode the byte array using method described in above question.
Hope this helps.
Good luck.
Use singleton class and store image in it using setter() and later u can use getter ().
Or you convert the image to string using base64 encoding and save it shared preferences or file or database or external storage or pass as intent data to next activity and then decode it to bitmap
I want to save my webview to a PDF file. I know that I can print the WebView with WebView.createPrintDocumentAdapter() and PrintManager.print().
But I need a way to save the PDF, that is generated internally by the PrintDocumentAdapter, directly without any user interactions, because I need the file for further processing inside my app.
Any ideas?
I realise this question is quite old now. But I have just realised how this can be sensibly done.
Essentially as per the question you can use the createPrintDocumentAdapter method mentioned above and pass the result to your own "fake" PrintManager implementation which simply overrides the onWrite method to save the output to your own file. The snippet below shows how to take any PrintDocumentAdapter and send the output from it to a file.
public void print(PrintDocumentAdapter printAdapter, final File path, final String fileName) {
printAdapter.onLayout(null, printAttributes, null, new PrintDocumentAdapter.LayoutResultCallback() {
#Override
public void onLayoutFinished(PrintDocumentInfo info, boolean changed) {
printAdapter.onWrite(null, getOutputFile(path, fileName), new CancellationSignal(), new PrintDocumentAdapter.WriteResultCallback() {
#Override
public void onWriteFinished(PageRange[] pages) {
super.onWriteFinished(pages);
}
});
}
}, null);
}
As you can see there's quite a few nulls passed into the adapters methods but I have checked the Chromium source code and these variables are never used so the nulls are ok.
I created a blog post about how to do it here:
http://www.annalytics.co.uk/android/pdf/2017/04/06/Save-PDF-From-An-Android-WebView/
Create a custom WebViewClient (reference) and set it on your WebView.
In this WebViewClient you should override shouldOverrideUrlLoading (WebView view, String url). From here on you can download the PDF manually when it is clicked.
I have an app for uploading files to a server using php!
How can I implement file browser in my app to select which file to be uploaded! ?
Please give me very simple example ! Or simple solution!
if you need to select any type of file there's no simple solution, you'll have to implement a file manager-similar functionality. Here are some tips and samples to get you started:
prerequisites: your have some basic understanding for how Android works; you know how to implement a custom ListView
use ListView to display the files
parametrize your Adapter with an ArrayList<File>
start with the root of external storage:
File root = Environment
.getExternalStorageDirectory();
the following method will list all files and subdirs in a directory:
public static ArrayList<File> getSubfiles(File root) {
File[] mFiles = root.listFiles();
ArrayList<File> files = new ArrayList<File>();
ArrayList<File> dirs = new ArrayList<File>();
ArrayList<File> allData = new ArrayList<File>();
for (int i = 0; i < myFiles.length; i++) {
if (!myFiles[i].isDirectory()) {
files.add(myFiles[i]);
} else {
dirs.add(myFiles[i]);
}
}
Collections.sort(files);
Collections.sort(dirs);
allData.addAll(dirs);
allData.addAll(files);
return allData;
}
using this method you can move "down" the file system by passing any directory to it. To move up, simply use getParentFile() and pass the result to this method.
So you should always pass the result of this method to your Adapter, calling notifyDataSetChanged() afterwards.
That's all, you have a very basic file viewer. Of course you will need to create some layouts and write a bit more of code, the above tips should help you to get started, since as was already mentioned nobody is going to write half of your app for you here on SO. If you have further questions/problems leave a comment and describe your problem.
There are so many solutions for this on google, and here you can't just ask for a full implementation and expect someone to write it here. Here are a couple of good results:
http://www.dreamincode.net/forums/topic/190013-creating-simple-file-chooser/
http://android-er.blogspot.pt/2010/01/implement-simple-file-explorer-in.html
Basically you will have a list dialog that will search for files and directories on your sdcard, then if it is a file (there are methods in File class to check if it is file or directory for example) then choose it and dismiss the dialog, or if it is a directory, change directory and refresh dialog with list of files and directories and so on.
If you only need to select the file path try the Android-Simple-File-Explorer-Library
First show the file explorer:
Intent intent = new Intent(CONTEXT, SimpleFileExplorerActivity);
startActivityForResult(intent, REQUEST_CODE);
And then receive the result:
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if(data != null){
String selectedAbsolutePath = data.getStringExtra(SimpleFileExplorerActivity.ON_ACTIVITY_RESULT_KEY);
Toast.makeText(CONTEXT, selectedAbsolutePath, Toast.LENGTH_SHORT).show();
}
}
hi
i am developing an android app using an emulator.
i am using a filter class to filter mp3 songs and adding these to a list songs.
class Mp3Filter implements FilenameFilter
{
public boolean accept(File dir, String name)
{
return (name.endsWith(".mp3"));
}
}
public void updateList()
{
File home = new File(MEDIA_PATH);
if (home.listFiles( new Mp3Filter()).length > 0)
{
for (File file : home.listFiles( new Mp3Filter()))
{
songs.add(file.getName());
}
}
}
i want to know is there any order in which new songs gets added in sdcard like
alphabetically or datewise because i am seeing that new songs getting added anywhere
thus each time i am adding any songs i am finding my song list rearranged.
is there any way to get the list of all songs form the sdcard in the order of dates&time
they were added in the card ?
I don't think the File class exposes the creation date, but you could use the lastModified() method to find out when the files were last modified, then sort the list based on that value.