Friday 20 May 2016

Faster sqlite database insertion

Many a time we have the requirement to insert bulk of data into Android SQLite database, but the normal database insert() operation provided by SQLiteDatabase.java class will take more time in such situation.
So today we will see how to make database insertion faster for bulk data insertion by using transaction with database insert() operation.
Let's see a sqlite database operation example
Here I will take an example of managing student database with just insert operation


Student.java
public class Student {

   private int id;
   private String name;

   public long getId() {
      return id;
   }

   public void setId(int id) {
      this.id = id;
   }

   public String getName() {
      return this.name;
   }

   public void setName(String name) {
      this.name = name;
   }

   @Override   public String toString() {
      return name;
   }
}






DataBaseWrapper.java


import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DataBaseWrapper extends SQLiteOpenHelper {

   public static final String STUDENTS = "Students";
   public static final String STUDENT_ID = "_id";
   public static final String STUDENT_NAME = "_name";

   private static final String DATABASE_NAME = "Students.db";
   private static final int DATABASE_VERSION = 1;

  // creation SQLite statement
private static final String DATABASE_CREATE = "create table " + STUDENTS + "(" + STUDENT_ID + "" +
      " integer primary key autoincrement, " + STUDENT_NAME + " text not null);";

public DataBaseWrapper(Context context) {
   super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Overridepublic void onCreate(SQLiteDatabase db) {
   db.execSQL(DATABASE_CREATE);
}
@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
   db.execSQL("DROP TABLE IF EXISTS " + STUDENTS);
   onCreate(db);
}
}
StudentOperations.java
import android.content.ContentValues;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class StudentOperations {

   // Database fields   private DataBaseWrapper dbHelper;
   private String[] STUDENT_TABLE_COLUMNS = { DataBaseWrapper.STUDENT_ID,
 DataBaseWrapper.STUDENT_NAME };
   private SQLiteDatabase database;

   public StudentOperations(Context context) {
      dbHelper = new DataBaseWrapper(context);
   }

   public void open() throws SQLException {
      database = dbHelper.getWritableDatabase();
   }

//normal database insert operation
   public void addStudent(String name) {

      for(int i=0; i<1000;i++) {
         ContentValues values = new ContentValues();
         values.put(DataBaseWrapper.STUDENT_NAME, name);
         long studId = database.insert(DataBaseWrapper.STUDENTS, null, values);
      }
   }

//faster database insert operation
public void addStudentbulk(String name) { database.beginTransaction(); for(int i=0; i<1000;i++) { ContentValues values = new ContentValues(); values.put(DataBaseWrapper.STUDENT_NAME, name); database.insert(DataBaseWrapper.STUDENTS, null, values); } database.setTransactionSuccessful(); database.endTransaction(); } }
MainActivity.java 
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    private StudentOperations studentDBoperation;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        studentDBoperation = new StudentOperations(this);
        studentDBoperation.open();
        long startTime = System.nanoTime();
        //studentDBoperation.addStudent("Chetan");        
        studentDBoperation.addStudentbulk("Chetan");
        long endTime = System.nanoTime();
        long duration = (endTime - startTime)/1000000000;
        System.out.println("time taken : "+duration);
    }

}
You can calculate the time taken by both the operation I have also 
include the logic of time calculation to perform each operation.
You can comment the either operation and can get result
For me
Time take to insert 1000 students record is
by normal database operation operation : 
6+ seconds
by faster database operation operation :
less than one seconds
Try it yourself
Please suggest if any update.
Updates are always welcome
HAPPY CODING :)


source code  https://github.com/gaikwadChetan93/FasterDatabaseOperation

My Apps MobileUtility


Saturday 14 May 2016

Android encrypting Security key, Encryption key, and Important string


1. Many a time you are in a situation where you need store Security key, Encryption key or some important string in a safe place


2. Sometimes we have a requirement to encrypt the database but the question is, where to store the
Encryption key


3. IOS have keychain, where app can store such security keys in an encrypted form but android doesn't have any


refer this conversation on Stackoverflow
http://stackoverflow.com/questions/10990821/how-to-securely-store-credentials-password-in-android-application


So we need to find some alternative for android where we can store such information securely.

4. I found one awesome post on web using which we can store our security keys in an encrypted format using Advanced Encryption Standard or AES

here is the link to that post
https://trivedihardik.wordpress.com/tag/android-aes-example/

5.This post has also provided code for NDK support for making encryption stronger.

Please feel free to suggest an update.
Updates are always welcome.
Happy coding :)



My Apps MobileUtility

Thursday 12 May 2016

All installed apps information

We can get all the information about all the application installed on your android device.

Following  is the code using which we can get information of app like application name, size, app icon etc


1.Create a model class to store application information like app name, size icon etc
Following is the sample model class

DataDto.java

import java.io.File;

import android.graphics.drawable.Drawable;


public class DataDTO {
   public Drawable imgAppIcon;
   public String txtAppName;
   public String txtAppSize;
   public boolean txtAppStatus;
   public File file;
   public File getFile() {
      return file;
   }
   public void setFile(File file) {
      this.file = file;
   }
   public Drawable getImgAppIcon() {
      return imgAppIcon;
   }
   public void setImgAppIcon(Drawable drawable) {
      this.imgAppIcon = drawable;
   }
   public String getTxtAppName() {
      return txtAppName;
   }
   public void setTxtAppName(String txtAppName) {
      this.txtAppName = txtAppName;
   }
   public String getTxtAppSize() {
      return txtAppSize;
   }
   public void setTxtAppSize(String txtAppSize) {
      this.txtAppSize = txtAppSize;
   }
   public boolean getTxtAppStatus() {
      return txtAppStatus;
   }
   public void setTxtAppStatus(boolean txtAppStatus) {
      this.txtAppStatus = txtAppStatus;
   }

}

2.Using package manager we can extract all the application information installed on your android device.

ArrayList<DataDTO> list = new ArrayList<DataDTO>();

final PackageManager packageManager = getPackageManager();
Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
final List pkgAppsList = packageManager.queryIntentActivities( intent, 0);
for (Object object : pkgAppsList) {

   ResolveInfo info = (ResolveInfo) object;

   //Get application apk   File f1 =new File( info.activityInfo.applicationInfo.publicSourceDir);

   Log.v("file--", " "+f1.getName().toString()+"----"+info.loadLabel(packageManager));

   String file_name = info.loadLabel(packageManager).toString();
   DataDTO dataDTO = new DataDTO();

   dataDTO.setTxtAppStatus(isPresent(file_name));

   //Get application name   dataDTO.setTxtAppName(file_name);

   //Get application icon   dataDTO.setImgAppIcon(info.loadIcon(packageManager));

   int size= (int) (f1.length()/1024);

   //Get application size   if( size <=1024 ) {
      dataDTO.setTxtAppSize(size+" KB");
   } else {
      float a = (float) (size/1024.00);
      double newKB = Math.round(a*100.0)/100.0;
      dataDTO.setTxtAppSize(newKB+" MB");
   }
   dataDTO.setFile(f1);

   list.add(dataDTO);
}



note : For better performance you can execute this code in an asynctask



3.You can sort the list of application information as per your requirement
following is a example of sorting by app name

//SortingCollections.sort(list, new Comparator<DataDTO>() {
   @Override   public int compare(DataDTO  obj1, DataDTO  obj2)
   {
      return  obj1.txtAppName.compareTo(obj2.getTxtAppName());
   }
});


Thanks :)

My Apps MobileUtility