Pages

Monday, February 4, 2013

Used your existing SQLite database file in Android Application

Here, I am posting to how to use existing SQLite database file in android application. follow below steps.

1. Make the SQLite database file.

If you don't have a sqlite manager I recommend you to download the opensource SQLite Database Browser available for Win/Linux/Mac. Make database file.

2. Use this database in your Android application.

Now put your database file in the "assets" folder of your project and create a Database Helper class by extending the SQLiteOpenHelper class


public class Databasehelper extends SQLiteOpenHelper
{
      private SQLiteDatabase myDataBase;
      private final Context myContext;
      private static final String DATABASE_NAME = "db.sqlite";
      public final static String DATABASE_PATH = "";
      public static final int DATABASE_VERSION = 1;
      //public static final int DATABASE_VERSION_old = 1;
      //Constructor

      public Databasehelper(Context context)
      {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
            this.myContext = context;
            DATABASE_PATH = myContext.getDatabasePath(DATABASE_NAME).toString();
      }

      //Create a empty database on the system
      public void createDatabase() throws IOException
      {
           boolean dbExist = checkDataBase();
            if(dbExist)
            {
                  Log.v("DB Exists", "db exists");
                  // By calling this method here onUpgrade will be called on a
                  // writeable database, but only if the version number has been
                  // bumped
                  //onUpgrade(myDataBase, DATABASE_VERSION_old, DATABASE_VERSION);
           }         
            boolean dbExist1 = checkDataBase();
            if(!dbExist1)
            {
                  this.getReadableDatabase();
                  try
                  {
                        this.close();    
                        copyDataBase();
                  }
                  catch (IOException e)
                  {
                        throw new Error("Error copying database");
                  }
            }
      }

      //Check database already exist or not
      private boolean checkDataBase()
      {
            boolean checkDB = false;
            try
            {
                  String myPath = DATABASE_PATH;
                  File dbfile = new File(myPath);
                  checkDB = dbfile.exists();
            }
            catch(SQLiteException e)
            {
            }
            return checkDB;
      }

      //Copies your database from your local assets-folder to the just created empty database in the system folder

      private void copyDataBase() throws IOException
      {
            String outFileName = DATABASE_PATH;
            OutputStream myOutput = new FileOutputStream(outFileName);
            InputStream myInput = myContext.getAssets().open(DATABASE_NAME);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = myInput.read(buffer)) > 0)
            {
                  myOutput.write(buffer, 0, length);
            }
            myInput.close();
            myOutput.flush();
            myOutput.close();
      }

      //delete database
      public void db_delete()
      {
            File file = new File(DATABASE_PATH);
            if(file.exists())
            {
                  file.delete();
                  System.out.println("delete database file.");
            }
      }

      //Open database
      public void openDatabase() throws SQLException
      {
            String myPath = DATABASE_PATH;
            myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
      }

      public synchronized void closeDataBase()throws SQLException
      {
            if(myDataBase != null)
                  myDataBase.close();
            super.close();
      }

      public void onCreate(SQLiteDatabase db)
      {
      }

      public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
      {    
            if (newVersion > oldVersion)
            {
                  Log.v("Database Upgrade", "Database version higher than old.");
                  db_delete();
            }
      }
      //add your public methods for insert, get, delete and update data in database.
}
Now you can create a new instance of this DataBaseHelper class and call the createDataBase() and openDataBase() methods.


DataBaseHelper myDbHelper = new DataBaseHelper();
    myDbHelper = new DataBaseHelper(this);
    try {
          myDbHelper.createDataBase();
    } catch (IOException ioe) {
          throw new Error("Unable to create database");
    }
    try {
          myDbHelper.openDataBase();
    }catch(SQLException sqle){
          throw sqle;
    }


Friday, February 1, 2013

Enable & Disable Key Lock In android Application

key Lock Enable and Disable in android application



Function for Disable Keylock

// object....


KeyguardManager keyguardManager;
KeyguardLock lock;

public void Disable_AutoLock() {   
 getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
 keyguardManager = (KeyguardManager) getSystemService(Activity.KEYGUARD_SERVICE);
 lock = keyguardManager.newKeyguardLock(KEYGUARD_SERVICE);       
 lock.disableKeyguard();
}

Function for enable KeyLock


public void Enable_AutoLock()
{
   lock.reenableKeyguard();
}

Need to add permission in AndoridManifest.xml 
  

<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

   



Sorting ArrayList (String ArrayList and custom class)

 1. String array List order by... use to Collection.sort(arrayList)..


List<String> arrString = new ArrayList<String>();
  
Collections.sort(arrString, new Comparator<String>(){
      public int compare(String obj1, String obj2)
      {
            // TODO Auto-generated method stub
            return obj1.compareToIgnoreCase(obj2);
      }
});


2. Custom class Array List order by.. use to Collection.sort(arraylist)..


//student.java class define public String object.....

class student 
{
      public String name;
      public int rollno;
      public String phone_no;
}

//ArrayList....


List<student> arrStudent = new ArrayList<student>();
arrStudent.add( new student("dddd",45,"755555"));
arrStudent.add( new student("zzzz",45,"345345"));
arrStudent.add( new student("cccc",45,"888888"));
arrStudent.add( new student("qqqq",1,"123123"));
arrStudent.add( new student("llll",12,"123123"));
arrStudent.add( new student("pppp",65,"123123"));
arrStudent.add( new student("hhhh",4,"123123"));
arrStudent.add( new student("bbbb",78,"123123"));
arrStudent.add( new student("abbb",3,"123123"));

//then i want to order by student name then... use this ..

Collections.sort(arrStudent, new Comparator<student>(){
      public int compare(student obj1, student obj2)
      {
            // TODO Auto-generated method stub
            return obj1.name.compareToIgnoreCase(obj2.name);
      }
});

//Sorting student roll number Ascending Order

 Collections.sort(arrStudent, new Comparator<student>(){
  public int compare(student obj1, student obj2)
  {
    // TODO Auto-generated method stub
    return (obj1.rollno < obj2.rollno) ? -1: (obj1.rollno > obj2.rollno) ? 1:0 ;
  }
}); 


//Sorting student roll number Descending Order

 Collections.sort(arrStudent, new Comparator<student>(){
  public int compare(student obj1, student obj2)
  {
    // TODO Auto-generated method stub
    return (obj1.rollno > obj2.rollno) ? -1: (obj1.rollno > obj2.rollno) ? 1:0 ;
  }
}); 


Other Post

- How to use custom contains method in an ArrayList in android?