Tuesday, August 6, 2013

Android SQLITE Query Browser Example | Query Browser Demo In Android | Sqlite Database Tutorial in Android

Hi Friends!
I have posted many article on sq-lite in android but they all java class base, so on many demand today I am going to share code for sq-lite using query browser in Android. For this first install Sqlite query browser in your system from below link-

And after that create new database using file menu, and after that create table like I created student table. 
    After that Create SQLiteHelper.java class in your project and extend it to SQLiteOpenHelper. and for getting and inserting data into database create SQLiteConnector.java class.

And finally you have all done just show your data on home page in listview. Please copy paste below code and enjoy.



1)MainActivity.java


package com.manish.sqlitequerybrowser;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
/**
 * 
 * @author manish.s
 *
 */

public class MainActivity extends Activity {
 ListView listStudents;
 SQLiteConnector sqlConnect;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  listStudents = (ListView) findViewById(R.id.listView1);
  sqlConnect = new SQLiteConnector(this);

  ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
    android.R.layout.simple_list_item_1, sqlConnect.getAllRecord());
  listStudents.setAdapter(adapter);

 }

}

2)SQLiteHelper.java


package com.manish.sqlitequerybrowser;

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;
/**
 * 
 * @author manish.s
 *
 */

public class SQLiteHelper extends SQLiteOpenHelper {

 private static String DB_PATH="/data/data/com.manish.sqlitequerybrowser/databases/";
 private static String DB_NAME = "mydatabase.sqlite";
 private static int VERSION =1;
 private SQLiteDatabase myDataBase;
 private final Context myContext;

 public SQLiteHelper(Context context) {
  super(context, DB_NAME, null, VERSION);
  myContext = context;
  try {
   createDatabase(); 
     } 
     catch (IOException ioe) { 
         throw new Error("Unable to create database"); 
     }
 }

 public void createDatabase() throws IOException {
  boolean dbExist = checkDataBase();

  if (dbExist) {
   System.out.println("DB EXIST");
  }

  else {
   this.getReadableDatabase();
   this.close();
   copyDataBase();
  }
 }

 private void copyDataBase() throws IOException {
  InputStream myInput = myContext.getAssets().open(DB_NAME);
  String outFileName = DB_PATH + DB_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();

 }

 private boolean checkDataBase() {
  SQLiteDatabase checkDB = null;

  try {
   String myPath = DB_PATH + DB_NAME;
   checkDB = SQLiteDatabase.openDatabase(myPath, null,
     SQLiteDatabase.OPEN_READONLY);
  } catch (SQLiteException e) {
   System.out.println("Database does't exist yet.");
  }

  if (checkDB != null) {
   checkDB.close();
  }

  return checkDB != null ? true : false;

 }

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

  super.close();
 }

 @Override
 public void onCreate(SQLiteDatabase arg0) {
 
 }

 @Override
 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  
 }

}

3)SQLiteConnector.java


package com.manish.sqlitequerybrowser;

import java.util.ArrayList;
import java.util.List;


import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
/**
 * 
 * @author manish.s
 *
 */

public class SQLiteConnector {
 
 private SQLiteDatabase database;
 private SQLiteHelper sqlHelper;
 private Cursor cursor;
 
 private static final String TABLE_RECORD = "student";
 
 public SQLiteConnector(Context context) {
  sqlHelper = new SQLiteHelper(context);
 }
 
 // Getting All records
   public List<String> getAllRecord() {
    List<String> studentList = new ArrayList<String>();
    String selectQuery = "SELECT  * FROM " + TABLE_RECORD;

    database = sqlHelper.getReadableDatabase();
    cursor = database.rawQuery(selectQuery, null);
    if (cursor.moveToFirst()) {
     do {
      studentList.add(cursor.getString(1));
      
     } while (cursor.moveToNext());
    }
    database.close();
    return studentList;
   }
 
}

4)activity_main.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentTop="true" >
    </ListView>

</RelativeLayout>

5)AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.manish.sqlitequerybrowser"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.manish.sqlitequerybrowser.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Download Zip Code

Thanks!