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!
Related
Hello friends i want to generate csv file in my application in following format
Whne in android i get followign type csv
My code is a follows.
private class ExportDatabaseCSVTask extends AsyncTask<String, Void, Boolean>{
File exportDir;
File filerootAccount;
String mStringGenerateFileName="";
CSVWriter csvWrite;
#Override
public void onPreExecute() {
mCustomProgressDialog=new CustomProgressDialog(getActivity());
mCustomProgressDialog.show("");
}
public Boolean doInBackground(final String... args){
try {
if (mStringCurrentState.equalsIgnoreCase("Month")) {
if (mAllMethods.isSDCARDPResent()==true) {
exportDir = new File(getExternalStorageDirectory()+"/Month");
}
else {
exportDir = new File(getActivity().getCacheDir() ,"/Month");
}
if (!exportDir.exists()) {
exportDir.mkdirs();
}
mStringGenerateFileName=String.valueOf(mTextViewChoiseTitle.getText().toString().trim())+".csv";
filerootAccount = new File(exportDir, mStringGenerateFileName);
System.out.println("filerootAccount "+filerootAccount.toString());
System.out.println("mStringGenerateFileName "+mStringGenerateFileName);
filerootAccount.createNewFile();
csvWrite = new CSVWriter(new FileWriter(filerootAccount));
String Title="Financial Report for "+mTextViewTitle.getText().toString().trim();
csvWrite.writeNext(Title);
String Title1="Property Address : "+mStringPropertyAddress;
csvWrite.writeNext(Title1);
List<CartData>mListAccount=new ArrayList<CartData>();
CartData acc=new CartData();
String Title11="Month : "+mTextViewChoiseTitle.getText().toString().trim();
csvWrite.writeNext(Title11);
// this is the Column of the table and same for Header of CSV file
String arrStracc[] ={"Unit","Type","Income","Expense"};
csvWrite.writeNext(arrStracc);
CartData acc1=new CartData();
if (mArrayListFinRentDatas.size()>0) {
for (int i = 0; i < mArrayListFinRentDatas.size(); i++) {
acc1.setAmount(mAllMethods.AmountForamte(mArrayListFinRentDatas.get(i).getRent_amount()));
acc1.setEtype(mArrayListFinRentDatas.get(i).getIncome_cat());
mListAccount.add(acc1);
String arrStr[] ={mArrayListFinRentDatas.get(i).getUnit_name(), mArrayListFinRentDatas.get(i).getIncome_cat(),mAllMethods.AmountForamte(mArrayListFinRentDatas.get(i).getRent_amount())};
csvWrite.writeNext(arrStr);
}
}
if (mArrayListFinExpenseDatas.size()>0) {
for (int i = 0; i < mArrayListFinExpenseDatas.size(); i++) {
acc.setAmount(mAllMethods.AmountForamte(mArrayListFinExpenseDatas.get(i).getE_amount()));
System.out.println("Types "+mArrayListFinExpenseDatas.get(i).getExpense_cat());
acc.setEtype(mArrayListFinExpenseDatas.get(i).getExpense_cat());
mListAccount.add(acc);
String arrStr[] ={mArrayListFinExpenseDatas.get(i).getUnit_name(), mArrayListFinExpenseDatas.get(i).getExpense_cat(),"",mAllMethods.AmountForamte(mArrayListFinExpenseDatas.get(i).getE_amount())};
csvWrite.writeNext(arrStr);
}
}
String arrStr4[] ={ "Total","",mAllMethods.AmountForamte(mStringFinalTotalIncome),mAllMethods.AmountForamte(mStringFinalTotalExpense) };
csvWrite.writeNext(arrStr4);
List<CartData>mListAccount16=new ArrayList<CartData>();
CartData acc161=new CartData();
double profit=0.0;
profit=Double.parseDouble(mStringFinalTotalIncome)-(Double.parseDouble(mStringFinalTotalExpense) );
if (profit <0) {
double p= Math.abs(profit);
acc161.setEtype("Total Profit / Loss ");
acc161.setAmount(String.valueOf(p));
mListAccount16.add(acc161);
for(int index=0; index < mListAccount16.size(); index++)
{
acc161=mListAccount16.get(index);
String arrStr[] ={ acc161.getEtype(),"","","Loss" ,mAllMethods.AmountForamte(acc161.getAmount())};
csvWrite.writeNext(arrStr);
}
}
else if (profit ==0) {
acc161.setEtype("Total Profit / Loss ");
acc161.setAmount("0.00");
mListAccount16.add(acc161);
for(int index=0; index < mListAccount16.size(); index++)
{
acc161=mListAccount16.get(index);
String arrStr[] ={ acc161.getEtype(),"","","" ,mAllMethods.AmountForamte(acc161.getAmount())};
csvWrite.writeNext(arrStr);
}
}
else {
acc161.setEtype("Total Profit / Loss ");
acc161.setAmount(String.valueOf(profit));
mListAccount16.add(acc161);
for(int index=0; index < mListAccount16.size(); index++)
{
acc161=mListAccount16.get(index);
String arrStr[] ={ "Total Profit / Loss","", "","",mAllMethods.AmountForamte(acc161.getAmount())};
csvWrite.writeNext(arrStr);
}
}
}
csvWrite.close();
return true;
}
catch (IOException e){
Log.e("MainActivity", e.getMessage(), e);
return false;
}
}
#Override
public void onPostExecute(final Boolean success) {
mCustomProgressDialog.dismiss("");
if (success){
System.out.println("Expeort");
Toast.makeText(getActivity(), "Financial report exported successfully.", Toast.LENGTH_SHORT).show();
}
else {
mAllMethods.ShowDialog(getActivity(), "Suceess", "Export failed!", "OK");
}
}
}
My issue is i want my csv format text with bold and bigger size and also with different color as per first image so how can i make it possible ? your all suggestions are appreciably.
Not possible to add styling, font size and colors ( text formatting) in CSV files because CSV files are just container for plain text data.
So create files like :HTML or XLSX or DOCX,... which allow text formatting.
For creating .xlsx in android:
Apache POI
You can manage to get the required file by using APPAche POI lib. You can find it easily just google it. :)
Once i need this and i managed to get this by using this lib.
i hope this snippets will help you achieve what you want.
Workbook wb = new HSSFWorkbook();
Sheet sheet1 = null;
CellStyle cell = null;
// Cell style for header row
cs = wb.createCellStyle();
cs.setFillForegroundColor(HSSFColor.LIME.index);
cs.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
Font boldFont = wb.createFont();
boldFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
cs.setFont(boldFont);
sheet1 = wb.createSheet(sheetname);
cell.setCellValue("Colum name");
cell.setCellStyle(cs);
sheet1.setColumnWidth(size, (15 * 500));
Can any one help me to
display an excel file taking from assets folder in an android application
I can't make it out to display file.
I used POI jar file also to display that file...Please send me the code
i tried from sd card but i can't make from assets
public class MainActivity extends Activity
{
String dbStr = Environment.getExternalStorageDirectory() + "/dropbox/xls/stock1.xls";
String strHyouji="";
String[][] arrays = read();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(arrays == null)
{
strHyouji="no such file";
}
else
{
for (String[] array : arrays)
{
for (String v : array)
{
strHyouji = strHyouji + v + ",";
}
strHyouji = strHyouji + "\n";
}
}
TextView textSetting = (TextView) findViewById(R.id.textView1);
textSetting.setText(strHyouji);
}
public String[][] read()
{
Workbook workbook = null;
try
{
WorkbookSettings ws = new WorkbookSettings();
ws.setGCDisabled(true);
workbook = Workbook.getWorkbook(new File(dbStr), ws);
Sheet sheet = workbook.getSheet(0);
int rowCount = sheet.getRows();
String[][] result = new String[rowCount][];
for (int i = 0; i < rowCount; i++)
{
Cell[] row = sheet.getRow(i);
result[i] = new String[row.length];
for (int j = 0; j < row.length; j++)
{
result[i][j] = row[j].getContents();
}
}
return result;
}
catch (BiffException e)
{
strHyouji=strHyouji+ e.toString();
}
catch (IOException e)
{
strHyouji=strHyouji+ e.toString();
}
catch (Exception e)
{
strHyouji=strHyouji+ e.toString();
}
finally
{
if (workbook != null)
{
workbook.close();
}
}
return null;
}
}
Mail : ravitejabrt#gmail.com
Late response.But it will be used for someone...
Try this...
Don't forget to have Excel file in AssetFolder.
public class MainActivity extends ActionBarActivity implements OnClickListener {
private Button btnReadExcel1;
AssetManager assetManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnReadExcel1 = (Button) findViewById(R.id.btnReadExcel1);
btnReadExcel1.setOnClickListener(this);
assetManager = getAssets();
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.btnReadExcel1) {
readExcelFileFromAssets();
}
}
public void readExcelFileFromAssets() {
try {
// Creating Input Stream
/*
* File file = new File( filename); FileInputStream myInput = new
* FileInputStream(file);
*/
InputStream myInput;
// Don't forget to Change to your assets folder excel sheet
myInput = assetManager.open("contacts.xls");
// Create a POIFSFileSystem object
POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);
// Create a workbook using the File System
HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);
// Get the first sheet from workbook
HSSFSheet mySheet = myWorkBook.getSheetAt(0);
/** We now need something to iterate through the cells. **/
Iterator<Row> rowIter = mySheet.rowIterator();
while (rowIter.hasNext()) {
HSSFRow myRow = (HSSFRow) rowIter.next();
Iterator<Cell> cellIter = myRow.cellIterator();
while (cellIter.hasNext()) {
HSSFCell myCell = (HSSFCell) cellIter.next();
Log.e("FileUtils", "Cell Value: " + myCell.toString()+ " Index :" +myCell.getColumnIndex());
// Toast.makeText(getApplicationContext(), "cell Value: " +
// myCell.toString(), Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return;
}
}
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;
}
Hi I have designed a File Explorer which I use to show some XML files and depending on the selected one I open one XML or another. Until the moment there is no problem at all and with the help of XMLPullParser I insert the text from the attributes into some ArrayLists. The problem is that IF I go back and I select another XML file these values are the same as the following XML and that happens with the following XMLs. I think that the problem is that the arrayLists don´t get empty once a new instance is called.
Here is how this works:
FileExporer where I show the files and I click on anyone.
public class MainActivity extends ListActivity {
private List<String> item = null;
private List<String> path = null;
private String root;
private TextView myPath;
static File file;
static String texto;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myPath = (TextView)findViewById(R.id.path);
root = Environment.getExternalStorageDirectory().getPath();
getDir(root);
}
private void getDir(String dirPath)
{
myPath.setText("Location: " + dirPath);
item = new ArrayList<String>();
path = new ArrayList<String>();
File f = new File(dirPath);
File[] files = f.listFiles();
if(!dirPath.equals(root))
{
item.add(root);
path.add(root);
item.add("../");
path.add(f.getParent());
}
for(int i=0; i < files.length; i++)
{
File file = files[i];
if(!file.isHidden() && file.canRead() && (file.getName().endsWith("xml"))){
path.add(file.getPath());
if(file.isDirectory()){
item.add(file.getName() + "/");
}else{
item.add(file.getName());
}
}
}
ArrayAdapter<String> fileList =
new ArrayAdapter<String>(this, R.layout.row, item);
setListAdapter(fileList);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
file = new File(path.get(position));
if (file.isDirectory())
{
if(file.canRead()){
getDir(path.get(position));
}else{
new AlertDialog.Builder(this)
.setIcon(R.drawable.ic_launcher)
.setTitle("[" + file.getName() + "] folder can't be read!")
.setPositiveButton("OK", null).show();
}
}else {
file = new File(path.get(position));
file.getName();
XMLPullParser.Parse(this);
texto = XMLPullParserHandler.getA(0);
}
Parseo();
Intent i = new Intent(MainActivity.this, Correccion.class);
startActivity(i);
MainActivity.this.finish();
}
public void Parseo(){
}
public static String fileName(){
return file.getName();
}
public static String getText(){
return texto;
}
}
XMLPullParser: It says the file that need to be read and calls a new isntance of XMLPullParserHandler.
public class XMLPullParser{
static String Fichero;
public static void Parse(Context context){
try {
List<Puntuacion> puntuacion;
XMLPullParserHandler parser = new XMLPullParserHandler();
File dir = Environment.getExternalStorageDirectory();
File yourFile = new File(dir, MainActivity.fileName());
FileInputStream iStream = new FileInputStream(yourFile);
puntuacion = parser.parse(iStream);
} catch (IOException e) {
e.printStackTrace();
}
}
}
XMLPullParserHandler: I think that here is the problem, when I create and add text to the ArrayLists: For example in this case in ArrayList a
public class XMLPullParserHandler {
List<Puntuacion> puntuaciones;
private Puntuacion puntuacion;
static List<String> nombres = new ArrayList<String>();
static List<String> a = new ArrayList<String>();
private String text;
public XMLPullParserHandler() {
// puntuaciones.clear();
// puntuaciones.removeAll(puntuaciones);
puntuaciones = new ArrayList<Puntuacion>();
;
}
public List<Puntuacion> getPuntuacion() {
return puntuaciones;
}
public List<Puntuacion> parse(InputStream is) {
XmlPullParserFactory factory = null;
XmlPullParser parser = null;
try {
factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
parser = factory.newPullParser();
parser.setInput(is, null);
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
String tagname = parser.getName();
switch (eventType) {
case XmlPullParser.START_TAG:
if (tagname.equalsIgnoreCase("TEST")) {
// create a new instance of puntuacion
puntuacion = new Puntuacion();
}
break;
case XmlPullParser.TEXT:
text = parser.getText();
break;
case XmlPullParser.END_TAG:
if (tagname.equalsIgnoreCase("TEST")) {
puntuaciones.add(puntuacion);
} else if (tagname.equalsIgnoreCase("NUMERO_ACIERTOS")) {
puntuacion.setValor_Transformado((text));
a.add(text);
Log.i("ii", text);
}
break;
default:
break;
}
eventType = parser.next();
}
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return puntuaciones;
}
public static String getNombre(int posicion){
String[] ListN = new String[nombres.size()];
ListN = nombres.toArray(ListN);
return ListN[posicion];
}
public static String getA(int posicion){
String[] ListA = new String[a.size()];
ListA = a.toArray(ListA);
return ListA[posicion];
}
}
For example if I have in this case a XML with **<NUMERO_ACIERTOS>1</NUMERO_ACIERTOS>** and after this I read another one with **<NUMERO_ACIERTOS>3</NUMERO_ACIERTOS>** in my UI I only see the value **1** because is the first that has been loaded into the arraylist.
thank you for your time and attention.
No me gustan estos:
static List<String> nombres = new ArrayList<String>();
static List<String> a = new ArrayList<String>();
They should not be static, and probably should be private:
private List<String> nombres;
private List<String> a;
I think they should be created new when you start your parse like this:
public List<Puntuacion> parse(InputStream is) {
XmlPullParserFactory factory = null;
XmlPullParser parser = null;
nombres = new ArrayList<String>();
a = new ArrayList<String>();
try {
¡Buena suerte!
This question already has answers here:
Android expandable list need help to delete item
(2 answers)
Closed 8 years ago.
public class DeleteActivity extends ExpandableListActivity {
private RingtoneAdapter expListAdapter;
int myProgress = 0;
List<String> items = new ArrayList<String>();
final Context myApp = this;
// private static final String DIRECTORY = "/system/media/audio/ringtones/";
private static final String DIRECTORY = "/sdcard/download/";
private MediaPlayer mp = new MediaPlayer();
List<String> Ringtones = new ArrayList<String>();
ArrayAdapter<String> adapter;
TextView tv, empty;
ExpandableListView exlv1;
// ListView lv1;
Boolean hasErrors = false;
int currentPosition = 0;
private static final String LOG_TAG = "MobiIntheMorning";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
refreshList();
Toast.makeText(this, "hello this is delete called", Toast.LENGTH_LONG).show();
Ringtones.remove(DIRECTORY+Ringtones.get(1));//THIS DOSE NOT GIVING ANY AFFECT
refreshList();
Intent i = new Intent(DeleteActivity.this, FindFilesByType.class);
startActivity(i);
}
public void refreshList() {
File ringtones_directory = new File(DIRECTORY);
if (!ringtones_directory.exists()) {
AlertDialog.Builder ad = new AlertDialog.Builder(
DeleteActivity.this);
ad.setTitle("Directory Not Found");
ad.setMessage("Sorry! The ringtones directory doesn't exist.");
ad.setPositiveButton("OK", null);
ad.show();
hasErrors = true;
}
if ( !ringtones_directory.canRead()) {
AlertDialog.Builder ad = new AlertDialog.Builder(
DeleteActivity.this);
ad.setTitle("Permissions");
ad.setMessage("Sorry! You don't have permission to list the files in that folder");
ad.setPositiveButton("OK", null);
ad.show();
hasErrors = true;
} else {
Ringtones = FindFiles(false);
if (Ringtones.size() < 1) {
AlertDialog.Builder ad = new AlertDialog.Builder(
DeleteActivity.this);
ad.setTitle("Permissions");
ad.setMessage("Sorry! No ringtones exists in " + DIRECTORY
+ ".");
ad.setPositiveButton("OK", null);
ad.show();
Log.e(LOG_TAG, "No ringtones were found.");
hasErrors = true;
}
}
try {
if ( !hasErrors) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
DeleteActivity.this, android.R.layout.test_list_item,
Ringtones);
ArrayList<String> GrouppList = new ArrayList<String>();
GrouppList.addAll(Ringtones);
ArrayList<ArrayList<Color>> colors = new ArrayList<ArrayList<Color>>();
for (int i = 0; i <= Ringtones.size(); i++) {
ArrayList<Color> color = new ArrayList<Color>();
color = new ArrayList<Color>();
color.add(new Color("", "", true));
colors.add(color);
}
expListAdapter = new RingtoneAdapter(this, GrouppList, colors);
Toast.makeText(this, GlobalVariable.getstrEmail(),
Toast.LENGTH_LONG).show();
Ringtones.remove(0);
// setListAdapter(expListAdapter);
exlv1 = (ExpandableListView) findViewById(R.id.expandableListView1);
this.exlv1.setAdapter(this.expListAdapter);
}
this.exlv1.setOnGroupExpandListener(new OnGroupExpandListener() {
#Override
public void onGroupExpand(int arg0) {
Toast.makeText(DeleteActivity.this, "hello" + arg0,
Toast.LENGTH_LONG).show();
GlobalVariable.SetcurrentPosition(arg0);
GlobalVariable.SetstrEmail(DIRECTORY + Ringtones.get(arg0));
}
});
} catch (Exception e) {
Toast.makeText(this, "Error " + e.toString(), Toast.LENGTH_LONG)
.show();
Log.i(LOG_TAG, e.toString());
}
}
private List<String> FindFiles(Boolean fullPath) {
final List<String> tFileList = new ArrayList<String>();
Resources resources = getResources();
// array of valid audio file extensions
String[] audioTypes = resources.getStringArray(R.array.audio);
FilenameFilter[] filter = new FilenameFilter[audioTypes.length];
int i = 0;
for (final String type : audioTypes) {
filter[i] = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith("." + type);
}
};
i++;
}
FileUtils fileUtils = new FileUtils();
File[] allMatchingFiles = fileUtils.listFilesAsArray(
new File(DIRECTORY), filter, -1);
for (File f : allMatchingFiles) {
if (fullPath) {
tFileList.add(f.getAbsolutePath());
} else {
tFileList.add(f.getName());
}
}
return tFileList;
} // find fil
#SuppressWarnings("unchecked")
public List<String> loadArray(String filename) {
try {
FileInputStream fis = new FileInputStream(filename);
GZIPInputStream gzis = new GZIPInputStream(fis);
ObjectInputStream in = new ObjectInputStream(gzis);
List<String> read_field = (List<String>) in.readObject();
in.close();
return read_field;
} catch (Exception e) {
e.getStackTrace();
}
return null;
}
public Collection<File> listFiles(File directory, FilenameFilter[] filter,
int recurse) {
Vector<File> files = new Vector<File>();
File[] entries = directory.listFiles();
if (entries != null) {
for (File entry : entries) {
for (FilenameFilter filefilter : filter) {
if (filter == null
|| filefilter.accept(directory, entry.getName())) {
files.add(entry);
Log.v(LOG_TAG, "Added: " + entry.getName());
}
}
if ((recurse <= -1) || (recurse > 0 && entry.isDirectory()))
files.addAll(listFiles(entry, filter, recurse - 1));
}
}
return files;
}
public class FileUtils {
public void saveArray(String filename, List<String> output_field) {
try {
FileOutputStream fos = new FileOutputStream(filename);
GZIPOutputStream gzos = new GZIPOutputStream(fos);
ObjectOutputStream out = new ObjectOutputStream(gzos);
out.writeObject(output_field);
out.flush();
out.close();
} catch (IOException e) {
e.getStackTrace();
}
}
public File[] listFilesAsArray(File directory, FilenameFilter[] filter,
int recurse) {
Collection<File> files = listFiles(directory, filter, recurse);
File[] arr = new File[files.size()];
return files.toArray(arr);
}
}
}
I've done some code that code fetches .mp3 files from the sdcard and displays it to me
now i am trying to delete selected item from it using
Ringtones.remove(DIRECTORY+Ringtones.get(1));
that is it should delete my first item from the list but it doesn't works for me
what is wrong i ma doing into this?
I am not able to find any silly mistakes I made here; Ringtones.remove("test.mp3"); and Ringtones.remove(1.mp3); both I've also tried.
Why are you doing
DIRECTORY + Ringtones.get(1)
Ringtones is a List so you want to be doing something like
Ringtones.remove(1);
or
Ringtones.remove(aRintoneString)
what you effectively doing here is getting the first element and adding a other string which gives you a NEW third string that doesn't exist in Ringtones
Hi Call notifyDataSetChanged() on your Adapter after removing the item from the List.
It will refresh your List and you will get updated items in your list.