Thursday 20 February 2014

Android Sqlite Example | Existing Sqlite DataBase | Large Sqlite DataBase | Insert , Delete, Retrieve By Sqlite DataBase


 Hello Friends Today I will write a code for large existing database (assets does not allow for insert large data in that condition break your sqlite db in multiple part for each part size must be less than 1 mb .For break large sqlite use jtsplit software)

Step 1: Create Project SqliteDemo .

Step 2 : Create Sqlite Database and save as Riteshdb.sqlite .

Step 3: Create new Table Student with two field name,phone and add some name and phone no then save it.

Step 4 : Copy your Database and paste in assets folder .

Step 5: Write this code in MainActivity


package com.ritesh.sqlitedemo;

import java.io.IOException;
import java.util.ArrayList;

import android.os.Bundle;
import android.app.Activity;
import android.database.SQLException;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

public class MainActivity extends Activity {
private DatabaseHandler  databaseHandler;
EditText insertname,insertphone,entename;
Button buttonshow,Insertbutton,buttondelete;

private ListView listview;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
databaseHandler = new DatabaseHandler(MainActivity.this);
databaseHandler.createdatabase();

} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
databaseHandler.opendatabase();
} catch (SQLException sqle) {
throw sqle;
}

insertname=(EditText)findViewById(R.id.insertname);
insertphone=(EditText)findViewById(R.id.insertphone);
entename=(EditText)findViewById(R.id.entename);

Insertbutton=(Button)findViewById(R.id.Insertbutton);
buttonshow=(Button)findViewById(R.id.buttonshow);
buttondelete=(Button)findViewById(R.id.buttondelete);
listview=(ListView)findViewById(R.id.listViewshowall);
Insertbutton.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(insertname.getText().toString().length()>0&&insertphone.getText().toString().length()>0)
{
databaseHandler.insertvalue(insertname.getText().toString(), insertphone.getText().toString());}
   }
});

buttonshow.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

ArrayList<StudentEntity> list=databaseHandler.Getvalue(entename.getText().toString());
ListViewAdapter adapter=new ListViewAdapter(MainActivity.this, list);
listview.setAdapter(adapter);



}
});

buttondelete.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (entename.getText().toString().length()>0) {
databaseHandler.DeleteValue(entename.getText().toString());
}

}
});
}
}

Step 6: Write this code in activity_main.xml

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

    <EditText
        android:id="@+id/insertname"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:hint="Insert Name"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/insertphone"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/insertname"
        android:hint="Insert Phone"
        android:ems="10" />

    <EditText
        android:id="@+id/entename"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/Insertbutton"
        android:layout_marginTop="14dp"
        android:ems="10"
        android:hint="Delete Name" />

    <Button
        android:id="@+id/buttondelete"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@+id/entename"
        android:text="Delete" />

    <Button
        android:id="@+id/buttonshow"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:layout_below="@+id/entename"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="14dp"
        android:text="ShowAll" />

    <ListView
        android:id="@+id/listViewshowall"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/buttonshow"
        android:layout_centerHorizontal="true" >

    </ListView>

    <Button
        android:id="@+id/Insertbutton"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/insertphone"
        android:layout_alignBottom="@+id/insertphone"
        android:layout_alignParentRight="true"
        android:text="Insert" />

</RelativeLayout>


Step 7: Write this code in DatabaseHandler

package com.ritesh.sqlitedemo;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import android.app.Activity;
import android.content.ContentValues;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DatabaseHandler extends SQLiteOpenHelper {

public static final String TAG = "DatabaseHandler";

private SQLiteDatabase db;
private Activity activity;
    private String DB_PATH = "/data/data/com.ritesh.sqlitedemo" + "/databases/";

private static String DB_NAME = "Riteshdb.sqlite";

public DatabaseHandler(Activity activity) throws IOException {
super(activity, DB_NAME, null, 1);
this.activity = activity;
boolean dbexist = checkdatabase();
if (dbexist) {
Log.d("Ritesh", "Database exists");
opendatabase();
} else {
System.out.println("Database doesn't exist");
createdatabase();
}
}

public void createdatabase() throws IOException {
boolean dbexist = checkdatabase();
if (dbexist) {
System.out.println(" Database exists.");
} else {
this.getReadableDatabase();
try {
copydatabase();
} catch (IOException e) {
e.printStackTrace();
}
}
}

private boolean checkdatabase() {
boolean checkdb = false;
try {
String myPath = DB_PATH + DB_NAME;
Log.d("Trong", "DB_PATH + DB_NAME " + DB_PATH + DB_NAME);
File dbfile = new File(myPath);
checkdb = dbfile.exists();
} catch (SQLiteException e) {
Log.d("Trong", "Database doesn't exist");
}
return checkdb;
}

    private void copydatabase() throws IOException {
        AssetManager am = activity.getAssets();
        OutputStream os = new FileOutputStream(DB_PATH + DB_NAME);
        byte[] b = new byte[1024];
        String[] files = am.list("");
        Arrays.sort(files);
        int r;
        
        // Split large db using jt split software and insert all in assets folder then  add it at runtime 
        
        // For multiple db replace this two line
        
        // for (int i = 1; i <= 4; i++) {
        // InputStream is = am.open("Riteshdb.sqlite"+i);
        
        // Currently I used a single db
        
        for (int i = 1; i <= 1; i++) {
            InputStream is = am.open("Riteshdb.sqlite");
            while ((r = is.read(b)) != -1) {
                os.write(b, 0, r);
            }
           Log.d("Ritesh", "Part:"+i);
            is.close();
        }
        os.close();
    }

public void opendatabase() throws SQLException {
// Open the database
String mypath = DB_PATH + DB_NAME;
db = SQLiteDatabase.openDatabase(mypath, null,
SQLiteDatabase.OPEN_READWRITE);
}

public synchronized void close() {
if (db != null) {
db.close();
}
super.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub

}

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

}


public void insertvalue(String name, String phone) {
// TODO Auto-generated method stub
ContentValues cvalue=new ContentValues();
cvalue.put("name", name);
cvalue.put("phone", phone);
db.insert("Student", null, cvalue);
}
public void DeleteValue(String value) {
// TODO Auto-generated method stub
db.delete("Student", "name="+"'"+value+"'", null) ;


}
public ArrayList<StudentEntity> Getvalue(String entername) {
ArrayList<StudentEntity> listentity = new ArrayList<StudentEntity>();
String selectQuery = "SELECT  * FROM "+"student";
    
Cursor cursor = db.rawQuery(selectQuery, null);

if (cursor.moveToFirst()) {
do {
StudentEntity sentity = new StudentEntity();
sentity.setName(cursor.getString(0));
sentity.setPhone(cursor.getString(1));
listentity.add(sentity);
} while (cursor.moveToNext());
}

// return contact list
return listentity;
}

}

Step 8 : Write this code in StudentEntity

package com.ritesh.sqlitedemo;

public class StudentEntity {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
String name;
String phone;

}


Step 9: Write this code in ListViewAdapter

package com.ritesh.sqlitedemo;

import java.util.ArrayList;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class ListViewAdapter extends BaseAdapter{
 LayoutInflater layoutinflater;
 ArrayList<StudentEntity> listhash;
 Activity activity;
 private ViewHolder holder;

 public ListViewAdapter(Activity activity,
   ArrayList<StudentEntity> list) {
  // TODO Auto-generated constructor stub
  this.listhash=list;
  this.activity=activity;
  this.layoutinflater=LayoutInflater.from(activity);
 }

 private class ViewHolder {
  public TextView tvname,phone;
 }
 @Override
 public int getCount() {
  // TODO Auto-generated method stub
  return listhash.size();
 }

 @Override
 public Object getItem(int arg0) {
  // TODO Auto-generated method stub
  return null;
 }

 @Override
 public long getItemId(int arg0) {
  // TODO Auto-generated method stub
  return 0;
 }

 @Override
 public View getView(final int position, View convertView, ViewGroup parent) {

  if (convertView == null) {
   convertView = layoutinflater.inflate(R.layout.list_item,
     null);
   holder = new ViewHolder();
   holder.tvname = (TextView) convertView
     .findViewById(R.id.text_name);
   holder.phone = (TextView) convertView
    .findViewById(R.id.texphoneno);
   
   convertView.setTag(holder);
  } else {
   holder = (ViewHolder) convertView.getTag();
  }
  holder.tvname.setText(listhash.get(position).getName());
  holder.phone.setText(listhash.get(position).getPhone());

  return convertView;
 }


}

Step 10 : Write this code in list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="70dp"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/text_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
       android:layout_marginTop="8dp"
        android:layout_marginLeft="56dp"
        android:text="Name"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/texphoneno"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/text_name"
        android:layout_alignLeft="@+id/text_name"
        android:layout_alignParentBottom="true"
        android:text="TextView" />

</RelativeLayout>

Step 11 : Write this code in your manifest file

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

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.ritesh.sqlitedemo.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>

Step 12 : Run The Project










No comments:

Post a Comment