Friday 21 February 2014

Access Database From Assets Folder In Android

How To Access Local DB From Assets Folder In Android
Step By Step  :
   1) Create Database .
   2) Check Database in local path or SD card path.
   3) Copy Database from Asset Folder.
   4) Open Database.
   5) Close Database.

1)   Create Database :
     Here Database Create means First Check database local path or SD Card Path(Which path for you given),Inside Create Database Checking and Copying database from asset folder.

For Example:
     public final void createDataBase() throws IOException {

                final boolean dbExist = checkDataBase();
                SQLiteDatabase db_Read = null;
                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.
                 //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.
                 db_Read = this.getReadableDatabase();
                 db_Read.close();
                 try {
                  copyDataBase();
                 } catch (IOException e) {
                  throw new Error("Error copying database");
                 }
                }
               }

2) Check Database local path or SD Card path :
     Its Used for check database which path you give.

For Example :

private boolean checkDataBase() {
                final File dbFile = new File(DB_PATH + DATABASE_NAME);
                return dbFile.exists();
               }


3) Copy Database from asset folder to Local path or SD Card Path :
        Its Copy Database from asset folder to local path any location, like SD card path.

For Example :
         private void copyDataBase() throws IOException {

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

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

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

                //transfer bytes from the inputfile to the outputfile
                final 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();

               }
4) Open Database :
     Its used for database read and write permission here.

For Example :
public final void openDataBase()  {
              try
              {
                     //Open the database
                       final String myPath = DB_PATH + DATABASE_NAME;
                          DataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
              }
              catch(Exception ex)
              {
                     ex.printStackTrace();
              }

5) Close Database :
     Its used for close database finished all works(get data from database or insert or update or delete data from database) once finished you must call close database.

For Example :
public final synchronized void close() {
                if (DataBase != null)
                       DataBase.close();
                super.close();
               }

Android soft keyboard hide and show event

How to Show/Hide Soft Keyboard Programmatically


To Show :
             Show Soft Keyboard when click edit text box.

          EditText objEdtTxt = (EditText) findViewById(R.id.YourEdtTextID);          InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);mgr.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);

To Hide :
            Hide Soft Keyboard method ,This method you can use any where in your application for example Layout Click Event ,Button Click Event etc...

InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(YourEdtTextObj.getWindowToken(), 0);

How To Use JDBC SQL DROID Connection In Android

Here easy way to get data from database with jdbc sql droid connection.

1)What is JDBC?
      Java database connectivity (JDBC) is the Java Soft specification of a standard application programming interface (API) that allows Java programs to access database management systems. The JDBC API consists of a set of interfaces and classes written in the Java programming language.
      Using these standard interfaces and classes, programmers can write applications that connect to databases, send queries written in structured query language (SQL), and process the results.

2)JDBC SQL Droid Connection Method:
        How to connect jdbc Sql Droid to database with sqldroidDriver.And Connection Checking ,DriverManager Connection.
private static SQLDroidConnection GetConnection() {

              if (_Connection == null) {
                     // Create new Connection
                     try {
                           try {
                                  Class.forName("org.sqldroid.SQLDroidDriver").newInstance();
                           } catch (InstantiationException e) {

                                  e.printStackTrace();
                           } catch (IllegalAccessException e) {

                                  e.printStackTrace();
                           }
                     } catch (ClassNotFoundException e) {

                           e.printStackTrace();
                     }
                     try {
                           String url = "jdbc:sqldroid:" + myPath;
                           _Connection = (SQLDroidConnection) DriverManager
                                         .getConnection(url);
                     } catch (SQLException e) {

                           e.printStackTrace();
                     }

              }
              return _Connection;
       }


3)JDBC SQL Droid GET Result Method:
     Here GET Result form database, Easy to retrieve values from SqlDroidResultSet like Dotnet.
     Query Excute is also easy,Database open and close error reduce using jDBC SQLDROID.
private static SQLDroidResultSet GetResultSet(String query)
                     throws SQLException {

              try {
                     stmt = (SQLDroidStatement) GetConnection().createStatement();
                     sqlresult = (SQLDroidResultSet) stmt.executeQuery(query);
              } catch (SQLException e) {

                     e.printStackTrace();

              }
              return sqlresult;
       }

4)Copy Database from Asset Folder :
   Here easy way to  Copy Database from Asset folder to local path or sd path.
private void copyDataBase() throws IOException {

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

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

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

                //transfer bytes from the inputfile to the outputfile
                final 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();

               }
5)Complete Example Class :
public class SampleDatabase extends SQLiteOpenHelper
{
       private static final String DATABASE_NAME = "Database Name";
       private static String DB_PATH = "Your Data Base Path(Local Path or SD Card Path)";
       private Context myContext;
       public SQLiteDatabase DataBase;
      
       static String myPath = DB_PATH + DATABASE_NAME;
       private static SQLDroidConnection _Connection = null;
       static SQLDroidStatement stmt;
       static SQLDroidResultSet sqlresult = null;
      
      
      
       public SampleDatabase(Context context) {
       super(context, DATABASE_NAME, null, 1);
       this.myContext = context;
   }  

       public final void createDataBase() throws IOException {

                final boolean dbExist = checkDataBase();
                SQLiteDatabase db_Read = null;
                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.
                 //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.
                 db_Read = this.getReadableDatabase();
                 db_Read.close();
                 try {
                  copyDataBase();
                 } catch (IOException e) {
                  throw new Error("Error copying database");
                 }
                }
               }

       private boolean checkDataBase() {
                final File dbFile = new File(DB_PATH + DATABASE_NAME);
                return dbFile.exists();
               }

       private void copyDataBase() throws IOException {

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

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

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

                //transfer bytes from the inputfile to the outputfile
                final 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();

               }

       public final void openDataBase()  {
              try
              {
                     //Open the database
                       final String myPath = DB_PATH + DATABASE_NAME;
                      DataBase = SQLiteDatabase.openDatabase(myPath, null,                                     SQLiteDatabase.OPEN_READWRITE);
              }
              catch(Exception ex)
              {
                     ex.printStackTrace();
              }
               
       }

       public final synchronized void close() {
                if (DataBase != null)
                       DataBase.close();
                super.close();
               }

       @Override
       public void onCreate(SQLiteDatabase db) {
              // TODO Auto-generated method stub
       }

       @Override
       public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
              // TODO Auto-generated method stub
             
       }
      
       private static SQLDroidConnection GetConnection() {

              if (_Connection == null) {
                     // Create new Connection
                     try {
                           try {
                                  Class.forName("org.sqldroid.SQLDroidDriver").newInstance();
                           } catch (InstantiationException e) {

                                  e.printStackTrace();
                           } catch (IllegalAccessException e) {

                                  e.printStackTrace();
                           }
                     } catch (ClassNotFoundException e) {

                           e.printStackTrace();
                     }
                     try {
                           String url = "jdbc:sqldroid:" + myPath;
                            _Connection = (SQLDroidConnection) DriverManager
                                         .getConnection(url);
                     } catch (SQLException e) {

                           e.printStackTrace();
                     }

              }
              return _Connection;
       }

       private static SQLDroidResultSet GetResultSet(String query)
                     throws SQLException {

              try {
                     stmt = (SQLDroidStatement) GetConnection().createStatement();
                     sqlresult = (SQLDroidResultSet) stmt.executeQuery(query);
              } catch (SQLException e) {

                     e.printStackTrace();

              }
              return sqlresult;
       }
      
      
      
       //Get All Company Name form Database.
       public static SQLDroidResultSet GetAllCompanyDetails() {
              SQLDroidResultSet ds = null;
              try {
                     String query = ("Select * from "+"Your Table Name");
                     ds = GetResultSet(query);

              } catch (Exception ex) {
                     ex.printStackTrace();
              }
              return ds;
       }

               

}