Android Database Example ,database usage, AsyncTask , Database Export

This is continuation of previous lessons on Android. In this article i would like to discuss Database Operations in Android and Concept of AsyncTask in android
AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers. This can be used in Timeconsuming processes so that UI is not obstructed

Note: As previously defined i’ve been compiling opensource Tutorials on android and selecting and modifying them to create a easy tutorial on major topics

Before working with Database ,lets create a Utility classes which can create/update/drop/insert database/tables

Here are 2 utility classes which are self explanatory


package com.linkwithweb.sqllite;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import android.provider.BaseColumns;
import android.util.Log;

/**
 * @author Ashwin Kumar
 * 
 */
public class DataBaseHelper extends SQLiteOpenHelper {

	// The Android's default system path of your application database.
	private static String DB_PATH = "/data/data/linkwithweb/databases/";

	private static String DB_NAME = "myDBName.db";

	private static final int DATABASE_VERSION = 1;

	// Table name
	public static final String TABLE_NAME = "TEST";

	private SQLiteDatabase myDataBase;

	private final Context myContext;

	private SQLiteStatement insertStmt;
	private static final String INSERT = "insert into " + TABLE_NAME
			+ "(name) values (?)";

	/**
	 * Constructor
	 * Takes and keeps a reference of the passed context in order to access to the application assets and resources.
	 * 
	 * @param context
	 */
	public DataBaseHelper(Context context) {
		super(context, DB_NAME, null, DATABASE_VERSION);
		this.myContext = context;
		this.myDataBase = getWritableDatabase();
		this.insertStmt = this.myDataBase.compileStatement(INSERT);
	}

	/**
	 * Creates a empty database on the system and rewrites it with your own database.
	 * */
	public void createDataBase() throws IOException {

		boolean dbExist = checkDataBase();

		if (dbExist) {
			// do nothing - database already exist
		} else {

			// By calling this method and empty database will be created into the default system path
			// of your application so we are gonna be able to overwrite that database with our database.
			this.getReadableDatabase();

			try {

				copyDataBase();

			} catch (IOException e) {

				throw new Error("Error copying database");

			}
		}

	}

	/**
	 * Check if the database already exist to avoid re-copying the file each time you open the application.
	 * 
	 * @return true if it exists, false if it doesn't
	 */
	private boolean checkDataBase() {

		SQLiteDatabase checkDB = null;

		try {
			String myPath = DB_PATH + DB_NAME;
			checkDB = SQLiteDatabase.openDatabase(myPath, null,
					SQLiteDatabase.OPEN_READONLY);

		} catch (SQLiteException e) {

			// database does't exist yet.

		}

		if (checkDB != null) {

			checkDB.close();

		}

		return checkDB != null ? true : false;
	}

	/**
	 * Copies your database from your local assets-folder to the just created empty database in the
	 * system folder, from where it can be accessed and handled.
	 * This is done by transfering bytestream.
	 * */
	private void copyDataBase() throws IOException {

		// Open your local db as the input stream
		InputStream myInput = myContext.getAssets().open(DB_NAME);

		// Path to the just created empty db
		String outFileName = DB_PATH + DB_NAME;

		// Open the empty db as the output stream
		OutputStream myOutput = new FileOutputStream(outFileName);

		// transfer bytes from the inputfile to the outputfile
		byte[] buffer = new byte[1024];
		int length;
		while ((length = myInput.read(buffer)) > 0) {
			myOutput.write(buffer, 0, length);
		}

		// Close the streams
		myOutput.flush();
		myOutput.close();
		myInput.close();

	}

	/**
	 * @throws SQLException
	 */
	public void openDataBase() throws SQLException {
		// Open the database
		String myPath = DB_PATH + DB_NAME;
		myDataBase = SQLiteDatabase.openDatabase(myPath, null,
				SQLiteDatabase.OPEN_READONLY);

	}

	@Override
	public synchronized void close() {
		if (myDataBase != null)
			myDataBase.close();

		super.close();

	}

	public SQLiteDatabase getDb() {
		return myDataBase;
	}

	/**
	 * Compiled Insert Statement
	 * 
	 * @param name
	 * @return
	 */
	public long insert(String name) {
		this.insertStmt.bindString(1, name);
		return this.insertStmt.executeInsert();
	}

	/**
	 * 
	 */
	public void deleteAll() {
		this.myDataBase.delete(TABLE_NAME, null, null);
	}

	/**
	 * @return
	 */
	public List selectAll() {
		List list = new ArrayList();
		Cursor cursor = this.myDataBase.query(TABLE_NAME,
				new String[] { "name" }, null, null, null, null, "name desc");
		if (cursor.moveToFirst()) {
			do {
				list.add(cursor.getString(0));
			} while (cursor.moveToNext());
		}
		if (cursor != null && !cursor.isClosed()) {
			cursor.close();
		}
		return list;
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		String sql = "create table " + TABLE_NAME + "( " + BaseColumns._ID
				+ " integer primary key autoincrement, name text not null);";
		Log.d("EventsData", "onCreate: " + sql);
		db.execSQL(sql);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		if (oldVersion >= newVersion)
			return;

		String sql = null;
		if (oldVersion == 1)
			sql = "alter table " + TABLE_NAME + " add COLUMN_2 text;";
		if (oldVersion == 2)
			sql = "";

		Log.d("EventsData", "onUpgrade	: " + sql);
		if (sql != null)
			db.execSQL(sql);
	}

	// Add your public helper methods to access and get content from the database.
	// You could return cursors by doing "return myDataBase.query(....)" so it'd be easy
	// to you to create adapters for your views.

}

Now let me define my database xml exporter. Just exports any database to XML format


package com.linkwithweb.sqllite;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;
import android.util.Log;

import com.linkwithweb.MyApplication;

/**
 * Android DataExporter that allows the passed in SQLiteDatabase 
 * to be exported to external storage (SD card) in an XML format.
 * 
 * To backup a SQLite database you need only copy the database file itself
 * (on Android /data/data/APP_PACKAGE/databases/DB_NAME.db) -- you *don't* need this
 * export to XML step.
 * 
 * XML export is useful so that the data can be more easily transformed into
 * other formats and imported/exported with other tools (not for backup per se).  
 * 
 * The kernel of inspiration for this came from: 
 * http://mgmblog.com/2009/02/06/export-an-android-sqlite-db-to-an-xml-file-on-the-sd-card/. 
 * (Though I have made many changes/updates here, I did initially start from that article.)
 * 
 * @author ccollins
 *
 */
public class DataXmlExporter {

   private static final String DATASUBDIRECTORY = "exampledata";

   private SQLiteDatabase db;
   private XmlBuilder xmlBuilder;

   public DataXmlExporter(SQLiteDatabase db) {
      this.db = db;
   }

   public void export(String dbName, String exportFileNamePrefix) throws IOException {
      Log.i(MyApplication.APP_NAME, "exporting database - " + dbName + " exportFileNamePrefix=" + exportFileNamePrefix);

      this.xmlBuilder = new XmlBuilder();
      this.xmlBuilder.start(dbName);

      // get the tables
      String sql = "select * from sqlite_master";
      Cursor c = this.db.rawQuery(sql, new String[0]);
      Log.d(MyApplication.APP_NAME, "select * from sqlite_master, cur size " + c.getCount());
      if (c.moveToFirst()) {
         do {
            String tableName = c.getString(c.getColumnIndex("name"));
            Log.d(MyApplication.APP_NAME, "table name " + tableName);

            // skip metadata, sequence, and uidx (unique indexes)
            if (!tableName.equals("android_metadata") && !tableName.equals("sqlite_sequence")
                     && !tableName.startsWith("uidx")) {
               this.exportTable(tableName);
            }
         } while (c.moveToNext());
      }
      String xmlString = this.xmlBuilder.end();
      this.writeToFile(xmlString, exportFileNamePrefix + ".xml");
      Log.i(MyApplication.APP_NAME, "exporting database complete");
   }

   private void exportTable(final String tableName) throws IOException {
      Log.d(MyApplication.APP_NAME, "exporting table - " + tableName);
      this.xmlBuilder.openTable(tableName);
      String sql = "select * from " + tableName;
      Cursor c = this.db.rawQuery(sql, new String[0]);
      if (c.moveToFirst()) {
         int cols = c.getColumnCount();
         do {
            this.xmlBuilder.openRow();
            for (int i = 0; i < cols; i++) {
               this.xmlBuilder.addColumn(c.getColumnName(i), c.getString(i));
            }
            this.xmlBuilder.closeRow();
         } while (c.moveToNext());
      }
      c.close();
      this.xmlBuilder.closeTable();
   }

   private void writeToFile(String xmlString, String exportFileName) throws IOException {
      File dir = new File(Environment.getExternalStorageDirectory(), DATASUBDIRECTORY);
      if (!dir.exists()) {
         dir.mkdirs();
      }
      File file = new File(dir, exportFileName);
      file.createNewFile();

      ByteBuffer buff = ByteBuffer.wrap(xmlString.getBytes());
      FileChannel channel = new FileOutputStream(file).getChannel();
      try {
         channel.write(buff);
      } finally {
         if (channel != null)
            channel.close();
      }
   }

   /**
    * XmlBuilder is used to write XML tags (open and close, and a few attributes)
    * to a StringBuilder. Here we have nothing to do with IO or SQL, just a fancy StringBuilder. 
    * 
    * @author ccollins
    *
    */
   class XmlBuilder {
      private static final String OPEN_XML_STANZA = "";
      private static final String CLOSE_WITH_TICK = "'>";
      private static final String DB_OPEN = "<database name='";
      private static final String DB_CLOSE = "";
      private static final String TABLE_OPEN = "<table name='";
      private static final String TABLE_CLOSE = "";
      private static final String ROW_OPEN = "";
      private static final String ROW_CLOSE = "";
      private static final String COL_OPEN = "<col name='";
      private static final String COL_CLOSE = "";

      private final StringBuilder sb;

      public XmlBuilder() throws IOException {
         this.sb = new StringBuilder();
      }

      void start(String dbName) {
         this.sb.append(OPEN_XML_STANZA);
         this.sb.append(DB_OPEN + dbName + CLOSE_WITH_TICK);
      }

      String end() throws IOException {
         this.sb.append(DB_CLOSE);
         return this.sb.toString();
      }

      void openTable(String tableName) {
         this.sb.append(TABLE_OPEN + tableName + CLOSE_WITH_TICK);
      }

      void closeTable() {
         this.sb.append(TABLE_CLOSE);
      }

      void openRow() {
         this.sb.append(ROW_OPEN);
      }

      void closeRow() {
         this.sb.append(ROW_CLOSE);
      }

      void addColumn(final String name, final String val) throws IOException {
         this.sb.append(COL_OPEN + name + CLOSE_WITH_TICK + val + COL_CLOSE);
      }
   }
}


Now lets create Activity and AsyncTasks to Delete/Insert data into Database tables. Below one is sample Async Task


	private class InsertDataTask extends AsyncTask {
		private final ProgressDialog dialog = new ProgressDialog(
				DatabaseActivity.this);

		// can use UI thread here
		protected void onPreExecute() {
			this.dialog.setMessage("Inserting data...");
			this.dialog.show();
		}

		// automatically done on worker thread (separate from UI thread)
		protected Void doInBackground(final String... args) {
			DatabaseActivity.this.application.getDataHelper().insert(args[0]);
			return null;
		}

		// can use UI thread here
		protected void onPostExecute(final Void unused) {
			if (this.dialog.isShowing()) {
				this.dialog.dismiss();
			}
			// reset the output view by retrieving the new data
			// (note, this is a naive example, in the real world it might make sense
			// to have a cache of the data and just append to what is already there, or such
			// in order to cut down on expensive database operations)
			new SelectDataTask().execute();
		}
	}

Here is the Database Activity Listed. This just inserts some data into database on button click and deletes all data on another button click


/**
 * 
 */
package com.linkwithweb;

import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.linkwithweb.sqllite.ManageData;

/**
 * @author Ashwin Kumar
 * 
 */
public class DatabaseActivity extends Activity {

	private static final String NAME = "NAME";

	private static final int MENU_MANAGE = 0;

	private EditText input;
	private Button saveButton;
	private Button deleteButton;
	private TextView output;

	private MyApplication application;

	@Override
	public void onCreate(final Bundle savedInstanceState) {
		Log.d(MyApplication.APP_NAME, "onCreate");
		super.onCreate(savedInstanceState);

		this.setContentView(R.layout.dbview);

		// get "Application" object for shared state or creating of expensive resources - like DataHelper
		// (this is not recreated as often as each Activity)
		this.application = (MyApplication) this.getApplication();

		// inflate views
		this.input = (EditText) this.findViewById(R.id.in_text);
		this.saveButton = (Button) this.findViewById(R.id.save_button);
		this.deleteButton = (Button) this.findViewById(R.id.del_button);
		this.output = (TextView) this.findViewById(R.id.out_text);

		// initially populate "output" view from database
		new SelectDataTask().execute();

		// save new data to database (when save button is clicked)
		this.saveButton.setOnClickListener(new OnClickListener() {
			public void onClick(final View v) {
				new InsertDataTask().execute(DatabaseActivity.this.input
						.getText().toString());
				DatabaseActivity.this.input.setText("");
			}
		});

		// delete all data from database (when delete button is clicked)
		this.deleteButton.setOnClickListener(new OnClickListener() {
			public void onClick(final View v) {
				new DeleteDataTask().execute();
			}
		});
	}

	@Override
	public void onSaveInstanceState(final Bundle b) {
		Log.d(MyApplication.APP_NAME, "onSaveInstanceState");
		if ((this.input.getText().toString() != null)
				&& (this.input.getText().toString().length() > 0)) {
			b.putString(DatabaseActivity.NAME, this.input.getText().toString());
		}
		super.onSaveInstanceState(b);
	}

	@Override
	public void onRestoreInstanceState(final Bundle b) {
		super.onRestoreInstanceState(b);
		Log.d(MyApplication.APP_NAME, "onRestoreInstanceState");
		String name = b.getString(DatabaseActivity.NAME);
		if (name != null) {
			// use onSaveInstanceState/onRestoreInstance state to manage state when orientation is changed (and whenever restarted)
			// put some text in input box, then rotate screen, text should remain
			// COMMENT this out, and try again, text won't be there - you need to maintain this state - esp for orientation changes
			// (you can rotate the screen in the emulator by pressing 9 on numeric keypad)
			this.input.setText(name);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(final Menu menu) {
		menu.add(0, DatabaseActivity.MENU_MANAGE, 1, "Manage Database")
				.setIcon(android.R.drawable.ic_menu_manage);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(final MenuItem item) {
		switch (item.getItemId()) {
		case MENU_MANAGE:
			this.startActivity(new Intent(DatabaseActivity.this,
					ManageData.class));
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private class InsertDataTask extends AsyncTask {
		private final ProgressDialog dialog = new ProgressDialog(
				DatabaseActivity.this);

		// can use UI thread here
		protected void onPreExecute() {
			this.dialog.setMessage("Inserting data...");
			this.dialog.show();
		}

		// automatically done on worker thread (separate from UI thread)
		protected Void doInBackground(final String... args) {
			DatabaseActivity.this.application.getDataHelper().insert(args[0]);
			return null;
		}

		// can use UI thread here
		protected void onPostExecute(final Void unused) {
			if (this.dialog.isShowing()) {
				this.dialog.dismiss();
			}
			// reset the output view by retrieving the new data
			// (note, this is a naive example, in the real world it might make sense
			// to have a cache of the data and just append to what is already there, or such
			// in order to cut down on expensive database operations)
			new SelectDataTask().execute();
		}
	}

	private class SelectDataTask extends AsyncTask {
		private final ProgressDialog dialog = new ProgressDialog(
				DatabaseActivity.this);

		// can use UI thread here
		protected void onPreExecute() {
			this.dialog.setMessage("Selecting data...");
			this.dialog.show();
		}

		// automatically done on worker thread (separate from UI thread)
		protected String doInBackground(final String... args) {
			List names = DatabaseActivity.this.application
					.getDataHelper().selectAll();
			StringBuilder sb = new StringBuilder();
			for (String name : names) {
				sb.append(name + "\n");
			}
			return sb.toString();
		}

		// can use UI thread here
		protected void onPostExecute(final String result) {
			if (this.dialog.isShowing()) {
				this.dialog.dismiss();
			}
			DatabaseActivity.this.output.setText(result);
		}
	}

	private class DeleteDataTask extends AsyncTask {
		private final ProgressDialog dialog = new ProgressDialog(
				DatabaseActivity.this);

		// can use UI thread here
		protected void onPreExecute() {
			this.dialog.setMessage("Deleting data...");
			this.dialog.show();
		}

		// automatically done on worker thread (separate from UI thread)
		protected Void doInBackground(final String... args) {
			DatabaseActivity.this.application.getDataHelper().deleteAll();
			return null;
		}

		// can use UI thread here
		protected void onPostExecute(final Void unused) {
			if (this.dialog.isShowing()) {
				this.dialog.dismiss();
			}
			// reset the output view by retrieving the new data
			// (note, this is a naive example, in the real world it might make sense
			// to have a cache of the data and just append to what is already there, or such
			// in order to cut down on expensive database operations)
			new SelectDataTask().execute();
		}
	}
}


Attached is the eclipse project with all examples(Rename .doc to .zip to extract to workspace)
AndroidLessons

You can also checkout code from
http://linkwithweb.googlecode.com/svn/trunk/Android/AndroidLessons/

Advertisements

8 thoughts on “Android Database Example ,database usage, AsyncTask , Database Export

  1. I don’t know if anyone is monitoring this or not, but if so, has anyone seen this type of error? Know how to resolve it?

    ERROR/AndroidRuntime(427): at com.jacobbstoneglobal.mood.ManageData$ExportDataAsXmlTask.doInBackground(ManageData.java:169)

  2. Could you please suggest me how to use the DataXmlExporter class? I already have the class that extends SQLiteOpenHelper, but I don’t understand when I should to call it and how.

  3. Just an addition:

    in createDataBase() there is the following check;

    this.getReadableDatabase();

    This checks if there is already a database with the provided name and if not creates an empty database such that it can be overwritten with the one in the assets folder. On newer devices this works flawlessly but there are some devices on which this doesn’t work. Mainly older devices. I do not know exactly why, but it seems like the getReadableDatabase() function not only gets the database but also opens it. If you then copy the database from the assets folder over it, it still has the pointer to an empty database and you will get table does not exist errors.

    So in order to make it work on all devices you should modify it to the following lines:

    SQLiteDatabase db = this.getReadableDatabase();
    if (db.isOpen()){
    db.close();
    }

    Even if the database is opened in the check, it is closed thereafter and it will not give you any more trouble.

  4. THIS IS MY DBAdapter.java
    public class DBAdapter extends SQLiteOpenHelper
    {

    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = “BalesUtaro.db”;
    public static final String TABLE_NAME=”BaleTable”;
    public static final String COLUMN_ID=”Id”;
    public static final String COLUMN_LOOSERUE=”LooseRue”;
    public static final String COLUMN_KAPASIYAUTARO=”KapasiyaUtaro”;
    public static final String COLUMN_EXPENSE=”Expense”;
    public static final String COLUMN_KAPASRATEFROM=”KapasRateFrom”;
    public static final String COLUMN_KAPASRATETO=”KapasRateTo”;
    public static final String COLUMN_KAPASIYARATEFROM=”KapasiyaRateFrom”;
    public static final String COLUMN_KAPASIYARATETO=”KapasiyaRateTo”;
    private static final String INSERT= “insert into ” + TABLE_NAME + “(name) values (?)”;

    @SuppressLint(“SdCardPath”)

    private final Context myContext;
    private SQLiteDatabase myDB;
    private SQLiteStatement insertStmt;

    /**
    * Check db.If it exists,open it else create db.
    *
    * @param context
    */
    public DBAdapter(Context myContext)
    {
    super(myContext, DATABASE_NAME, null, DATABASE_VERSION);
    this.myContext = myContext;
    this.myDB = getWritableDatabase();
    this.insertStmt = this.myDB.compileStatement(INSERT);
    }

    /**
    * Database creation
    * @throws IOException
    */
    public void createdatabase() throws IOException
    {
    boolean dbexist = checkdatabase();
    myDB = this.getReadableDatabase();
    if (dbexist)
    {
    Log.d(“DataBase”, “Database exists”);
    }
    else
    {
    this.getReadableDatabase();
    try
    {
    copyDataBase();
    }
    catch (IOException e)
    {
    throw new Error(“Error copying database”);
    }
    }
    }

    /**
    * Check Database whether it exists or not
    * @return
    */
    private boolean checkdatabase()
    {
    SQLiteDatabase checkDB = null;

    try {
    String myPath = DATABASE_NAME;
    checkDB = SQLiteDatabase.openDatabase(myPath, null,SQLiteDatabase.OPEN_READONLY);

    } catch (SQLiteException e) {

    // database does’t exist yet.

    }

    if (checkDB != null) {

    checkDB.close();

    }

    return checkDB != null ? true : false;
    }
    /**
    * Copy Database from www folder to phone memory
    *
    * @throws IOException
    */
    private void copyDataBase() throws IOException
    {
    InputStream myInput = myContext.getAssets().open(DATABASE_NAME);

    String outFileName = DATABASE_NAME;

    OutputStream myOutput = new FileOutputStream(outFileName);

    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer)) > 0)
    {
    myOutput.write(buffer, 0, length);
    }

    myOutput.flush();
    myOutput.close();
    myInput.close();
    }

    /**
    * Open Database
    *
    * @return
    * @throws SQLException
    */
    public void openDataBase() throws SQLException {

    String myPath = DATABASE_NAME;
    myDB = SQLiteDatabase.openDatabase(myPath, null,
    SQLiteDatabase.OPEN_READWRITE);

    }
    /**
    * Close DB.
    */
    @Override
    public synchronized void close()
    {
    if (myDB != null)
    myDB.close();
    super.close();
    }
    public SQLiteDatabase getDb() {
    return myDB;
    }
    public long insert(String name)
    {
    this.insertStmt.bindString(1, name);
    return this.insertStmt.executeInsert();
    }

    /**
    *
    */
    public void deleteAll() {
    this.myDB.delete(TABLE_NAME, null, null);
    }

    /**
    * @return
    */
    @SuppressWarnings({ “rawtypes”, “unchecked” })
    public List selectAll() {
    List list = new ArrayList();
    Cursor cursor = this.myDB.query(TABLE_NAME,
    new String[] { “name” }, null, null, null, null, “name desc”);
    if (cursor.moveToFirst())
    {
    do {
    list.add(cursor.getString(0));
    }
    while (cursor.moveToNext());
    }
    if (cursor != null && !cursor.isClosed()) {
    cursor.close();
    }
    return list;
    }

    @Override
    public void onCreate(SQLiteDatabase db)
    {
    String sql = “create table ” + TABLE_NAME + “(” + COLUMN_ID + ” INTEGER PRIMARY KEY, ”
    + COLUMN_LOOSERUE +” NUMERIC,”+ COLUMN_KAPASIYAUTARO +” NUMERIC,”+ COLUMN_EXPENSE +” NUMERIC,”+ COLUMN_KAPASRATEFROM +” NUMERIC,”+ COLUMN_KAPASRATETO +” NUMERIC,”+ COLUMN_KAPASIYARATEFROM +” NUMERIC,”+ COLUMN_KAPASIYARATETO +” NUMERIC);”;
    Log.d(“EventsData”, “onCreate: ” + sql);
    db.execSQL(sql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
    if (oldVersion >= newVersion)
    return;

    String sql = null;
    if (oldVersion == 1)
    sql = “alter table ” + TABLE_NAME + ” add COLUMN_2 text;”;
    if (oldVersion == 2)
    sql = “”;

    Log.d(“EventsData”, “onUpgrade : ” + sql);
    if (sql != null)
    db.execSQL(sql);

    }

    }
    and this is secondactivity.java
    public class SecondActivity extends Activity implements OnClickListener {
    EditText looseRueUtaro;
    EditText kapasiyaUtaro;
    EditText expense;
    EditText kapasRateFrom;
    EditText kapasRateTo;
    EditText kapasiyaRateFrom;
    EditText kapasiyaRateTo;
    TextView txtLooseRue;
    TextView txtKapasiyaUtaro;
    TextView txtexpense;
    TextView txtkapasRateFrom;
    TextView txtkapasRateTo;
    TextView txtkapasiyaRateFrom;
    TextView txtkapasiyaRateTo;
    TextView txtRoundOff;
    Button refresh;
    Intent refreshIntent;
    RadioGroup rg;
    RadioButton yes;
    RadioButton no;
    DBAdapter dba;
    SQLiteDatabase database;

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.second_main);
    looseRueUtaro = (EditText)findViewById(R.id.elooserue);
    kapasiyaUtaro = (EditText)findViewById(R.id.ekapasiyautaro);
    expense = (EditText)findViewById(R.id.eexpense);
    kapasRateFrom = (EditText)findViewById(R.id.ekapasratefrom);
    kapasRateTo = (EditText)findViewById(R.id.ekapasrateto);
    kapasiyaRateFrom = (EditText)findViewById(R.id.ekapasiyaratefrom);
    kapasiyaRateTo = (EditText)findViewById(R.id.ekapasiyarateto);
    txtLooseRue = (TextView)findViewById(R.id.tlooserue);
    txtKapasiyaUtaro = (TextView)findViewById(R.id.tkapasiyautaro);
    txtexpense = (TextView)findViewById(R.id.texpense);
    txtkapasRateFrom = (TextView)findViewById(R.id.tkapasratefrom);
    txtkapasRateTo = (TextView)findViewById(R.id.tkapasrateto);
    txtkapasiyaRateFrom = (TextView)findViewById(R.id.tkapasiyaratefrom);
    txtkapasiyaRateTo = (TextView)findViewById(R.id.tkapasiyarateto);
    txtRoundOff = (TextView)findViewById(R.id.troundoff);
    rg=(RadioGroup)findViewById(R.id.radioGroup);
    yes=(RadioButton)findViewById(R.id.ryes);
    no=(RadioButton)findViewById(R.id.rno);
    refresh=(Button)findViewById(R.id.refresh1);
    refresh.setOnClickListener(this);
    }
    public void onRadioButtonClicked(View view) {
    // Is the button now checked?
    boolean checked = ((RadioButton) view).isChecked();

    // Check which radio button was clicked
    switch(view.getId()) {
    case R.id.ryes:
    if (checked)
    break;
    case R.id.rno:
    if (checked)
    break;
    }
    }
    public void onClick(View v) {
    // insert data into database
    getTextAndStoreIntoDB();
    // /////////////
    refreshIntent = new Intent(v.getContext(), ThirdActivity.class);
    Toast.makeText(SecondActivity.this, “Saved Successfully!!!”,
    Toast.LENGTH_LONG).show();
    startActivityForResult(refreshIntent, 0);

    }

    @SuppressWarnings(“unused”)
    public void getTextAndStoreIntoDB() {
    String looseRue = looseRueUtaro.getText().toString();
    String kapasiya = kapasiyaUtaro.getText().toString();
    String expenseStr = expense.getText().toString();
    String kapasRateFr = kapasRateFrom.getText().toString();
    String kapasRateto = kapasRateTo.getText().toString();
    String kapasiyaRateFr = kapasiyaRateFrom.getText().toString();
    String kapasiyaRateto = kapasiyaRateTo.getText().toString();
    String[] columns = { DBAdapter.COLUMN_LOOSERUE,
    DBAdapter.COLUMN_KAPASIYAUTARO,
    DBAdapter.COLUMN_EXPENSE,
    DBAdapter.COLUMN_KAPASRATEFROM,
    DBAdapter.COLUMN_KAPASRATETO,
    DBAdapter.COLUMN_KAPASIYARATEFROM,
    DBAdapter.COLUMN_KAPASIYARATETO};
    Object[] values = { looseRue, kapasiya, expenseStr,
    kapasRateFr, kapasRateto,kapasiyaRateFr , kapasiyaRateto };
    dba = new DBAdapter(getApplicationContext());
    database = dba.getWritableDatabase();

    }

    public int convertStringToInt(String data)
    {
    try
    {
    return Integer.parseInt(data);
    }
    catch (Exception e)
    {
    return 0;

    }

    }

    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s