Android Open Source - sloop-sql C S V Cursor Serializer






From Project

Back to project page sloop-sql.

License

The source code is released under:

SloopSQL is released into the Public Domain. There are no restrictions on how you may use this code, and there is no warranty or guarantee of fitness for anything. USE AT YOUR OWN RISK (and enjoy).

If you think the Android project sloop-sql listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package com.megginson.sloopsql;
import android.database.Cursor;
import java.io.Writer;
import java.io.IOException;
/*  w  w  w  .  ja  v  a 2 s  .  c o m*/
/**
 * Write a cursor's contents out as CSV.
 */
public class CSVCursorSerializer
{

  private Cursor mCursor;

  public CSVCursorSerializer(Cursor cursor)
  {
    mCursor = cursor;
  }

  public void serialize(Writer output) throws IOException
  {
    serialize_headers(output);
    mCursor.moveToPosition(-1);
    while (mCursor.moveToNext())
    {
      serialize_row(output);
    }
  }

  private void serialize_headers(Writer output) throws IOException
  {
    for (int i = 0; i < mCursor.getColumnCount(); i++)
    {
      if (i > 0)
      {
        output.write(',');
      }
      output.write(escape_item(mCursor.getColumnName(i)));
    }
    output.write("\r\n");
  }

  private void serialize_row(Writer output) throws IOException
  {
    for (int i = 0; i < mCursor.getColumnCount(); i++)
    {
      if (i > 0)
      {
        output.write(',');
      }
      output.write(escape_item(mCursor.getString(i)));
    }
    output.write("\r\n");
  }

  private String escape_item(String s)
  {
    if (s.indexOf(',') > -1 || s.indexOf('"') > -1 || s.indexOf('\r') > -1 || s.indexOf('\n') > -1)
    {
      if (s.indexOf('"') > -1)
      {
        s = s.replace("\"", "\"\"");
      }
      return '"' + s + '"';
    }
    else
    {
      return s;
    }
  }

}




Java Source Code List

com.megginson.sloopsql.AsyncResult.java
com.megginson.sloopsql.CSVCursorSerializer.java
com.megginson.sloopsql.DatabaseHandler.java
com.megginson.sloopsql.MainActivity.java
com.megginson.sloopsql.QueryFragment.java
com.megginson.sloopsql.QueryResultAdapter.java
com.megginson.sloopsql.ScriptFragment.java
com.megginson.sloopsql.TabListener.java
com.megginson.sloopsql.TableListAdapter.java
com.megginson.sloopsql.TableListFragment.java
com.megginson.sloopsql.Util.java