Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!

cursorToCSV

By: praveen on Oct 10th, 2011  |  syntax: None  |  size: 0.94 KB  |  views: 289  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1.         private int cursorToCSV(Cursor cursor, String file)
  2.         {
  3.                 // TODO Auto-generated method stub
  4.             StringBuffer out = new StringBuffer();
  5.             int count=0;
  6.            
  7.             // loop thru all the records
  8.             while (cursor.moveToNext())
  9.             {
  10.               // loop thru all the columns
  11.               for (int i = 0; i < cursor.getColumnCount(); i++)
  12.               {
  13.                 String column = cursor.getString(i);
  14.                 if (i != 0)
  15.                   out.append(",");
  16.                 out.append(column); // adds a column
  17.               }
  18.               out.append("\n");
  19.               count++;
  20.             }
  21.  
  22. //           save to a file
  23.             try
  24.             {
  25.               FileOutputStream outStream = context.openFileOutput(file, Context.MODE_PRIVATE);
  26.               outStream.write(out.toString().getBytes());
  27.               outStream.close();
  28.               Log.d("Backup", out.toString());
  29.             } catch (IOException e)
  30.             {
  31.               Log.d("Backup", "Error writing CSV to file: "+file); e.printStackTrace();
  32.             }      
  33.             return count;
  34.         }