How to use file browser in android - android

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

Related

Java/Android Displaying .apk files as files but with their icons

I am building a root app allowing to debloat apk files from system/app and system/priv app. I have a ListView that takes the content of both dirs and filters them against a string array that I built (not all apps can be debloated). It feeds into a list with multiple choice mode.
Now, what I can't manage is how to display apk files with their icons.
I am using a simple adapter for now. But I can switch to base adapter. What I need is a way to add the app icons into the Image View.
I am not using the package manager to generate the list, for several reasons I need it to be the actual apk files that are displayed.
Can someone please help me with a way to make an apk file display with it's icon? Like in root explorer f.e.?
This is the main part of code that takes care of the list for now:
public class MainActivity extends ListActivity
implements View.OnClickListener,
AdapterView.OnItemSelectedListener{
private List<String> fileList = new ArrayList<String>();
Button debloat;
ListView appList;
File app = new File("/system/app");
File privApp = new File("/system/priv-app");
ArrayAdapter<String> directoryList;
BufferedWriter debloatBW;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
Runtime.getRuntime().exec("su");
} catch (IOException e) {
e.printStackTrace();
}
setContentView(R.layout.activity_main);
debloat = (Button) findViewById(R.id.button);
debloat.setOnClickListener(this);
appList = getListView();
File[] files = app.listFiles();
File[] files1 = privApp.listFiles();
List<String> relevantApps =
Arrays.asList(getResources().getStringArray(R.array.include_apk));
fileList.clear();
for (File file : files){
if (file.isFile()
&& file.getPath().endsWith(".apk")
&& relevantApps.contains(file.getName().toString()))
{
fileList.add(file.getName());
}
}
for (File file1 : files1) {
if (file1.isFile()
&& file1.getPath().endsWith(".apk")
&& relevantApps.contains(file1.getName().toString()))
{
fileList.add(file1.getName());
}
}
directoryList = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, fileList);
appList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
appList.setAdapter(directoryList);
}
Thank you for any advice you might have!
Cheers!
I recommend creating your own custome adapter in which you inflate the row as usuala and then set the text, to get the icon of the package with the help of this post Get Apk Icon and set it to the ImageView in the row. How to create a custome adapter you find out bets with this tutorial Using Android ListView.

Save PDF from Webview on Android

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.

Android Data Backup: dynamic file list with BackupAgentHelper

I want to backup my internal files. These are created by My App: random number of files and random names. Like data1.xml, data7,xml, data13.xml, ....
So I do not have any fixed file list.
When MyBackupAgentHelper::onCreate is running before the onBackup(), I can easily provide the filenames by querying the files getApplicationContext().fileList();
public class MyBackupAgentHelper extends BackupAgentHelper
{
#Override
public void onCreate()
{
String[] files = getApplicationContext().fileList();
FileBackupHelper helper = new FileBackupHelper(this, files );
addHelper(FILES_BACKUP_KEY, helper);
}
...
However, if the onRestore is ready to run after an uninstall/re-install, I cannot provide the filenames in the onCreate as this time the getApplicationContext().fileList() returns empty list - obviously.
So nothing is restored :(
Is there any way to restore all files which were backuped without specifying the filenames? Just saying, "do it all".
If not, how could I use the Data Backup in this scenario?
Thanks
I just ran into the same problem. It's frustrating because FileBackupHelper does almost exactly what we want it to do.
If you look at the code for FileBackupHelper's restoreEntity function here
https://android.googlesource.com/platform/frameworks/base.git/+/android-4.2.2_r1/core/java/android/app/backup/FileBackupHelper.java
public void restoreEntity(BackupDataInputStream data) {
if (DEBUG) Log.d(TAG, "got entity '" + data.getKey() + "' size=" + data.size());
String key = data.getKey();
if (isKeyInList(key, mFiles)) {
File f = new File(mFilesDir, key);
writeFile(f, data);
}
}
...you can see that the only reason the files aren't being written is because they're not in the list that you passed to the FileBackupHelper constructor.
My first solution was to override isKeyInList to always return true. And that actually worked, but then it struck me as odd because isKeyInList has default protection and my FileBackupHelper subclass is not in the same package. It turns out this is some sort dalvik vm bug that allows this so I wouldn't want to rely on it (see Android method with default (package) visibility overriding (shouldn't work, but does - why?) )
But then I realized I could just hold on to the array of files that I passed to the FileBackupHelper constructor and then change the first element to always be the name of the file that wanted to be created. That way it would always be found in the list.
class MyFileBackupHelper extends FileBackupHelper
{
String[] mMyFiles;
MyFileBackupHelper(Context context, String... files)
{
super(context,files);
mMyFiles = files;
}
/* boolean isKeyInList(String key, String[] list)
{
return true;
} */
public void restoreEntity(BackupDataInputStream data)
{
mMyFiles[0] = data.getKey();
super.restoreEntity(data);
}
}
Of course this also relies on FileBackupHelper keeping the same implementation where it doesn't make a copy of the Files list. I'm not exactly sure why they went to so much trouble to prevent restoring arbitrary files, and maybe they'll try to thwart this solution later. But for now, I'm calling it good!
Oh yeah, one extra detail to making my solution work is that you need to make sure there's always one file in the list when you're restoring. That way there will always be an array element 0 to replace. This is what I did in my BackupAgent
public class MyBackupAgent extends BackupAgentHelper
{
public void AddFileHelper(String files[])
{
FileBackupHelper aHelper = new MyFileBackupHelper(this,files);
addHelper("userfiles", aHelper);
}
#Override
public void onBackup(ParcelFileDescriptor oldState, BackupDataOutput data, ParcelFileDescriptor newState) throws IOException
{
String[] anArray = GetAllUserFiles(); // I'm not including this function for brevity
AddFileHelper(anArray);
super.onBackup(oldState, data, newState);
}
#Override
public void onRestore(BackupDataInput data, int appVersionCode, ParcelFileDescriptor newState) throws IOException
{
AddFileHelper(new String[] { "filename" } );
super.onRestore(data, appVersionCode, newState);
}
}
So you see that I don't rely on onCreate(). Instead I put the correct files in the list in onBackup and I just put one filename in the list in onRestore. Then MyFileBackupHelper replaces array element 0 in that list every time before calling the parent restoreEntity. Hopefully google will let this solution continue to work in future version of their libraries since it seems like a nice feature to have!
EDIT: You cannot backup folders - you need to individually list files in the file helper to backup those.
I realize this question is quite old, but I was running into a similar problem (wanting to back up an arbitrary set of files from a folder), and my solution was to take all of the files, and put them into a zip file, and the have the FileBackupHelper backup the zip file. For onRestore, after the .zip file gets restored, I extract the files back. This may not be the best solution, but it seems to work for me.

Get content-scheme Uri of an image via MediaScannerConnectionClient

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.

getting list of mp3 files from a sdcard in the order they were added in the card

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.

Categories

Resources