Skip to main content

Featured post

Simple RecyclerView example with filter option in Android

Hi Guys, Maybe you all are expert in terms of using RecyclerView in android. This blog is simple example for using filter option with RecyclerView adapter. As for now you will instantiate RecyclerView and set the adapter to RecyclerView as following way. RecyclerView list = (RecyclerView) findViewById(R.id.list); list.setLayoutManager(new LinearLayoutManager(this)); list.setHasFixedSize(true); ArrayList&ltNumber&gt numbers = new ArrayList&lt&gt(); String ONEs[] = {"ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE", "TEN"}; String TENs[] = {"ZERO", "TEN", "TWENTY", "THIRTY", "FOURTY", "FIFTY", "SIXTY", "SEVENTY", "EIGHTY", "NINETY", "HUNDRED"}; String HUNDREDS[] = {"ZERO", "HUNDRED", "TWO HUND

SQLite Databases using External DB


This is tutorial for accessing external DB from assets folder. In android We can create sqlite database by using SQLite Database Browser. Now the question is how to access this database in source code. The answer is very simple. Store the database in assets folder that is placed in project folder.


Then we can access this database in dbhelper class using

context.getAssets().open(DB_NAME);

After this we should copy this database to our root directory. Why because our SQLiteOpenHelper reads data from root directory only. for this we have to open new empty file in root directory by using.
private String DB_PATH = "/data/data/" + context.getPackageName() + "/" + "databases/";
String DB_NAME = "database";
String outFileName = DB_PATH + DB_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
then we have to copy our data to this empty file by using.
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}

Now we can access our data from root directory db to our project easily. Sample project to implement external sqlite database access in android.

DBHelper.java
package com.android.sqlite;

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.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBHelper extends SQLiteOpenHelper {

 private static String DB_NAME = "database";
 private SQLiteDatabase db;
 private final Context context;
 private String DB_PATH;

 public DBHelper(Context context) {
  super(context, DB_NAME, null, 1);
  this.context = context;
  DB_PATH = "/data/data/" + context.getPackageName() + "/" + "databases/";
 }

 public void createDataBase() throws IOException {

  boolean dbExist = checkDataBase();
  if (dbExist) {

  } else {
   this.getReadableDatabase();
   try {
    copyDataBase();
   } catch (IOException e) {
    throw new Error("Error copying database");
   }
  }
 }

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

 private void copyDataBase() throws IOException {

  InputStream myInput = context.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);
  }

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

 }

 public Cursor getData() {
  String myPath = DB_PATH + DB_NAME;
  db = SQLiteDatabase.openDatabase(myPath, null,
    SQLiteDatabase.OPEN_READONLY);
  Cursor c = db.rawQuery("SELECT * FROM master", null);
   // Note: Master is the one table in External db. Here we trying to access the records of table from external db.
  return c;
 }

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

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

And
ExternalDBActivity.java
package com.android.sqlite;

import java.io.IOException;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class ExternalDBActivity extends Activity {
 /** Called when the activity is first created. */
 DBHelper dbhelper;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  
  String[] from = new String[] { "_id", "columnName1", "columnName2" };
  int[] to = new int[] { R.id.TextView1, R.id.TextView2, R.id.TextView3 };

  dbhelper = new DBHelper(this);
  try {
   dbhelper.createDataBase();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

  Cursor c = dbhelper.getData();
  
  SimpleCursorAdapter adapter = new SimpleCursorAdapter(
    getApplicationContext(), R.layout.list, c, from, to);
  
   ListView list = (ListView) findViewById(R.id.ListView1);
  
   list.setAdapter(adapter);
 }
}

main.xml
<?xml version="1.0" encoding="utf-8"?<
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" <

    <ListView
        android:id="@+id/ListView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" <
    </ListView<

</LinearLayout<
list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center" >

    <TextView
        android:id="@+id/TextView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp" />

    <TextView
        android:id="@+id/TextView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp" />

    <TextView
        android:id="@+id/TextView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp" />

</LinearLayout>
Related article How to create and use SQLite database dynamically

Reduce your work by using SQLiteHelper.jar

Thank You

Comments

Post a Comment

Popular posts from this blog

Simple example of OCRReader in Android.

Hi Friends, Maybe you all heard/used text scanning using camera feature or extracting text from Image. But this sample made it very easy for you. You can made it in very simple line of code. You can download the source code from OCRSample and import the library as a module into your project. Example usage : MainActivity.java public class MainActivity extends AppCompatActivity { private TextView textView; private final int CAMERA_SCAN_TEXT = 0; private final int LOAD_IMAGE_RESULTS = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.textView); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_main, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSele

Simple example of using Spinner in Kotlin | Android

Though Kotlin has lot massive features to speedup the development time, here is the simple way of using Spinner in Android. In Kotlin we don't need to declare and initialize Spinner. We can simply access the id of Spinner from xml. Ex : import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.View import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.Toast import android.widget.Toast.LENGTH_LONG import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //String array. val myStrings = arrayOf("One", "Two", "Three", "Four", "Five") //Adapter for spinner mySpinner.adapter = ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_i

Set limit for fraction in decimal numbers in EditText

            Already we know that we can set which type of input the edittext should accept from user using android:inputType="numberDecimal" But there is no predefined function to set the limit for the edittext to How many digit it should accept after the decimal point from user . We can achieve this by using TextWatcher . Full code example. Following program creates a Decimal Filter. DecimalFilter.java import android.text.Editable; import android.text.InputFilter; import android.text.TextWatcher; import android.view.KeyEvent; import android.view.View; import android.view.View.OnKeyListener; import android.widget.EditText; public class DecimalFilter implements TextWatcher { int count= -1 ; EditText et; Activity activity; public DecimalFilter(EditText edittext, Activity activity) { et = edittext; this.activity = activity; } public void afterTextChanged(Editable s) { if (s.length() > 0) { String str = et.getText().toString(); et.setOnKeyListener(new OnKeyL