Wednesday 10 August 2011

Sqlite External Database Connectivity


DataBaseHelper.java


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 android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;


public class DataBaseHelper extends SQLiteOpenHelper {
private static String DB_PATH = "/data/data/PACKAGE_NAME/databases/";  //PACKAGE_NAME= getApplicationContext().getPackageName();
private static String DB_NAME = "contacts.db";
private static SQLiteDatabase myDataBase;
private final Context myContext;


public DataBaseHelper(Context context) {


super(context, DB_NAME, null, 1);
this.myContext = context;
}


//---Create the database---
public void createDataBase() throws IOException {


//---Check whether database is already created or not---
boolean dbExist = checkDataBase();


if (dbExist) {
} else {
this.getReadableDatabase();
try {
//---If not created then copy the database---
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}


}

//--- Check whether database already created or not---
private boolean checkDataBase() {
try {
String myPath = DB_PATH + DB_NAME;
File f = new File(myPath);
if (f.exists())
return true;
else
return false;
} catch (SQLiteException e) {
e.printStackTrace();
return false;
}


}


//--- Copy the database to the output stream---
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();


}


public void openDataBase() throws SQLException {


//--- Open the database---
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);


}


@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) {


}


/**
 * Insert new contact detail in ContactMaster table
 * @param name
 * @param phone
 * @return boolean value
 */
public boolean insertContact(String name, String phone) {
boolean inserted = false;
openDataBase();
try {
ContentValues values = new ContentValues();


values.put("name", name);
values.put("phone", phone);

myDataBase.insert("contactMaster", null, values);
inserted = true;


} catch (Exception e) {
e.printStackTrace();
} finally {


myDataBase.close();
SQLiteDatabase.releaseMemory();
}


return inserted;
}


/**
 * Update contact detail
 * @param id
 * @param name
 * @param phone
 * @return boolean value
 */
public boolean updateContact(int id, String name, String phone) {
boolean updated = false;
openDataBase();
try {
ContentValues values = new ContentValues();


values.put("name", name);
values.put("phone", phone);

myDataBase.update("contactMaster", values, "Id = " + id, null);

updated = true;


} catch (Exception e) {
e.printStackTrace();
} finally {


myDataBase.close();
SQLiteDatabase.releaseMemory();
}
return updated;
}

/**
 * Delete the contact detail of the id passed from ContactMaster table 
 * @param id
 * @return booleane value
 */
public boolean deleteContact(int id) {
boolean deleted = false;
openDataBase();
try {

myDataBase.delete("contactMaster", "Id = " + id, null);
deleted = true;


} catch (Exception e) {
e.printStackTrace();
} finally {


myDataBase.close();
SQLiteDatabase.releaseMemory();
}
return deleted;
}

/**
 * Get all the contacts from the ContactMaster table
 * @return ArrayList<ContactModel>
 */
public ArrayList<ContactModel> getContacts() {


ArrayList<ContactModel> contacts = null;
openDataBase();
Cursor c;


String select = "Select * from contactMaster";
try {
c = myDataBase.rawQuery(select, null);
contacts = new ArrayList<ContactModel>();


for (int i = 0; i < c.getCount(); i++) {
c.moveToNext();
ContactModel contact = new ContactModel();


contact.setId(c.getInt(0));
contact.setName(c.getString(1));
contact.setPhone(c.getString(2));

contacts.add(contact);
}
myDataBase.close();
c.close();
SQLiteDatabase.releaseMemory();


} catch (Exception e) {
e.printStackTrace();
}
return contacts;
}


/**
 * Get the contact details from the id passed
 * @param userid
 * @return ContactModel
 */
public ContactModel getUser(int userid) {
ContactModel user = new ContactModel();
openDataBase();
Cursor c;


String select = "Select * from contactMaster " + "where Id =" + userid;
try {
c = myDataBase.rawQuery(select, null);


for (int i = 0; i < c.getCount(); i++) {
c.moveToNext();


user.setId(c.getInt(0));
user.setName(c.getString(1));
user.setPhone(c.getString(2));

}
c.close();
} catch (Exception e) {
e.printStackTrace();
}finally{
myDataBase.close();
SQLiteDatabase.releaseMemory();
}

return user;
}
}




ContactModel.java





public class ContactModel {

private int id;
private String name;
private String phone;

//--- Set ID of contact---
public void setId(int id) {
this.id = id;
}
//--- Get ID of contact---
public int getId() {
return id;
}
//--- Set name of contact---
public void setName(String name) {
this.name = name;
}
//--- Get name of contact---
public String getName() {
return name;
}
//--- Set phone of contact---
public void setPhone(String phone) {
this.phone = phone;
}
//--- Get name of contact---
public String getPhone() {
return phone;
}

}



ContactList.java

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

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;



public class ContactList extends Activity implements OnClickListener{
/**
 * Intialize variables
 */
DataBaseHelper myDatabase;
ArrayList<ContactModel> contacts;
LinearLayout linearMain;
Button btnadd;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);

setContentView(R.layout.sqlite_contactlist);
linearMain = (LinearLayout) findViewById(R.id.linearmainLayout);
//---Database initialize and create database---
myDatabase = new DataBaseHelper(this);
try {
myDatabase.createDataBase();
} catch (IOException e1) {
e1.printStackTrace();
}
btnadd = (Button) findViewById(R.id.btnadd);
btnadd.setOnClickListener(this);
}
@Override
protected void onResume() {
super.onResume();

linearMain.removeAllViews();
linearMain.invalidate();
 //---display the dynamic list of contacts---
AddLayout();
}

/**
 * Get all the contacts from the database
 */
public void AddLayout() {
contacts = myDatabase.getContacts();
if (contacts.size() > 0) {
for (int i =0; i < contacts.size(); i++)
createLayout(contacts.get(i));
}
}
/**
 * Create dynamic layout to display contact list
 * @param contact 
 */
public void createLayout(final ContactModel contact) {

LinearLayout.LayoutParams lp_l = new LinearLayout.LayoutParams(
(LayoutParams.FILL_PARENT), (LayoutParams.WRAP_CONTENT));
lp_l.setMargins(5, 5, 5, 5);

RelativeLayout relative = new RelativeLayout(getApplicationContext());
relative.setLayoutParams(lp_l);
relative.setBackgroundColor(Color.GRAY);
relative.setPadding(5, 5, 5, 5);
RelativeLayout.LayoutParams rel_lp1 = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
rel_lp1.setMargins(0, 15, 0, 0);
final TextView tvname = new TextView(getApplicationContext());
tvname.setLayoutParams(rel_lp1);
tvname.setTextColor(Color.WHITE);
tvname.setText(contact.getName());
relative.addView(tvname);

RelativeLayout.LayoutParams rel_lp2 = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
rel_lp2.setMargins(150, 15, 0, 0);
final TextView tvPhone = new TextView(getApplicationContext());
tvPhone.setLayoutParams(rel_lp2);
tvPhone.setTextColor(Color.WHITE);
tvPhone.setText(contact.getPhone());
relative.addView(tvPhone);
final Button edit = new Button(getApplicationContext());
RelativeLayout.LayoutParams rel_lp3 = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
rel_lp3.addRule(RelativeLayout.ALIGN_RIGHT);
rel_lp3.setMargins(280, 0, 0, 0);
edit.setLayoutParams(rel_lp3);
edit.setTextColor(Color.BLACK);
edit.setText("Edit");
edit.setClickable(true);
relative.addView(edit);

final Button delete = new Button(getApplicationContext());
RelativeLayout.LayoutParams rel_lp4 = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
rel_lp4.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
rel_lp4.setMargins(50, 0, 0, 0);
delete.setLayoutParams(rel_lp4);
delete.setTextColor(Color.BLACK);
delete.setText("Delete");
delete.setClickable(true);
relative.addView(delete);
linearMain.addView(relative);
/**
 * On edit button click EditContact activity is called
 */
edit.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(ContactList.this,EditContact.class);
i.putExtra("id", contact.getId());
startActivity(i);
}
});
/**
 * On delete button click selected contact will be deleted.
 */
delete.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
new AlertDialog.Builder(ContactList.this)

.setMessage("Are you sure, want to delete this record?")
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
//---Delete contact from ContactMaster----
myDatabase.deleteContact(contact.getId());
//---Create the dynamic layout again after deletion of record---
linearMain.removeAllViews();
linearMain.invalidate();
AddLayout();
}
}).setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
})

.create().show();
}
});
}

@Override
public void onClick(View v) {
/**
 * Add new contact so called AddContact activity
 */
if(v == btnadd){
Intent i = new Intent(ContactList.this,AddContact.class);
startActivity(i);
}
}
}

1 comment:

  1. can u post a link for the source code download ??!

    ReplyDelete