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 HUNDRED&q…

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

  1. where do the first three bits of code go?

    ReplyDelete
  2. how to use database query to display multiple rows from a certain row id to another

    ReplyDelete

Post a Comment

Popular posts from this blog

Spinner with multiple selection in Android

Video Output:



Source code link is added below.

Here we have a class called MultiSelectionSpinner.

In this class we have following methods.


public void setItems(String[] items)
Used to set adapter items using array of strings to this spinner. public void setItems(List items)
Used to set adapter items using list of strings to this spinner. public void setSelection(String[] selection)
Used to set selected items on this adapter using array of strings to this spinner. public void setSelection(List selection)
Used to set selected items on this adapter using list of strings to this spinner. public void setSelection(int index)
Used to set single selected item using position to this spinner. public void setSelection(int[] selectedIndices)
Used to set selected items using array of integers to this spinner. public List getSelectedStrings()
Used to get the selected items as a string public List getSelectedIndices()
Used to get the selected indexes as a list of integers

I hope this post is usef…

Simple Timer Example in android

Here is the simple example of using timer in Android
public void startTimer() { timer = new Timer(); TimerTask timerTask = new TimerTask() { @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { textView.setText(String.format(Locale.getDefault(), "%d", time)); if (time > 0) time -= 1; else { textView.setText(R.string.hello_world); btnStart.setChecked(false); } } }); } }; timer.scheduleAtFixedRate(timerTask, 0, 1000); } Full class
MainActivity.java
package com.guna.testapplication; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.CompoundButton; import android.widget.TextView; import android.widget.ToggleButton; import java.uti…

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_it…