inserting values into the db in android with a button click
<p>Hi I am new to android databases. I want to insert values to a table on a button click. Here is the code that I use. But an error is shown as database not open. What should I do? Please Help</p>

<p>Here is the code:</p>

<pre><code>package com.istyle;

import java.io.File;
import java.io.IOException;  

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class Profile_Page extends Activity {
    protected SQLiteDatabase sampleDB;
    private static final String DATABASE_NAME = "istyle.sqlite";

    private static final int SELECT_PICTURE = 1;
    private String selectedImagePath;
    private ImageView img;
     String readName;
      String readMail;
      EditText Name;
      EditText Email;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.profile_page);
          Name=(EditText)findViewById(R.id.editText1);
          Email=(EditText)findViewById(R.id.editText2);          

          final DataBaseHelper dbAdapter = DataBaseHelper.getInstance(this, DATABASE_NAME);             
          try {
            if (getFirstRun()) {
                sampleDB = dbAdapter.getDatabase();
                setRunned();
            } else {
            sampleDB = dbAdapter.getWritableDatabase();
            }

            Cursor c1 = sampleDB.rawQuery("SELECT * FROM USER_PROFILE WHERE user_id='1'", null);

          if (c1.moveToFirst()) {
              do{

              System.out.println(c1.getString(c1.getColumnIndex("user_id")));
            System.out.println(c1.getString(c1.getColumnIndex("user_name")));
            System.out.println(c1.getString(c1.getColumnIndex("user_email")));
                        } while (c1.moveToNext());
          }  
            Button ok=(Button)findViewById(R.id.button1);
            ok.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                     readName=Name.getText().toString();
                     readMail=Email.getText().toString();   
                     String Query="UPDATE TABLE user_profile SET user_name="+readName+" user_email="+readMail+" WHERE user_id='1'";
                     sampleDB.execSQL(Query);
                }           
            });             

            c1.close();         
            sampleDB.close();               

        } 
      catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();            
        } 

         img = (ImageView)findViewById(R.id.imageView1);
        ((Button) findViewById(R.id.button3))
        .setOnClickListener(new OnClickListener() {
             public void onClick(View arg0) {
                 Intent intent = new Intent();
                 intent.setType("image/*");
                 intent.setAction(Intent.ACTION_GET_CONTENT);


                 startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);

             }
             });         

    }

private void setRunned() {
        // TODO Auto-generated method stub

    }

private boolean getFirstRun() {
        // TODO Auto-generated method stub
        return false;
    }

public void onActivityResult(int requestCode, int resultCode, Intent data) {
                if (resultCode == RESULT_OK) {
                        if (requestCode == SELECT_PICTURE) {
                            Uri selectedImageUri = data.getData();
                            selectedImagePath = getPath(selectedImageUri);
                            System.out.println("Image Path : " + selectedImagePath);
                            img.setImageURI(selectedImageUri);
                        }
                    }
                }

    public String getPath(Uri uri) {
                    String[] projection = { MediaStore.Images.Media.DATA };
                    Cursor cursor = managedQuery(uri, projection, null, null, null);
                    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    cursor.moveToFirst();
                    return cursor.getString(column_index);
                }

}
</code></pre>

<p>Also the database helper class i use is as follows</p>

<pre><code>package com.istyle;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.util.Log;

// Modify by me 24/6/2010
public class DataBaseHelper extends SQLiteOpenHelper {
        private static SQLiteDatabase sqliteDb;
        private static DataBaseHelper instance;
        //private static final int DATABASE_VERSION = 1;
        private static final int DATABASE_VERSION = 4;
        // the default database path is :
        // /data/data/pkgNameOfYourApplication/databases/
        private static String DB_PATH_PREFIX = "/data/data/";
        private static String DB_PATH_SUFFIX = "/databases/";
        private static final String TAG = "DataBaseHelper";
        private Context context;

        /***
         * Contructor
         * 
         * @param context
         *            : app context
         * @param name
         *            : database name
         * @param factory
         *            : cursor Factory
         * @param version
         *            : DB version
         */
        private DataBaseHelper(Context context, String name,
                        CursorFactory factory, int version) {
                super(context, name, factory, version);
                this.context = context;
                Log.i(TAG, "Create or Open database : " + name);
        }

        /***
         * Initialize method
         * 
         * @param context
         *            : application context
         * @param databaseName
         *            : database name
         */
        private static void initialize(Context context, String databaseName) {
                if (instance == null) {
                        /**
                         * Try to check if there is an Original copy of DB in asset
                         * Directory
                         */
                        if (!checkDatabase(context, databaseName)) {
                                // if not exists, I try to copy from asset dir
                                try {
                                        copyDataBase(context, databaseName);
                                } catch (IOException e) {
                                        Log.e(TAG,"Database "+ databaseName + " does not exists and there is no Original Version in Asset dir");
                                }
                        }

                        Log.i(TAG, "Try to create instance of database (" + databaseName + ")");
                        instance = new DataBaseHelper(context, databaseName,
                                        null, DATABASE_VERSION);
                        sqliteDb = instance.getWritableDatabase();
                        Log.i(TAG, "instance of database (" + databaseName + ") created !");
                }
        }

        /***
         * Static method for getting singleton instance
         * 
         * @param context
         *            : application context
         * @param databaseName
         *            : database name
         * @return : singleton instance
         */
        public static final DataBaseHelper getInstance(
                        Context context, String databaseName) {
                initialize(context, databaseName);
                return instance;
        }

        /***
         * Method to get database instance
         * 
         * @return database instance
         */
        public SQLiteDatabase getDatabase() {
                return sqliteDb;
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
                Log.d(TAG, "onCreate : nothing to do");    
        }    
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.d(TAG, "onUpGrade : add column Cache_Id3 to table BUI_BUILDINGS in adcensusdb.sql. This is an upgrade");              
    }

        /***
         * Method for Copy the database from asset directory to application's data
         * directory
         * 
         * @param databaseName
         *            : database name
         * @throws IOException
         *             : exception if file does not exists
         */
        private void copyDataBase(String databaseName) throws IOException {
                copyDataBase(context, databaseName);
        }

        /***
         * Static method for copy the database from asset directory to application's
         * data directory
         * 
         * @param aContext
         *            : application context
         * @param databaseName
         *            : database name
         * @throws IOException
         *             : exception if file does not exists
         */
        private static void copyDataBase(Context aContext, String databaseName)
                        throws IOException {

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

                // Path to the just created empty db
                String outFileName = getDatabasePath(aContext, databaseName);

                Log.i(TAG, "Check if create dir : " + DB_PATH_PREFIX
                                + aContext.getPackageName() + DB_PATH_SUFFIX);

                // if the path doesn't exist first, create it
                File f = new File(DB_PATH_PREFIX + aContext.getPackageName()
                                + DB_PATH_SUFFIX);
                if (!f.exists())
                        f.mkdir();

                Log.i(TAG, "Trying to copy local DB to : " + outFileName);

                // 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)) &gt; 0) {
                        myOutput.write(buffer, 0, length);
                }

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

                Log.i(TAG, "DB (" + databaseName + ") copied!");
        }

        /***
         * Method to check if database exists in application's data directory
         * 
         * @param databaseName
         *            : database name
         * @return : boolean (true if exists)
         */
        public boolean checkDatabase(String databaseName) {
                return checkDatabase(context, databaseName);
        }

        /***
         * Static Method to check if database exists in application's data directory
         * 
         * @param aContext
         *            : application context
         * @param databaseName
         *            : database name
         * @return : boolean (true if exists)
         */
        public static boolean checkDatabase(Context aContext, String databaseName) {
                SQLiteDatabase checkDB = null;

                try {
                        String myPath = getDatabasePath(aContext, databaseName);

                        Log.i(TAG, "Trying to conntect to : " + myPath);
                        checkDB = SQLiteDatabase.openDatabase(myPath, null,
                                        SQLiteDatabase.OPEN_READONLY);
                        Log.i(TAG, "Database " + databaseName + " found!");
                        checkDB.close();
                } catch (SQLiteException e) {
                        Log.i(TAG, "Database " + databaseName + " does not exists!");

                }

                return checkDB != null ? true : false;
        }

        /***
         * Method that returns database path in the application's data directory
         * 
         * @param databaseName
         *            : database name
         * @return : complete path
         */
        private String getDatabasePath(String databaseName) {
                return getDatabasePath(context, databaseName);
        }

        /***
         * Static Method that returns database path in the application's data
         * directory
         * 
         * @param aContext
         *            : application context
         * @param databaseName
         *            : database name
         * @return : complete path
         */
        private static String getDatabasePath(Context aContext, String databaseName) {
                return DB_PATH_PREFIX + aContext.getPackageName() + DB_PATH_SUFFIX
                                + databaseName;
        }
}
</code></pre>
