How to implement Export sqlite To excel/csv file in android? - android

I am developing android app where SQlite as a database.I want to export certain result from DB in to excel file format programatically, want to store that excel to local device path
I have come across following links
SQlite database programmatically convert into Excel file format in Android
Android - Generate CSV file from table values
android exporting to csv and sending as email attachment
So what is exact procedure to implement Export to Excel for android apps ?

Guys here is answer that I have implemented successfully
//new async task for file export to csv
private class ExportDatabaseCSVTask extends AsyncTask<String, String, Boolean> {
private final ProgressDialog dialog = new ProgressDialog(SearchResultActivity.this);
boolean memoryErr = false;
// to show Loading dialog box
#Override
protected void onPreExecute() {
this.dialog.setMessage("Exporting database...");
this.dialog.show();
}
// to write process
protected Boolean doInBackground(final String... args) {
boolean success = false;
String currentDateString = new SimpleDateFormat(Constants.SimpleDtFrmt_ddMMyyyy).format(new Date());
File dbFile = getDatabasePath("HLPL_FRETE.db");
Log.v(TAG, "Db path is: " + dbFile); // get the path of db
File exportDir = new File(Environment.getExternalStorageDirectory() + File.separator + Constants.FileNm.FILE_DIR_NM, "");
long freeBytesInternal = new File(getApplicationContext().getFilesDir().getAbsoluteFile().toString()).getFreeSpace();
long megAvailable = freeBytesInternal / 1048576;
if (megAvailable < 0.1) {
System.out.println("Please check"+megAvailable);
memoryErr = true;
}else {
exportDirStr = exportDir.toString();// to show in dialogbox
Log.v(TAG, "exportDir path::" + exportDir);
if (!exportDir.exists()) {
exportDir.mkdirs();
}
try {
List<SalesActivity> listdata = salesLst;
SalesActivity sa = null;
String lob = null;
for (int index = 0; index < listdata.size();) {
sa = listdata.get(index);
lob = sa.getLob();
break;
}
if (Constants.Common.OCEAN_LOB.equals(lob)) {
file = new File(exportDir, Constants.FileNm.FILE_OFS + currentDateString + ".csv");
} else {
file = new File(exportDir, Constants.FileNm.FILE_AFS + currentDateString + ".csv");
}
file.createNewFile();
CSVWriter csvWrite = new CSVWriter(new FileWriter(file));
// this is the Column of the table and same for Header of CSV
// file
if (Constants.Common.OCEAN_LOB.equals(lob)) {
csvWrite.writeNext(Constants.FileNm.CSV_O_HEADER);
}else{
csvWrite.writeNext(Constants.FileNm.CSV_A_HEADER);
}
String arrStr1[] = { "SR.No", "CUTSOMER NAME", "PROSPECT", "PORT OF LOAD", "PORT OF DISCHARGE" };
csvWrite.writeNext(arrStr1);
if (listdata.size() > 0) {
for (int index = 0; index < listdata.size(); index++) {
sa = listdata.get(index);
String pol;
String pod;
if (Constants.Common.OCEAN_LOB.equals(sa.getLob())) {
pol = sa.getPortOfLoadingOENm();
pod = sa.getPortOfDischargeOENm();
} else {
pol = sa.getAirportOfLoadNm();
pod = sa.getAirportOfDischargeNm();
}
int srNo = index;
String arrStr[] = { String.valueOf(srNo + 1), sa.getCustomerNm(), sa.getProspectNm(), pol, pod };
csvWrite.writeNext(arrStr);
}
success = true;
}
csvWrite.close();
} catch (IOException e) {
Log.e("SearchResultActivity", e.getMessage(), e);
return success;
}
}
return success;
}
// close dialog and give msg
protected void onPostExecute(Boolean success) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
if (success) {
dialogBox(Constants.Flag.FLAG_EXPRT_S);
} else {
if (memoryErr==true) {
dialogBox(Constants.Flag.FLAG_MEMORY_ERR);
} else {
dialogBox(Constants.Flag.FLAG_EXPRT_F);
}
}
}
}

this is my answer: And this works !
Excel file is the same as a .csv file.
Step 1: download this jar file https://code.google.com/p/opencsv/downloads/detail?name=opencsv-2.4.jar&can=2&q=
Step 2:
private class ExportDatabaseCSVTask extends AsyncTask<String ,String, String>{
private final ProgressDialog dialog = new ProgressDialog(MainActivity.this);
#Override
protected void onPreExecute() {
this.dialog.setMessage("Exporting database...");
this.dialog.show();
}
protected String doInBackground(final String... args){
File exportDir = new File(Environment.getExternalStorageDirectory(), "");
if (!exportDir.exists()) {
exportDir.mkdirs();
}
File file = new File(exportDir, "ExcelFile.csv");
try {
file.createNewFile();
CSVWriter csvWrite = new CSVWriter(new FileWriter(file));
//data
ArrayList<String> listdata= new ArrayList<String>();
listdata.add("Aniket");
listdata.add("Shinde");
listdata.add("pune");
listdata.add("anything#anything");
//Headers
String arrStr1[] ={"First Name", "Last Name", "Address", "Email"};
csvWrite.writeNext(arrStr1);
String arrStr[] ={listdata.get(0), listdata.get(1), listdata.get(2), listdata.get(3)};
csvWrite.writeNext(arrStr);
csvWrite.close();
return "";
}
catch (IOException e){
Log.e("MainActivity", e.getMessage(), e);
return "";
}
}
#SuppressLint("NewApi")
#Override
protected void onPostExecute(final String success) {
if (this.dialog.isShowing()){
this.dialog.dismiss();
}
if (success.isEmpty()){
Toast.makeText(MainActivity.this, "Export successful!", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(MainActivity.this, "Export failed!", Toast.LENGTH_SHORT).show();
}
}
}
Write Async task in your .java file
Step3: Add call this task
ExportDatabaseCSVTask task=new ExportDatabaseCSVTask();
task.execute();
ExcelFile.csv file will be created in your sdcard.

ExportDatabaseCSVTask:
public class ExportDatabaseCSVTask extends AsyncTask<String, Void, Boolean> {
private final ProgressDialog dialog = new ProgressDialog(MainActivity.this);
#Override
protected void onPreExecute() {
this.dialog.setMessage("Exporting database...");
this.dialog.show();
}
protected Boolean doInBackground(final String... args) {
String currentDBPath = "/data/"+ "your Package name" +"/databases/abc.db";
File dbFile = getDatabasePath(""+currentDBPath);
System.out.println(dbFile); // displays the data base path in your logcat
File exportDir = new File(Environment.getExternalStorageDirectory(), "/your Folder Name/");
if (!exportDir.exists()) { exportDir.mkdirs(); }
File file = new File(exportDir, "myfile.csv");
try {
file.createNewFile();
CSVWriter csvWrite = new CSVWriter(new FileWriter(file));
Cursor curCSV = simpledb.rawQuery("select * from " + tablename,null);
csvWrite.writeNext(curCSV.getColumnNames());
while(curCSV.moveToNext()) {
String arrStr[]=null;
String[] mySecondStringArray = new String[curCSV.getColumnNames().length];
for(int i=0;i<curCSV.getColumnNames().length;i++)
{
mySecondStringArray[i] =curCSV.getString(i);
}
csvWrite.writeNext(mySecondStringArray);
}
csvWrite.close();
curCSV.close();
return true;
} catch (IOException e) {
Log.e("MainActivity", e.getMessage(), e);
return false;
}
}
protected void onPostExecute(final Boolean success) {
if (this.dialog.isShowing()) { this.dialog.dismiss(); }
if (success) {
Toast.makeText(MainActivity.this, "Export successful!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Export failed", Toast.LENGTH_SHORT).show();
}
}
}
CSVWriter:
public class CSVWriter {
private PrintWriter pw;
private char separator;
private char quotechar;
private char escapechar;
private String lineEnd;
/** The character used for escaping quotes. */
public static final char DEFAULT_ESCAPE_CHARACTER = '"';
/** The default separator to use if none is supplied to the constructor. */
public static final char DEFAULT_SEPARATOR = ',';
/**
* The default quote character to use if none is supplied to the
* constructor.
*/
public static final char DEFAULT_QUOTE_CHARACTER = '"';
/** The quote constant to use when you wish to suppress all quoting. */
public static final char NO_QUOTE_CHARACTER = '\u0000';
/** The escape constant to use when you wish to suppress all escaping. */
public static final char NO_ESCAPE_CHARACTER = '\u0000';
/** Default line terminator uses platform encoding. */
public static final String DEFAULT_LINE_END = "\n";
/**
* Constructs CSVWriter using a comma for the separator.
*
* #param writer
* the writer to an underlying CSV source.
*/
public CSVWriter(Writer writer) {
this(writer, DEFAULT_SEPARATOR, DEFAULT_QUOTE_CHARACTER,
DEFAULT_ESCAPE_CHARACTER, DEFAULT_LINE_END);
}
/**
* Constructs CSVWriter with supplied separator, quote char, escape char and line ending.
*
* #param writer
* the writer to an underlying CSV source.
* #param separator
* the delimiter to use for separating entries
* #param quotechar
* the character to use for quoted elements
* #param escapechar
* the character to use for escaping quotechars or escapechars
* #param lineEnd
* the line feed terminator to use
*/
public CSVWriter(Writer writer, char separator, char quotechar, char escapechar, String lineEnd) {
this.pw = new PrintWriter(writer);
this.separator = separator;
this.quotechar = quotechar;
this.escapechar = escapechar;
this.lineEnd = lineEnd;
}
/**
* Writes the next line to the file.
*
* #param nextLine
* a string array with each comma-separated element as a separate
* entry.
*/
public void writeNext(String[] nextLine) {
if (nextLine == null)
return;
StringBuffer sb = new StringBuffer();
for (int i = 0; i < nextLine.length; i++) {
if (i != 0) {
sb.append(separator);
}
String nextElement = nextLine[i];
if (nextElement == null)
continue;
if (quotechar != NO_QUOTE_CHARACTER)
sb.append(quotechar);
for (int j = 0; j < nextElement.length(); j++) {
char nextChar = nextElement.charAt(j);
if (escapechar != NO_ESCAPE_CHARACTER && nextChar == quotechar) {
sb.append(escapechar).append(nextChar);
} else if (escapechar != NO_ESCAPE_CHARACTER && nextChar == escapechar) {
sb.append(escapechar).append(nextChar);
} else {
sb.append(nextChar);
}
}
if (quotechar != NO_QUOTE_CHARACTER)
sb.append(quotechar);
}
sb.append(lineEnd);
pw.write(sb.toString());
}
/**
* Flush underlying stream to writer.
*
* #throws IOException if bad things happen
*/
public void flush() throws IOException {
pw.flush();
}
/**
* Close the underlying stream writer flushing any buffered content.
*
* #throws IOException if bad things happen
*
*/
public void close() throws IOException {
pw.flush();
pw.close();
}
}

I have recently implemented the excel export function in my app. I have also included my full code on how to export filtered data to excel instead of the whole table.
You will need to create a second table for this. The second that will hold the data you require for this operation (In my second table I have removed my autoincrament ID column because I dont want it in my excel file).
You will need to clear the second table first and then add entries.
Then use the SqLiteToExcel object to export db to excel and save the file somewhere.
Then I have an email intent with the excel file attached for sharing (allows sharing with other apps other than email). here is my method:
private void ExportData() {
//CHECK IF YOU HAVE WRITE PERMISSIONS OR RETURN
int permission = ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(getContext(), "Storage permissions not granted", Toast.LENGTH_SHORT).show();
return;
}
//get database object
myDbhelper = new MyDbHelper(getContext());
SQLiteDatabase database = myDbhelper.getWritableDatabase();
//delete all entries in the second table
database.delete("Table2",null,null);
//Create a cursor of the main database with your filters and sort order applied
Cursor cursor = getActivity().getContentResolver().query(
uri,
projections,
selection,
args,
sortOrder);
//loop through cursor and add entries from first table to second table
try {
while (cursor.moveToNext()) {
final String ColumnOneIndex = cursor.getString(cursor.getColumnIndexOrThrow("COLUMN_ONE"));
final String ColumnTwoIndex = cursor.getString(cursor.getColumnIndexOrThrow("COLUMN_TWO"));
final String ColumnThreeIndex = cursor.getString(cursor.getColumnIndexOrThrow("COLUMN_THREE"));
//add entries from table one into the table two
ContentValues values = new ContentValues();
values.put("TABLE2_COLUMN_1", ColumnOneIndex);
values.put("TABLE2_COLUMN_2", ColumnTwoIndex );
values.put("TABLE2_COLUMN_3", ColumnThreeIndex);
database.insert("table2", null, values);
}
} finally {
//close cursor after looping is complete
cursor.close();
}
//create a string for where you want to save the excel file
final String savePath = Environment.getExternalStorageDirectory() + "/excelfileTemp";
File file = new File(savePath);
if (!file.exists()) {
file.mkdirs();
}
//create the sqLiteToExcel object
SQLiteToExcel sqLiteToExcel = new SQLiteToExcel(getContext(), "databasefile.db",savePath);
//use sqLiteToExcel object to create the excel file
sqLiteToExcel.exportSingleTable("table2","excelfilename.xls", new SQLiteToExcel.ExportListener() {
#Override
public void onStart() {
}
#Override
public void onCompleted(String filePath) {
//now attach the excel file created and be directed to email activity
Uri newPath = Uri.parse("file://" + savePath + "/" +"excelfilename.xls");
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
Intent emailintent = new Intent(Intent.ACTION_SEND);
emailintent.setType("application/vnd.ms-excel");
emailintent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
emailintent.putExtra(Intent.EXTRA_TEXT, "I'm email body.");
emailintent.putExtra(Intent.EXTRA_STREAM,newPath);
startActivity(Intent.createChooser(emailintent, "Send Email"));
}
#Override
public void onError(Exception e) {
System.out.println("Error msg: " + e);
Toast.makeText(getContext(), "Failed to Export data", Toast.LENGTH_SHORT).show();
}
});
}
I have this method implemented in my app and it works

The CSV format is "string, string, string /n" for each line,
the "," is the column separator and "/n" for rows.
Get the data from the database and export them like this:
public static Boolean exportToCSV(List<Data> data, File file) {
try {
final String head = "ValueX, ValueY \n";
if (!file.exists()) {
file.createNewFile();
}
FileWriter fileWriter = new FileWriter(file.getAbsoluteFile());
BufferedWriter writer = new BufferedWriter(fileWriter);
writer.write(head);
for (Item item : items) {
final String line = String.format("%s,%s\n",
item.getValueX(),
item.getValueY());
writer.write(line);
}
writer.close();
} catch (IOException e) {
return false;
}
return true;
}

Related

Speeding up the doinbackground() process

I'm splitting an encrypted video into 4 parts using this code
public class SplitVideoFile {
private static String result;
static ArrayList<String>update=new ArrayList<>();
public static String main(File file) {
try {
// File file = new File("C:/Documents/Despicable Me 2 - Trailer (HD) - YouTube.mp4");//File read from Source folder to Split.
if (file.exists()) {
String videoFileName = file.getName().substring(0, file.getName().lastIndexOf(".")); // Name of the videoFile without extension
// String path = Environment.getDataDirectory().getAbsolutePath().toString() + "/storage/emulated/0/Videointegrity";
String path = "/storage/emulated/0/Videointegrity";
// File myDir = new File(getFile, "folder");
//myDir.mkdir();
File splitFile = new File(path.concat("/").concat(videoFileName));//Destination folder to save.
if (!splitFile.exists()) {
splitFile.mkdirs();
Log.d("Directory Created -> ", splitFile.getAbsolutePath());
}
int i = 01;// Files count starts from 1
InputStream inputStream = new FileInputStream(file);
String videoFile = splitFile.getAbsolutePath() +"/"+ String.format("%02d", i) +"_"+ file.getName();// Location to save the files which are Split from the original file.
OutputStream outputStream = new FileOutputStream(videoFile);
Log.d("File Created Location: ", videoFile);
update.add("File Created Location: ".concat(videoFile));
int totalPartsToSplit =4 ;// Total files to split.
int splitSize = inputStream.available() / totalPartsToSplit;
int streamSize = 0;
int read = 0;
while ((read = inputStream.read()) != -1) {
if (splitSize == streamSize) {
if (i != totalPartsToSplit) {
i++;
String fileCount = String.format("%02d", i); // output will be 1 is 01, 2 is 02
videoFile = splitFile.getAbsolutePath() +"/"+ fileCount +"_"+ file.getName();
outputStream = new FileOutputStream(videoFile);
Log.d("File Created Location: ", videoFile);
streamSize = 0;
}
}
outputStream.write(read);
streamSize++;
}
inputStream.close();
outputStream.close();
Log.d("Total files Split ->", String.valueOf(totalPartsToSplit));
result="success";
} else {
System.err.println(file.getAbsolutePath() +" File Not Found.");
result="failed";
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public ArrayList<String> getUpdate()
{
return update;
}
And in my activity file i call this using async task's doinbackground method like below
protected String doInBackground(Void...arg0) {
Log.d(TAG + " DoINBackGround", "On doInBackground...");
File encvideo=new File(epath.getText().toString());
SplitVideoFile split=new SplitVideoFile();
String result=split.main(encvideo);
publishProgress(1);
return result;
}
Even though it splits the video, it takes too much of time to do the process.
How can I speed them up. As I'm showing a progress bar in preexecute method it looks like the user sees the progress bar for a long time, which I don't want.

Android: unable to zip generated files

I'm working on this project where I generated CSV files from contact list, and now I'm supposed to package all the files as a single zip archive using RxJava, so I'm trying to get the method to create an archive invoked using onComplete method. But the application is crashing with this error:
Attempt to invoke direct method 'boolean appjoe.wordpress.com.testdemo.Tab2$FileHelper.zip(java.lang.String, java.lang.String)' on a null object reference
This is my code:
path: /storage/emulated/0/Android/data/com.wordpress.appjoe/csv
File location = new File(Environment.getExternalStorageDirectory(), "Android/data/com.wordpress.appjoe/csv/");
File fileLocation;
FileOutputStream dest;
String path;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_tab2, container, false);
mbutton = v.findViewById(R.id.extractContact);
mbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Permission has already been granted
Observer observer = new Observer() {
#Override
public void onSubscribe(Disposable d) {
mCursor = getCursor();
fCursor = getCursor();
location.mkdirs();
path = location.getAbsolutePath();
try {
dest = new FileOutputStream(path);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
#Override
public void onNext(Object o) {
contactData = o.toString();
fCursor.moveToPosition(count);
fileLocation = new File(path, getName(fCursor)+".csv");
try {
FileOutputStream fileOut = new FileOutputStream(fileLocation);
fileOut.write(contactData.getBytes());
fileOut.flush();
fileOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onError(Throwable e) {
}
#Override
public void onComplete() {
mCursor.close();
fCursor.close();
// Creating archive once the CSV files are generated
if (fileHelper.zip(path, location.getParent())) {
Toast.makeText(getContext(), "Zip successful", Toast.LENGTH_SHORT).show();
}
Log.d("fileLocation", "location: " + location.getParent());
Log.d("fileLocation", "path: " + path);
Log.d("Observer_contact", "Completed");
}
};
io.reactivex.Observable.create(new ObservableOnSubscribe<String>() {
#Override
public void subscribe(ObservableEmitter<String> emitter) throws Exception {
try {
for (count = 0; count < mCursor.getCount(); count++) {
emitter.onNext(loadContacts(count));
}
emitter.onComplete();
} catch (Exception e) {
emitter.onError(e);
}
}
}).subscribeOn(Schedulers.io())
.distinct()
.subscribeWith(observer);
}
}
});
// Inflate the layout for this fragment
return v;
}
RxJava implementation to fetch contacts:
public String loadContacts(int i) {
StringBuilder mBuilder = new StringBuilder();
ContentResolver mContentResolver = getActivity().getContentResolver();
mCursor.moveToPosition(i);
if (mCursor.getCount() > 0 ) {
String id = getID(mCursor);
String name = getName(mCursor);
int hasPhoneNumber = hasNumber(mCursor);
if (hasPhoneNumber > 0) {
mBuilder.append("\"").append(name).append("\"");
Cursor cursor = mContentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "= ?",
new String[]{id}, null);
assert cursor != null;
while (cursor.moveToNext()) {
String phoneNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))
.replaceAll("\\s", "");
// if number is not existing in the list, then add number to the string
if (!(mBuilder.toString().contains(phoneNumber))) {
mBuilder.append(", ").append(phoneNumber);
}
}
cursor.close();
}
}
return mBuilder.toString();
}
Methods to get necessary information:
private Cursor getCursor() {
ContentResolver mContentResolver = getActivity().getContentResolver();
return mContentResolver.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, ContactsContract.Contacts.DISPLAY_NAME + " ASC");
}
private String getID(Cursor cursor) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
return id;
}
private String getName(Cursor cursor) {
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
return name;
}
private int hasNumber(Cursor cursor) {
return Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
}
Class to generate archive
// Custom class to help with zipping of generated CSVs
private class FileHelper {
private static final int BUFFER_SIZE = 2048;
private String TAG = FileHelper.class.getName();
private String parentPath = "";
private String destinationFileName = "Contacts_CSV.zip";
private boolean zip (String sourcePath, String destinationPath) {
new File(destinationPath).mkdirs();
FileOutputStream fileOutputStream;
ZipOutputStream zipOutputStream = null;
try {
if (!destinationPath.endsWith("/")) {
destinationPath = destinationPath + "/";
}
String destination = destinationPath + destinationFileName;
File file = new File(destination);
if (!file.exists()) {
file.createNewFile();
}
fileOutputStream = new FileOutputStream(file);
zipOutputStream = new ZipOutputStream(new BufferedOutputStream(fileOutputStream));
parentPath = new File(sourcePath).getParent() + "/";
zipFile(zipOutputStream, sourcePath);
} catch (IOException e) {
e.printStackTrace();
Log.d(TAG,e.getMessage());
return false;
} finally {
if (zipOutputStream!=null)
try {
zipOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
}
private void zipFile (ZipOutputStream zipOutputStream, String sourcePath) throws IOException {
java.io.File files = new java.io.File(sourcePath);
java.io.File[] fileList = files.listFiles();
String entryPath="";
BufferedInputStream input;
for (java.io.File file : fileList) {
if (file.isDirectory()) {
} else {
byte data[] = new byte[BUFFER_SIZE];
FileInputStream fileInputStream = new FileInputStream(file.getPath());
input = new BufferedInputStream(fileInputStream, BUFFER_SIZE);
entryPath = file.getAbsolutePath().replace(parentPath, "");
ZipEntry entry = new ZipEntry(entryPath);
zipOutputStream.putNextEntry(entry);
int count;
while ((count = input.read(data, 0, BUFFER_SIZE)) != -1) {
zipOutputStream.write(data, 0, count);
}
input.close();
}
}
}
}
I solved this problem by removing the class FileHelper and making both the methods inside FileHelper private methods within the main class. That way, calling the methods from onComplete() didn't cause the program to crash, and it was successfully generating the zip file.

how to read the file greater then 1mb

i have create an app in which i am reading the files from phone memory it can read any of the file but when i am reading .vcf file.but when it is smaller than 1 mb ,give correct result,if it is greater than 1 mb,it return nothing.how can i read the data from file.please suggest something.
File_Explore
public class File_Explorer extends Activity {
// Stores names of traversed directories
ArrayList<String> str = new ArrayList<String>();
// Check if the first level of the directory structure is the one showing
private Boolean firstLvl = true;
String aDataRow = "";
static StringBuilder aBuffer = new StringBuilder();
String aBuffer1="";
private static final String TAG = "F_PATH";
private Item[] fileList;
private File path = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
private String chosenFile;
private static final int DIALOG_LOAD_FILE = 0;
static String fileExtension="";
ListAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
loadFileList();
showDialog(DIALOG_LOAD_FILE);
Log.d(TAG, path.getAbsolutePath());
}
private void loadFileList() {
try {
path.mkdirs();
} catch (SecurityException e) {
Log.e(TAG, "unable to write on the sd card ");
}
// Checks whether path exists
if (path.exists()) {
FilenameFilter filter = new FilenameFilter() {
#Override
public boolean accept(File dir, String filename) {
File sel = new File(dir, filename);
// Filters based on whether the file is hidden or not
return (sel.isFile() || sel.isDirectory())
&& !sel.isHidden();
}
};
String[] fList = path.list(filter);
fileList = new Item[fList.length];
for (int i = 0; i < fList.length; i++) {
fileList[i] = new Item(fList[i], R.drawable.ic_launcher);
// Convert into file path
File sel = new File(path, fList[i]);
// Set drawables
if (sel.isDirectory()) {
fileList[i].icon = R.drawable.ic_launcher;
Log.d("DIRECTORY", fileList[i].file);
} else {
Log.d("FILE", fileList[i].file);
}
}
if (!firstLvl) {
Item temp[] = new Item[fileList.length + 1];
for (int i = 0; i < fileList.length; i++) {
temp[i + 1] = fileList[i];
}
temp[0] = new Item("Back", R.drawable.ic_launcher);
fileList = temp;
}
} else {
Log.e(TAG, "path does not exist");
}
adapter = new ArrayAdapter<Item>(this,
android.R.layout.select_dialog_item, android.R.id.text1,
fileList) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// creates view
View view = super.getView(position, convertView, parent);
TextView textView = (TextView) view
.findViewById(android.R.id.text1);
// put the image on the text view
textView.setCompoundDrawablePadding(
fileList[position].icon);
return view;
}
};
}
private class Item {
public String file;
public int icon;
public Item(String file, Integer icon) {
this.file = file;
this.icon = icon;
}
#Override
public String toString() {
return file;
}
}
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
AlertDialog.Builder builder = new Builder(this);
if (fileList == null) {
Log.e(TAG, "No files loaded");
dialog = builder.create();
return dialog;
}
switch (id) {
case DIALOG_LOAD_FILE:
builder.setTitle("Choose your file");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
chosenFile = fileList[which].file;
File sel = new File(path + "/" + chosenFile);
if (sel.isDirectory()) {
firstLvl = false;
// Adds chosen directory to list
str.add(chosenFile);
fileList = null;
path = new File(sel + "");
loadFileList();
removeDialog(DIALOG_LOAD_FILE);
showDialog(DIALOG_LOAD_FILE);
Log.d(TAG, path.getAbsolutePath());
}
// Checks if 'up' was clicked
else if (chosenFile.equalsIgnoreCase("Back") && !sel.exists()) {
// present directory removed from list
String s = str.remove(str.size() - 1);
// path modified to exclude present directory
path = new File(path.toString().substring(0,
path.toString().lastIndexOf(s)));
fileList = null;
// if there are no more directories in the list, then
// its the first level
if (str.isEmpty()) {
firstLvl = true;
}
loadFileList();
removeDialog(DIALOG_LOAD_FILE);
showDialog(DIALOG_LOAD_FILE);
Log.d(TAG, path.getAbsolutePath());
}
// File picked
else {
// Perform action with file picked
fileExtension
= MimeTypeMap.getFileExtensionFromUrl(sel.toString());
// Toast.makeText(getApplication(), fileExtension, Toast.LENGTH_LONG).show();
try{
// ArrayList<String> MyFiles = new ArrayList<String>();
FileInputStream fIn = new FileInputStream(sel);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
while ((aDataRow = myReader.readLine()) != null) {
aBuffer.append(aDataRow.toString()).append("\n");
}
// aBuffer1 = aBuffer.toString();
myReader.close();
}catch (FileNotFoundException e)
{e.printStackTrace();}
catch (IOException e) {
e.printStackTrace();
}
// Toast.makeText(getApplicationContext(),aBuffer,Toast.LENGTH_LONG).show();
Intent returnIntent = new Intent();
returnIntent.putExtra("name", aBuffer.toString());
setResult(RESULT_OK, returnIntent);
finish();
}
aBuffer.delete(0, aBuffer.length());
// aBuffer1=null;
}
}
);
break;
}
dialog = builder.show();
return dialog;
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
Intent i= new Intent(this, File_Selecter.class);
startActivity(i);
}
}
If you do not need whole 1MB (capital B by the way) read (which is usually the case), then read only the part you need. And if you do not know where the part you need is (so you cannot seek()), read in smaller chunks unless you find what you need to read from the file.

Android program to convert the SQLite database to excel

I want to change the sqlite database .db file to excel.
But I am not able to find what exactly I have to do. Can anybody please elaborate in a simple way what I have to perform to achieve this task.
By searching on Google, so many links appears, but I am not able to understand the step by step way to do this.
I have followed these links:
1. How to convert excel sheet into database of sqlite in android
2. SQlite database programmatically convert into Excel file format in Android
3. http://opencsv.sourceforge.net/
My solution is to convert the sqlite database into csv in first step then in second step is to convert the csv file to xls and it works fine for me, you will need 2 libraries (opencsv-1.7.jar; poi-3.8-20120326.jar)
public class ExportDatabaseCSVTask extends AsyncTask<String, Void, Boolean>
{
private final ProgressDialog dialog = new ProgressDialog(DatabaseExampleActivity.this);
#Override
protected void onPreExecute()
{
this.dialog.setMessage("Exporting database...");
this.dialog.show();
}
protected Boolean doInBackground(final String... args)
{
File dbFile=getDatabasePath("database_name");
//AABDatabaseManager dbhelper = new AABDatabaseManager(getApplicationContext());
AABDatabaseManager dbhelper = new AABDatabaseManager(DatabaseExampleActivity.this) ;
System.out.println(dbFile); // displays the data base path in your logcat
File exportDir = new File(Environment.getExternalStorageDirectory(), "");
if (!exportDir.exists())
{
exportDir.mkdirs();
}
File file = new File(exportDir, "excerDB.csv");
try
{
if (file.createNewFile()){
System.out.println("File is created!");
System.out.println("myfile.csv "+file.getAbsolutePath());
}else{
System.out.println("File already exists.");
}
CSVWriter csvWrite = new CSVWriter(new FileWriter(file));
//SQLiteDatabase db = dbhelper.getWritableDatabase();
Cursor curCSV=db.getdb().rawQuery("select * from " + db.TABLE_NAME,null);
csvWrite.writeNext(curCSV.getColumnNames());
while(curCSV.moveToNext())
{
String arrStr[] ={curCSV.getString(0),curCSV.getString(1),curCSV.getString(2)};
/*curCSV.getString(3),curCSV.getString(4)};*/
csvWrite.writeNext(arrStr);
}
csvWrite.close();
curCSV.close();
/*String data="";
data=readSavedData();
data= data.replace(",", ";");
writeData(data);*/
return true;
}
catch(SQLException sqlEx)
{
Log.e("MainActivity", sqlEx.getMessage(), sqlEx);
return false;
}
catch (IOException e)
{
Log.e("MainActivity", e.getMessage(), e);
return false;
}
}
protected void onPostExecute(final Boolean success)
{
if (this.dialog.isShowing())
{
this.dialog.dismiss();
}
if (success)
{
Toast.makeText(DatabaseExampleActivity.this, "Export succeed", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(DatabaseExampleActivity.this, "Export failed", Toast.LENGTH_SHORT).show();
}
}}
Export CSV to XLS part
public class CSVToExcelConverter extends AsyncTask<String, Void, Boolean> {
private final ProgressDialog dialog = new ProgressDialog(DatabaseExampleActivity.this);
#Override
protected void onPreExecute()
{this.dialog.setMessage("Exporting to excel...");
this.dialog.show();}
#Override
protected Boolean doInBackground(String... params) {
ArrayList arList=null;
ArrayList al=null;
//File dbFile= new File(getDatabasePath("database_name").toString());
File dbFile=getDatabasePath("database_name");
String yes= dbFile.getAbsolutePath();
String inFilePath = Environment.getExternalStorageDirectory().toString()+"/excerDB.csv";
outFilePath = Environment.getExternalStorageDirectory().toString()+"/test.xls";
String thisLine;
int count=0;
try {
FileInputStream fis = new FileInputStream(inFilePath);
DataInputStream myInput = new DataInputStream(fis);
int i=0;
arList = new ArrayList();
while ((thisLine = myInput.readLine()) != null)
{
al = new ArrayList();
String strar[] = thisLine.split(",");
for(int j=0;j<strar.length;j++)
{
al.add(strar[j]);
}
arList.add(al);
System.out.println();
i++;
}} catch (Exception e) {
System.out.println("shit");
}
try
{
HSSFWorkbook hwb = new HSSFWorkbook();
HSSFSheet sheet = hwb.createSheet("new sheet");
for(int k=0;k<arList.size();k++)
{
ArrayList ardata = (ArrayList)arList.get(k);
HSSFRow row = sheet.createRow((short) 0+k);
for(int p=0;p<ardata.size();p++)
{
HSSFCell cell = row.createCell((short) p);
String data = ardata.get(p).toString();
if(data.startsWith("=")){
cell.setCellType(Cell.CELL_TYPE_STRING);
data=data.replaceAll("\"", "");
data=data.replaceAll("=", "");
cell.setCellValue(data);
}else if(data.startsWith("\"")){
data=data.replaceAll("\"", "");
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue(data);
}else{
data=data.replaceAll("\"", "");
cell.setCellType(Cell.CELL_TYPE_NUMERIC);
cell.setCellValue(data);
}
//*/
// cell.setCellValue(ardata.get(p).toString());
}
System.out.println();
}
FileOutputStream fileOut = new FileOutputStream(outFilePath);
hwb.write(fileOut);
fileOut.close();
System.out.println("Your excel file has been generated");
} catch ( Exception ex ) {
ex.printStackTrace();
} //main method ends
return true;
}
protected void onPostExecute(final Boolean success)
{
if (this.dialog.isShowing())
{
this.dialog.dismiss();
}
if (success)
{
Toast.makeText(DatabaseExampleActivity.this, "file is built!", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(DatabaseExampleActivity.this, "file fail to build", Toast.LENGTH_SHORT).show();
}
}
}
I know this question is a little old but it provided me with the answer to the same question. I've cleaned up the code a little and done away with the need to write a csv file altogether by getting my database helper class to return me an ArrayList. Still using Apache POI though.
File folder =new File(Environment.getExternalStorageDirectory()+APP_FILES_PATH);
if(!folder.exists())
{
folder.mkdir();
}
DatabaseHelper dbHelper = DatabaseHelper.getInstance(context);
ArrayList<String[]> exts = dbHelper.getExtinguisherArray(1);
HSSFWorkbook hwb = new HSSFWorkbook();
HSSFSheet sheet = hwb.createSheet("extinguishers");
for(int x = 0; x < exts.size(); x++)
{
String[] arr = exts.get(x);
HSSFRow row = sheet.createRow(x);
for(int i = 0; i< arr.length; i++)
{
HSSFCell cell = row.createCell(i);
String data = arr[i];
cell.setCellValue(data);
}
}
FileOutputStream fileOut = new FileOutputStream(Environment.getExternalStorageDirectory()+APP_FILES_PATH+"file.xls");
hwb.write(fileOut);
fileOut.close();
Export Android SqliteDb to CSV format
You need to do these step...
add this jar file opencsv-1.7.jar http://www.java2s.com/Code/Jar/o/Downloadopencsv17jar.htm
And then use this code
public class ExportDatabaseToCSV{
Context context;
public ExportDatabaseToCSV(Context context) {
this.context=context;
}
public void exportDataBaseIntoCSV(){
CredentialDb db = new CredentialDb(context);//here CredentialDb is my database. you can create your db object.
File exportDir = new File(Environment.getExternalStorageDirectory(), "");
if (!exportDir.exists())
{
exportDir.mkdirs();
}
File file = new File(exportDir, "csvfilename.csv");
try
{
file.createNewFile();
CSVWriter csvWrite = new CSVWriter(new FileWriter(file));
SQLiteDatabase sql_db = db.getReadableDatabase();//here create a method ,and return SQLiteDatabaseObject.getReadableDatabase();
Cursor curCSV = sql_db.rawQuery("SELECT * FROM "+CredentialDb.TABLE_NAME,null);
csvWrite.writeNext(curCSV.getColumnNames());
while(curCSV.moveToNext())
{
//Which column you want to export you can add over here...
String arrStr[] ={curCSV.getString(0),curCSV.getString(1), curCSV.getString(2)};
csvWrite.writeNext(arrStr);
}
csvWrite.close();
curCSV.close();
}
catch(Exception sqlEx)
{
Log.e("Error:", sqlEx.getMessage(), sqlEx);
}
}
}
In addition to #user2324120's answer, and as we're in Android, you can directly add the libs to gradle (and therefore you don't need to download the jars) :
compile 'com.opencsv:opencsv:3.7'
compile 'org.apache.poi:poi:3.14'
I also did it a different way, a way more customisable one (and without useless CSV transition). Here it is, with a few comments :
public static Pair<Boolean, String> exportToXLS(Context context, boolean byAuthor) {
try {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet(context.getString(R.string.sheet_name)); // Good for localization
initSheetColumns(context, workbook, sheet, byAuthor);
addBooksToSheet(sheet, byAuthor);
setColumsWidth(sheet);
OutputStream outputStream = new FileOutputStream(new File(Methods.getDownloadsDirectory(), byAuthor ? context.getString(R.string.mylibrary_by_author_xls) : context.getString(R.string.mylibrary_xls)).getAbsolutePath());
workbook.write(outputStream);
outputStream.flush();
outputStream.close();
return new Pair<>(true, context.getString(R.string.database_saved));
} catch (Exception e) {
e.printStackTrace();
return new Pair<>(false, context.getString(R.string.an_error_has_occured_during_xls_file_creation));
}
}
private static void initSheetColumns(Context context, HSSFWorkbook workbook, HSSFSheet sheet, boolean byAuthor) {
HSSFRow row = sheet.createRow(0);
HSSFCell cell = row.createCell(0);
cell.setCellValue(byAuthor ? context.getString(R.string.db_author) : context.getString(R.string.db_title));
cell = row.createCell(1);
cell.setCellValue(byAuthor ? context.getString(R.string.db_title) : context.getString(R.string.db_author));
cell = row.createCell(2);
cell.setCellValue(context.getString(R.string.db_publisheddate));
/*
etc.
*/
boldHeaders(workbook, row);
}
private static void boldHeaders(HSSFWorkbook workbook, HSSFRow row) {
HSSFCellStyle style = workbook.createCellStyle();
/* Do your own style
...
*/
for (int i = 0; i < 8; i++) {
row.getCell(i).setCellStyle(style);
}
}
// Allow data personalisation and localisation if needed
private static void addBooksToSheet(HSSFSheet sheet, boolean byAuthor) {
int i = 1;
List<Book> books = Book.listAll(Book.class); // I use Sugar library here, if you're not just make a simple db query to get your objects
Collections.sort(books, byAuthor ? Book.bookAuthorComparator : Book.bookNameComparator);
for (Book book : books) {
HSSFRow row = sheet.createRow(i);
HSSFCell cell = row.createCell(0);
cell.setCellValue(byAuthor ? getBookValue(book, true) : book.getTitle());
cell = row.createCell(1);
cell.setCellValue(byAuthor ? book.getTitle() : getBookValue(book, false));
cell = row.createCell(2);
cell.setCellValue(book.getPublishedDate());
/*
etc.
*/
i++;
}
}
private static void setColumsWidth(HSSFSheet sheet) {
for (int i = 0; i < 8; i++) {
sheet.setColumnWidth(i, 255 * getMaxNumCharacters(sheet, i)); // Autosize not working on Android
}
}
// My method to get the max num char, if it can hekp
public static int getMaxNumCharacters(Sheet sheet, int column) {
int max = 0;
for (int rowIndex = 0; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
Row row = sheet.getRow(rowIndex);
if (row == null) {
continue;
}
Cell cell = row.getCell(column);
if (cell != null) {
int nb = cell.getStringCellValue().length();
if (nb > max) {
max = nb;
}
}
}
max = (int) (max * 1.1);
if (max > 255) {
return 255; // max 255 char for width
}
return max;
}
Hope it helps!

Upload an image from Android to Amazon S3?

I need to upload a bitmap to Amazon S3. I have never used S3, and the docs are proving less than helpful as I can't see anything to cover this specific requirement. Unfortunately I'm struggling to find time on this project to spend a whole day learning how it all hangs together so hoping one of you kind people can give me some pointers.
Can you point to me to a source of reference that explains how to push a file to S3, and get a URL reference in return?
More specifically:
- Where do the credentials go when using the S3 Android SDK?
- Do I need to create a bucket before uploading a file, or can they exist outside buckets?
- Which SDK method do I use to push a bitmap up to S3?
- Am I right in thinking I need the CORE and S3 libs to do what I need, and no others?
String ACCESS_KEY="****************",
SECRET_KEY="****************",
MY_BUCKET="bucket_name",
OBJECT_KEY="unique_id";
AWSCredentials credentials = new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY);
AmazonS3 s3 = new AmazonS3Client(credentials);
java.security.Security.setProperty("networkaddress.cache.ttl" , "60");
s3.setRegion(Region.getRegion(Regions.AP_SOUTHEAST_1));
s3.setEndpoint("https://s3-ap-southeast-1.amazonaws.com/");
List<Bucket> buckets=s3.listBuckets();
for(Bucket bucket:buckets){
Log.e("Bucket ","Name "+bucket.getName()+" Owner "+bucket.getOwner()+ " Date " + bucket.getCreationDate());
}
Log.e("Size ", "" + s3.listBuckets().size());
TransferUtility transferUtility = new TransferUtility(s3, getApplicationContext());
UPLOADING_IMAGE=new File(Environment.getExternalStorageDirectory().getPath()+"/Screenshot.png");
TransferObserver observer = transferUtility.upload(MY_BUCKET,OBJECT_KEY,UPLOADING_IMAGE);
observer.setTransferListener(new TransferListener() {
#Override
public void onStateChanged(int id, TransferState state) {
// do something
progress.hide();
path.setText("ID "+id+"\nState "+state.name()+"\nImage ID "+OBJECT_KEY);
}
#Override
public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) {
int percentage = (int) (bytesCurrent / bytesTotal * 100);
progress.setProgress(percentage);
//Display percentage transfered to user
}
#Override
public void onError(int id, Exception ex) {
// do something
Log.e("Error ",""+ex );
}
});
Take a look at the Amazon S3 API documentation to get a feel for what can and can't be done with Amazon S3. Note that there are two APIs, a simpler REST API and a more-involved SOAP API.
You can write your own code to make HTTP requests to interact with the REST API, or use a SOAP library to consume the SOAP API. All of the Amazon services have these standard API endpoints (REST, SOAP) and in theory you can write a client in any programming language!
Fortunately for Android developers, Amazon have released a (Beta) SDK that does all of this work for you. There's a Getting Started guide and Javadocs too. With this SDK you should be able to integrate S3 with your application in a matter of hours.
The Getting Started guide comes with a full sample and shows how to supply the required credentials.
Conceptually, Amazon S3 stores data in Buckets where a bucket contains Objects. Generally you'll use one bucket per application, and add as many objects as you like. S3 doesn't support or have any concept of folders, but you can put slashes (/) in your object names.
We can directly use "Amazone s3" bucket for storing any type of file on server, and we did not need to send any of file to Api server it will reduce the request time.
Gradle File :-
compile 'com.amazonaws:aws-android-sdk-core:2.2.+'
compile 'com.amazonaws:aws-android-sdk-s3:2.2.+'
compile 'com.amazonaws:aws-android-sdk-ddb:2.2.+'
Manifest File :-
<service android:name="com.amazonaws.mobileconnectors.s3.transferutility.TransferService"
android:enabled="true" />
FileUploader Function in any Class :-
private void setUPAmazon() {
//we Need Identity Pool ID like :- "us-east-1:f224****************8"
CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider(getActivity(),
"us-east-1:f224****************8", Regions.US_EAST_1);
AmazonS3 s3 = new AmazonS3Client(credentialsProvider);
final TransferUtility transferUtility = new TransferUtility(s3, getActivity());
final File file = new File(mCameraUri.getPath());
final TransferObserver observer = transferUtility.upload(GeneralValues.AMAZON_BUCKET, file.getName(), file, CannedAccessControlList.PublicRead);
observer.setTransferListener(new TransferListener() {
#Override
public void onStateChanged(int id, TransferState state) {
Log.e("onStateChanged", id + state.name());
if (state == TransferState.COMPLETED) {
String url = "https://"+GeneralValues.AMAZON_BUCKET+".s3.amazonaws.com/" + observer.getKey();
Log.e("URL :,", url);
//we just need to share this File url with Api service request.
}
}
#Override
public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) {
}
#Override
public void onError(int id, Exception ex) {
Toast.makeText(getActivity(), "Unable to Upload", Toast.LENGTH_SHORT).show();
ex.printStackTrace();
}
});
}
you can use the below mentioned class to Upload data to amazon s3 buckets.
public class UploadAmazonS3{
private CognitoCachingCredentialsProvider credentialsProvider = null;
private AmazonS3Client s3Client = null;
private TransferUtility transferUtility = null;
private static UploadAmazonS3 uploadAmazonS3;
/**
* Creating single tone object by defining private.
* <P>
* At the time of creating
* </P>*/
private UploadAmazonS3(Context context, String canito_pool_id)
{
/**
* Creating the object of the getCredentialProvider object. */
credentialsProvider=getCredentialProvider(context,canito_pool_id);
/**
* Creating the object of the s3Client */
s3Client=getS3Client(context,credentialsProvider);
/**
* Creating the object of the TransferUtility of the Amazone.*/
transferUtility=getTransferUtility(context,s3Client);
}
public static UploadAmazonS3 getInstance(Context context, String canito_pool_id)
{
if(uploadAmazonS3 ==null)
{
uploadAmazonS3 =new UploadAmazonS3(context,canito_pool_id);
return uploadAmazonS3;
}else
{
return uploadAmazonS3;
}
}
/**
* <h3>Upload_data</h3>
* <P>
* Method is use to upload data in the amazone server.
*
* </P>*/
public void uploadData(final String bukkate_name, final File file, final Upload_CallBack callBack)
{
Utility.printLog("in amazon upload class uploadData "+file.getName());
if(transferUtility!=null&&file!=null)
{
TransferObserver observer=transferUtility.upload(bukkate_name,file.getName(),file);
observer.setTransferListener(new TransferListener()
{
#Override
public void onStateChanged(int id, TransferState state)
{
if(state.equals(TransferState.COMPLETED))
{
callBack.sucess(com.tarha_taxi.R.string.AMAZON_END_POINT_LINK+bukkate_name+"/"+file.getName());
}
}
#Override
public void onProgressChanged(int id, long bytesCurrent, long bytesTotal)
{
}
#Override
public void onError(int id, Exception ex)
{
callBack.error(id+":"+ex.toString());
}
});
}else
{
callBack.error("Amamzones3 is not intialize or File is empty !");
}
}
/**
* This method is used to get the CredentialProvider and we provide only context as a parameter.
* #param context Here, we are getting the context from calling Activity.*/
private CognitoCachingCredentialsProvider getCredentialProvider(Context context,String pool_id)
{
if (credentialsProvider == null)
{
credentialsProvider = new CognitoCachingCredentialsProvider(
context.getApplicationContext(),
pool_id, // Identity Pool ID
AMAZON_REGION // Region
);
}
return credentialsProvider;
}
/**
* This method is used to get the AmazonS3 Client
* and we provide only context as a parameter.
* and from here we are calling getCredentialProvider() function.
* #param context Here, we are getting the context from calling Activity.*/
private AmazonS3Client getS3Client(Context context,CognitoCachingCredentialsProvider cognitoCachingCredentialsProvider)
{
if (s3Client == null)
{
s3Client = new AmazonS3Client(cognitoCachingCredentialsProvider);
s3Client.setRegion(Region.getRegion(AMAZON_REGION));
s3Client.setEndpoint(context.getString(com.tarha_taxi.R.string.AMAZON_END_POINT_LINK));
}
return s3Client;
}
/**
* This method is used to get the Transfer Utility
* and we provide only context as a parameter.
* and from here we are, calling getS3Client() function.
* #param context Here, we are getting the context from calling Activity.*/
private TransferUtility getTransferUtility(Context context,AmazonS3Client amazonS3Client)
{
if (transferUtility == null)
{
transferUtility = new TransferUtility(amazonS3Client,context.getApplicationContext());
}
return transferUtility;
}
/**
* Interface for the sucess callback fro the Amazon uploading .
* */
public interface Upload_CallBack
{
/**
*Method for sucess .
* #param sucess it is true on sucess and false for falure.*/
void sucess(String sucess);
/**
* Method for falure.
* #param errormsg contains the error message.*/
void error(String errormsg);
}
}
use the below method to access the above calss :
private void uploadToAmazon() {
dialogL.show();
UploadAmazonS3 amazonS3 = UploadAmazonS3.getInstance(getActivity(), getString(R.string.AMAZON_POOL_ID));
amazonS3.uploadData(getString(R.string.BUCKET_NAME), Utility.renameFile(VariableConstants.TEMP_PHOTO_FILE_NAME, phone.getText().toString().substring(1) + ".jpg"), new UploadAmazonS3.Upload_CallBack() {
#Override
public void sucess(String sucess) {
if (Utility.isNetworkAvailable(getActivity())) {
dialogL.dismiss();
/**
* to set the image into image view and
* add the write the image in the file
*/
activity.user_image.setTag(setTarget(progress_bar));
Picasso.with(getActivity()).load(getString(R.string.AMAZON_IMAGE_LINK) + phone.getText().toString().substring(1) + ".jpg").
networkPolicy(NetworkPolicy.NO_CACHE).memoryPolicy(MemoryPolicy.NO_CACHE).into((Target) activity.user_image.getTag());
Utility.printLog("amazon upload success ");
new BackgroundForUpdateProfile().execute();
} else {
dialogL.dismiss();
Utility.showToast(getActivity(), getResources().getString(R.string.network_connection_fail));
}
}
#Override
public void error(String errormsg) {
dialogL.dismiss();
Utility.showToast(getActivity(), getResources().getString(R.string.network_connection_fail));
}
});
}
You can use a library called S3UploadService. First you would need to convert your Bitmap to a File. To do so take a look at this post:
Convert Bitmap to File
S3UploadService is a library that handles uploads to Amazon S3. It provides a service called S3UploadService with a static method where you provide a Context (so the static method can start the service), a File, a boolean indicating if said file should be deleted after upload completion and optionally you can set a callback (Not like an ordinary callback though. The way this works is explained in the README file).
It's an IntentService so the upload will run even if the user kills the app while uploading (because its lifecycle is not attached to the app's lifecycle).
To use this library you just have to declare the service in your manifest:
<application
...>
...
<service
android:name="com.onecode.s3.service.S3UploadService"
android:exported="false" />
</application>
Then you build an S3BucketData instance and make a call to S3UploadService.upload():
S3Credentials s3Credentials = new S3Credentials(accessKey, secretKey, sessionToken);
S3BucketData s3BucketData = new S3BucketData.Builder()
.setCredentials(s3Credentials)
.setBucket(bucket)
.setKey(key)
.setRegion(region)
.build();
S3UploadService.upload(getActivity(), s3BucketData, file, null);
To add this library you need to add the JitPack repo to your root build.gradle:
allprojects {
repositories {
...
maven { url "https://jitpack.io" }
}
}
and then add the dependency:
dependencies {
compile 'com.github.OneCodeLabs:S3UploadService:1.0.0#aar'
}
Here is a link to the repo:
https://github.com/OneCodeLabs/S3UploadService
This answer is a bit late, but I hope it helps someone
you can upload image and download image in s3 amazon. you make a simple class use this WebserviceAmazon
public class WebserviceAmazon extends AsyncTask<Void, Void, Void> {
private String mParams;
private String mResult = "x";
WebServiceInterface<String, String> mInterface;
private int mRequestType;
private String UserId;
private Context mContext;
public WebserviceAmazon(Context context,String imagePath,String AppId,int type) {
this.mContext = context;
this.mParams = imagePath;
this.mRequestType = type;
this.UserId = AppId;
}
public void result(WebServiceInterface<String, String> myInterface) {
this.mInterface = myInterface;
}
#Override
protected Void doInBackground(Void... params) {
String ACCESS_KEY ="abc..";
String SECRET_KEY = "klm...";
try {
if (mRequestType == 1) { // POST
AmazonS3Client s3Client = new AmazonS3Client(new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY));
PutObjectRequest request = new PutObjectRequest("bucketName", "imageName", new File(mParams));
s3Client.putObject(request);
mResult = "success";
} if (mRequestType == 2) { // For get image data
AmazonS3Client s3Client = new AmazonS3Client(new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY));
S3Object object = s3Client.getObject(new GetObjectRequest("bucketName", mParams));
S3ObjectInputStream objectContent = object.getObjectContent();
byte[] byteArray = IOUtils.toByteArray(objectContent);
Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
mResult = "success";
}
} catch (Exception e) {
mResult = e.toString();
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
mInterface.success(this.mResult);
}
public interface WebServiceInterface<E, R> {
public void success(E reslut);
public void error(R Error);
}
}
call this webservice any where in project
WebserviceAmazon amazon = new WebserviceAmazon(getActivity(), imageName, "", 2);
amazon.result(new WebserviceAmazon.WebServiceInterface<String, String>() {
#Override
public void success(String reslut) {
}
#Override
public void error(String Error) {
}
});
return totalPoints;
}
here is my code to upload image to Amazon AWS S3 bucket
Hope this is helpful for you
First let me clear some key points
you can either take image from camera or pick image from gallery ,AWS store images as a file so first thing you need to store image to local dir and get path of image then create a file from that path after this you will be able to upload that imagefile to AWS.
first you need to add configration on Oncreate
BasicAWSCredentials credentials = new BasicAWSCredentials(KEY,SECRET);
s3 = new AmazonS3Client(credentials);
s3.setRegion(Region.getRegion(Regions.US_EAST_1));
private void uploadFile() {
verifyStoragePermissions(CustomCameraActivity.this);
TransferUtility transferUtility =
TransferUtility.builder()
.context(getApplicationContext())
.awsConfiguration(AWSMobileClient.getInstance().getConfiguration())
.s3Client(s3)
.build();
TransferObserver uploadObserver= null;
File file2 = FileUtils.getFile(CustomCameraActivity.this, storageImagePath);//here i am converting path to file ,,FileUtils.getFile is custom class
uploadObserver = transferUtility.upload("your bucket name", imageNameWithoutExtension + ".jpg", file2);// imagenamewithoutExtension is actually the name that you want to store
uploadObserver.setTransferListener(new TransferListener() {
#Override
public void onStateChanged(int id, TransferState state) {
if (TransferState.COMPLETED == state) {
Toast.makeText(getApplicationContext(), "Upload Completed!", Toast.LENGTH_SHORT).show();
uploadResourcesApi(uploadResoucesURL);
//imageFile.delete();
//file2.delete();
} else if (TransferState.FAILED == state) {
//imageFile.delete();
//file2.delete();
}
}
#Override
public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) {
float percentDonef = ((float) bytesCurrent / (float) bytesTotal) * 100;
int percentDone = (int) percentDonef;
//tvFileName.setText("ID:" + id + "|bytesCurrent: " + bytesCurrent + "|bytesTotal: " + bytesTotal + "|" + percentDone + "%");
}
#Override
public void onError(int id, Exception ex) {
ex.printStackTrace();
}
});
}
this is fileUtils class
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.webkit.MimeTypeMap;
import java.io.File;
import java.io.FileFilter;
import java.text.DecimalFormat;
import java.util.Comparator;
/**
* #version 2009-07-03
* #author Peli
* #version 2013-12-11
* #author paulburke (ipaulpro)
*/
public class FileUtils {
private FileUtils() {} //private constructor to enforce Singleton pattern
/** TAG for log messages. */
static final String TAG = "FileUtils";
private static final boolean DEBUG = false; // Set to true to enable logging
public static final String MIME_TYPE_AUDIO = "audio/*";
public static final String MIME_TYPE_TEXT = "text/*";
public static final String MIME_TYPE_IMAGE = "image/*";
public static final String MIME_TYPE_VIDEO = "video/*";
public static final String MIME_TYPE_APP = "application/*";
public static final String HIDDEN_PREFIX = ".";
/**
* Gets the extension of a file name, like ".png" or ".jpg".
*
* #param uri
* #return Extension including the dot("."); "" if there is no extension;
* null if uri was null.
*/
public static String getExtension(String uri) {
if (uri == null) {
return null;
}
int dot = uri.lastIndexOf(".");
if (dot >= 0) {
return uri.substring(dot);
} else {
// No extension.
return "";
}
}
/**
* #return Whether the URI is a local one.
*/
public static boolean isLocal(String url) {
if (url != null && !url.startsWith("http://") && !url.startsWith("https://")) {
return true;
}
return false;
}
/**
* #return True if Uri is a MediaStore Uri.
* #author paulburke
*/
public static boolean isMediaUri(Uri uri) {
return "media".equalsIgnoreCase(uri.getAuthority());
}
/**
* Convert File into Uri.
*
* #param file
* #return uri
*/
public static Uri getUri(File file) {
if (file != null) {
return Uri.fromFile(file);
}
return null;
}
/**
* Returns the path only (without file name).
*
* #param file
* #return
*/
public static File getPathWithoutFilename(File file) {
if (file != null) {
if (file.isDirectory()) {
// no file to be split off. Return everything
return file;
} else {
String filename = file.getName();
String filepath = file.getAbsolutePath();
// Construct path without file name.
String pathwithoutname = filepath.substring(0,
filepath.length() - filename.length());
if (pathwithoutname.endsWith("/")) {
pathwithoutname = pathwithoutname.substring(0, pathwithoutname.length() - 1);
}
return new File(pathwithoutname);
}
}
return null;
}
/**
* #return The MIME type for the given file.
*/
public static String getMimeType(File file) {
String extension = getExtension(file.getName());
if (extension.length() > 0)
return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.substring(1));
return "application/octet-stream";
}
/**
* #return The MIME type for the give Uri.
*/
public static String getMimeType(Context context, Uri uri) {
File file = new File(getPath(context, uri));
return getMimeType(file);
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is {#link LocalStorageProvider}.
* #author paulburke
*/
public static boolean isLocalStorageDocument(Uri uri) {
return LocalStorageProvider.AUTHORITY.equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is ExternalStorageProvider.
* #author paulburke
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is DownloadsProvider.
* #author paulburke
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is MediaProvider.
* #author paulburke
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is Google Photos.
*/
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* #param context The context.
* #param uri The Uri to query.
* #param selection (Optional) Filter used in the query.
* #param selectionArgs (Optional) Selection arguments used in the query.
* #return The value of the _data column, which is typically a file path.
* #author paulburke
*/
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
if (DEBUG)
DatabaseUtils.dumpCursor(cursor);
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
public static String getPath(final Context context, final Uri uri) {
if (DEBUG)
Log.d(TAG + " File -",
"Authority: " + uri.getAuthority() +
", Fragment: " + uri.getFragment() +
", Port: " + uri.getPort() +
", Query: " + uri.getQuery() +
", Scheme: " + uri.getScheme() +
", Host: " + uri.getHost() +
", Segments: " + uri.getPathSegments().toString()
);
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// LocalStorageProvider
if (isLocalStorageDocument(uri)) {
// The path is the id
return DocumentsContract.getDocumentId(uri);
}
// ExternalStorageProvider
else if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
// TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] {
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
public static File getFile(Context context, Uri uri) {
if (uri != null) {
String path = getPath(context, uri);
if (path != null && isLocal(path)) {
return new File(path);
}
}
return null;
}
public static String getReadableFileSize(int size) {
final int BYTES_IN_KILOBYTES = 1024;
final DecimalFormat dec = new DecimalFormat("###.#");
final String KILOBYTES = " KB";
final String MEGABYTES = " MB";
final String GIGABYTES = " GB";
float fileSize = 0;
String suffix = KILOBYTES;
if (size > BYTES_IN_KILOBYTES) {
fileSize = size / BYTES_IN_KILOBYTES;
if (fileSize > BYTES_IN_KILOBYTES) {
fileSize = fileSize / BYTES_IN_KILOBYTES;
if (fileSize > BYTES_IN_KILOBYTES) {
fileSize = fileSize / BYTES_IN_KILOBYTES;
suffix = GIGABYTES;
} else {
suffix = MEGABYTES;
}
}
}
return String.valueOf(dec.format(fileSize) + suffix);
}
public static Bitmap getThumbnail(Context context, File file) {
return getThumbnail(context, getUri(file), getMimeType(file));
}
public static Bitmap getThumbnail(Context context, Uri uri) {
return getThumbnail(context, uri, getMimeType(context, uri));
}
public static Bitmap getThumbnail(Context context, Uri uri, String mimeType) {
if (DEBUG)
Log.d(TAG, "Attempting to get thumbnail");
if (!isMediaUri(uri)) {
Log.e(TAG, "You can only retrieve thumbnails for images and videos.");
return null;
}
Bitmap bm = null;
if (uri != null) {
final ContentResolver resolver = context.getContentResolver();
Cursor cursor = null;
try {
cursor = resolver.query(uri, null, null, null, null);
if (cursor.moveToFirst()) {
final int id = cursor.getInt(0);
if (DEBUG)
Log.d(TAG, "Got thumb ID: " + id);
if (mimeType.contains("video")) {
bm = MediaStore.Video.Thumbnails.getThumbnail(
resolver,
id,
MediaStore.Video.Thumbnails.MINI_KIND,
null);
}
else if (mimeType.contains(FileUtils.MIME_TYPE_IMAGE)) {
bm = MediaStore.Images.Thumbnails.getThumbnail(
resolver,
id,
MediaStore.Images.Thumbnails.MINI_KIND,
null);
}
}
} catch (Exception e) {
if (DEBUG)
Log.e(TAG, "getThumbnail", e);
} finally {
if (cursor != null)
cursor.close();
}
}
return bm;
}
public static Comparator<File> sComparator = new Comparator<File>() {
#Override
public int compare(File f1, File f2) {
// Sort alphabetically by lower case, which is much cleaner
return f1.getName().toLowerCase().compareTo(
f2.getName().toLowerCase());
}
};
public static FileFilter sFileFilter = new FileFilter() {
#Override
public boolean accept(File file) {
final String fileName = file.getName();
// Return files only (not directories) and skip hidden files
return file.isFile() && !fileName.startsWith(HIDDEN_PREFIX);
}
};
public static FileFilter sDirFilter = new FileFilter() {
#Override
public boolean accept(File file) {
final String fileName = file.getName();
// Return directories only and skip hidden directories
return file.isDirectory() && !fileName.startsWith(HIDDEN_PREFIX);
}
};
public static Intent createGetContentIntent() {
// Implicitly allow the user to select a particular kind of data
final Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
// The MIME data type filter
intent.setType("*/*");
// Only return URIs that can be opened with ContentResolver
intent.addCategory(Intent.CATEGORY_OPENABLE);
return intent;
}
}
then you will also need this class
public class LocalStorageProvider extends DocumentsProvider {
public static final String AUTHORITY = "com.ianhanniballake.localstorage.documents";
private final static String[] DEFAULT_ROOT_PROJECTION = new String[] {
Root.COLUMN_ROOT_ID,
Root.COLUMN_FLAGS, Root.COLUMN_TITLE, Root.COLUMN_DOCUMENT_ID, Root.COLUMN_ICON,
Root.COLUMN_AVAILABLE_BYTES
};
private final static String[] DEFAULT_DOCUMENT_PROJECTION = new String[] {
Document.COLUMN_DOCUMENT_ID,
Document.COLUMN_DISPLAY_NAME, Document.COLUMN_FLAGS, Document.COLUMN_MIME_TYPE,
Document.COLUMN_SIZE,
Document.COLUMN_LAST_MODIFIED
};
#Override
public Cursor queryRoots(final String[] projection) throws FileNotFoundException {
final MatrixCursor result = new MatrixCursor(projection != null ? projection
: DEFAULT_ROOT_PROJECTION);
File homeDir = Environment.getExternalStorageDirectory();
final MatrixCursor.RowBuilder row = result.newRow();
// These columns are required
row.add(Root.COLUMN_ROOT_ID, homeDir.getAbsolutePath());
row.add(Root.COLUMN_DOCUMENT_ID, homeDir.getAbsolutePath());
row.add(Root.COLUMN_TITLE, "Internal storage");
row.add(Root.COLUMN_FLAGS, Root.FLAG_LOCAL_ONLY | Root.FLAG_SUPPORTS_CREATE);
row.add(Root.COLUMN_ICON, R.drawable.ic_launcher_foreground);
// These columns are optional
row.add(Root.COLUMN_AVAILABLE_BYTES, homeDir.getFreeSpace());
// Root.COLUMN_MIME_TYPE is another optional column and useful if you
return result;
}
#Override
public String createDocument(final String parentDocumentId, final String mimeType,
final String displayName) throws FileNotFoundException {
File newFile = new File(parentDocumentId, displayName);
try {
newFile.createNewFile();
return newFile.getAbsolutePath();
} catch (IOException e) {
Log.e(LocalStorageProvider.class.getSimpleName(), "Error creating new file " + newFile);
}
return null;
}
#Override
public AssetFileDescriptor openDocumentThumbnail(final String documentId, final Point sizeHint,
final CancellationSignal signal) throws FileNotFoundException {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(documentId, options);
final int targetHeight = 2 * sizeHint.y;
final int targetWidth = 2 * sizeHint.x;
final int height = options.outHeight;
final int width = options.outWidth;
options.inSampleSize = 1;
if (height > targetHeight || width > targetWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
while ((halfHeight / options.inSampleSize) > targetHeight
|| (halfWidth / options.inSampleSize) > targetWidth) {
options.inSampleSize *= 2;
}
}
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeFile(documentId, options);
// Write out the thumbnail to a temporary file
File tempFile = null;
FileOutputStream out = null;
try {
tempFile = File.createTempFile("thumbnail", null, getContext().getCacheDir());
out = new FileOutputStream(tempFile);
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
} catch (IOException e) {
Log.e(LocalStorageProvider.class.getSimpleName(), "Error writing thumbnail", e);
return null;
} finally {
if (out != null)
try {
out.close();
} catch (IOException e) {
Log.e(LocalStorageProvider.class.getSimpleName(), "Error closing thumbnail", e);
}
}
// It appears the Storage Framework UI caches these results quite
// aggressively so there is little reason to
// write your own caching layer beyond what you need to return a single
// AssetFileDescriptor
return new AssetFileDescriptor(ParcelFileDescriptor.open(tempFile,
ParcelFileDescriptor.MODE_READ_ONLY), 0,
AssetFileDescriptor.UNKNOWN_LENGTH);
}
#Override
public Cursor queryChildDocuments(final String parentDocumentId, final String[] projection,
final String sortOrder) throws FileNotFoundException {
// Create a cursor with either the requested fields, or the default
// projection if "projection" is null.
final MatrixCursor result = new MatrixCursor(projection != null ? projection
: DEFAULT_DOCUMENT_PROJECTION);
final File parent = new File(parentDocumentId);
for (File file : parent.listFiles()) {
// Don't show hidden files/folders
if (!file.getName().startsWith(".")) {
// Adds the file's display name, MIME type, size, and so on.
includeFile(result, file);
}
}
return result;
}
#Override
public Cursor queryDocument(final String documentId, final String[] projection)
throws FileNotFoundException {
// Create a cursor with either the requested fields, or the default
// projection if "projection" is null.
final MatrixCursor result = new MatrixCursor(projection != null ? projection
: DEFAULT_DOCUMENT_PROJECTION);
includeFile(result, new File(documentId));
return result;
}
private void includeFile(final MatrixCursor result, final File file)
throws FileNotFoundException {
final MatrixCursor.RowBuilder row = result.newRow();
// These columns are required
row.add(Document.COLUMN_DOCUMENT_ID, file.getAbsolutePath());
row.add(Document.COLUMN_DISPLAY_NAME, file.getName());
String mimeType = getDocumentType(file.getAbsolutePath());
row.add(Document.COLUMN_MIME_TYPE, mimeType);
int flags = file.canWrite() ? Document.FLAG_SUPPORTS_DELETE | Document.FLAG_SUPPORTS_WRITE
: 0;
// We only show thumbnails for image files - expect a call to
// openDocumentThumbnail for each file that has
// this flag set
if (mimeType.startsWith("image/"))
flags |= Document.FLAG_SUPPORTS_THUMBNAIL;
row.add(Document.COLUMN_FLAGS, flags);
// COLUMN_SIZE is required, but can be null
row.add(Document.COLUMN_SIZE, file.length());
// These columns are optional
row.add(Document.COLUMN_LAST_MODIFIED, file.lastModified());
// Document.COLUMN_ICON can be a resource id identifying a custom icon.
// The system provides default icons
// based on mime type
// Document.COLUMN_SUMMARY is optional additional information about the
// file
}
#Override
public String getDocumentType(final String documentId) throws FileNotFoundException {
File file = new File(documentId);
if (file.isDirectory())
return Document.MIME_TYPE_DIR;
// From FileProvider.getType(Uri)
final int lastDot = file.getName().lastIndexOf('.');
if (lastDot >= 0) {
final String extension = file.getName().substring(lastDot + 1);
final String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
if (mime != null) {
return mime;
}
}
return "application/octet-stream";
}
#Override
public void deleteDocument(final String documentId) throws FileNotFoundException {
new File(documentId).delete();
}
#Override
public ParcelFileDescriptor openDocument(final String documentId, final String mode,
final CancellationSignal signal) throws FileNotFoundException {
File file = new File(documentId);
final boolean isWrite = (mode.indexOf('w') != -1);
if (isWrite) {
return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_WRITE);
} else {
return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
}
}
#Override
public boolean onCreate() {
return true;
}
}

Categories

Resources