DATABASE HELPER CLASS IN ANDROID:
DataBaseHandler.java
import
android.content.ContentValues;
import
android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import
android.database.sqlite.SQLiteOpenHelper;
public class DataBaseHandler extends SQLiteOpenHelper
{
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "contactsManager";
private static final String tablename = "contacts";
private static final String id = "id";
private static final String fname = "fname";
private static final String lname = "lnamer";
public DataBaseHandler(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
//3rd argument to be passed is
CursorFactory instance
}
@Override
public void
onCreate(SQLiteDatabase db)
{
// TODO Auto-generated
method stub
String
CREATE_CONTACTS_TABLE = "CREATE TABLE " + tablename + "("
+ id + " INTEGER
PRIMARY KEY," + fname + " TEXT,"
+ lname + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
@Override
public void
onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// Drop older table if existed
db.execSQL("DROP TABLE IF
EXISTS " + tablename);
// Create tables again
onCreate(db);
}
void addContact(DataDb data) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(id,data.getID());
//values.put(id,data.getID());
values.put(fname, data.getfname()); // Contact
Name
values.put(lname, data.getlname()); // Contact
Phone
// Inserting Row
db.insert(tablename, null, values);
//2nd argument is String containing
nullColumnHack
db.close(); // Closing database
connection
}
}
DataDb.java
MAPPING VARIABLES IN SQLITE
DATABASE:
package android.mydata;
public class DataDb
{
Integer
id;
String
fname;
String
lname;
public DataDb()
{
}
public DataDb(int id,String
fname,String lname)
{
this.id=id;
this.fname=fname;
this.lname=lname;
}
public Integer getID()
{
return this.id;
}
public void setID(Integer id)
{
this.id=id;
}
public String getfname()
{
return this.fname;
}
public void setfname(String
fname)
{
this.fname=fname;
}
public String getlname()
{
return this.lname;
}
public void setlname(String
lname)
{
this.lname=lname;
}
}
MainActivity.java
METHOD
TO INSERT:
public void insert(View v)
{
EditText
e1=(EditText)findViewById(R.id.editText1);
EditText
e2=(EditText)findViewById(R.id.editText2);
String
name1=e1.getText().toString();
String
name2=e2.getText().toString();
DataBaseHandler db = new DataBaseHandler(this);
Log.d("Insert:
", "Inserting
..");
db.addContact(new DataDb(1,name1, name2));
Toast.makeText(this, "DATA INSERTED..", Toast.LENGTH_LONG).show();
}
No comments:
Post a Comment