Skip to content

Instantly share code, notes, and snippets.

@JChudasama
Last active August 29, 2015 14:27
Show Gist options
  • Save JChudasama/57ed0d23e285af948525 to your computer and use it in GitHub Desktop.
Save JChudasama/57ed0d23e285af948525 to your computer and use it in GitHub Desktop.
Database Demo
public class ClassUtils {
public static String objectToInsert(Object mainObj) {
Field[] fields = mainObj.getClass().getFields();
String key, value;
// System.out.println("Number of fields = " + fields.length);
StringBuffer keyData = new StringBuffer(" (");
StringBuffer valueData = new StringBuffer(" VALUES(");
Vector<String> arrKey = new Vector<String>();
Vector<String> arrValue = new Vector<String>();
for (Field field : fields) {
// System.out.println("Field name = " + field.getName());
// System.out.println("Field type = " + field.getType().getName());
key = field.getName();
try {
// System.out.println("\t\tFound Field ");
value = field.get(mainObj).toString();
if (!value.equalsIgnoreCase("") && value != null) {
arrKey.addElement(key);
arrValue.addElement(value);
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
for (int i = 0; i < arrKey.size(); i++) {
key = arrKey.elementAt(i);
value = arrValue.elementAt(i);
keyData.append(key);
valueData.append("'" + value + "'");
if (i < arrKey.size() - 1) {
keyData.append(", ");
valueData.append(", ");
}
}
keyData.append(")");
valueData.append(")");
String returnStr = keyData.append(valueData).toString();
Log.d("Insert-String", returnStr);
return returnStr;
}
public static void objectMapping(Object mainObj, String key, Object value) {
// String FQClassName = mainObj.getClass().getName();
Field[] fields = mainObj.getClass().getFields();
// System.out.println("Number of fields = " + fields.length);
for (Field field : fields) {
// System.out.println("Field name = " + field.getName());
// System.out.println("Field type = " + field.getType().getName());
if (field.getName().equalsIgnoreCase(key)) {
try {
// System.out.println("\t\tFound Field ");
field.set(mainObj, value);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
public static Object newObject(Object myObj) {
Class<? extends Object> theClass = myObj.getClass();
Object newObject = null;
try {
newObject = theClass.newInstance();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
return newObject;
}
// returns the class (without the package if any)
public static String getClassName(Object c) {
String FQClassName = c.getClass().getName();
Field[] fields = c.getClass().getFields();
System.out.println("Number of fields = " + fields.length);
for (Field field : fields) {
// System.out.println("Field name = " + field.getName());
// System.out.println("Field type = " + field.getType().getName());
try {
field.set(c, "UMN");
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
int firstChar;
firstChar = FQClassName.lastIndexOf('.') + 1;
if (firstChar > 0) {
FQClassName = FQClassName.substring(firstChar);
}
return FQClassName;
}
// returns package and class name
public static String getFullClassName(Class<?> c) {
return c.getName();
}
// returns the package without the classname, empty string if
// there is no package
public static String getPackageName(Class<?> c) {
String fullyQualifiedName = c.getName();
int lastDot = fullyQualifiedName.lastIndexOf('.');
if (lastDot == -1) {
return "";
}
return fullyQualifiedName.substring(0, lastDot);
}
/** Read the object from Base64 string. */
public static Object fromString(String s) throws IOException,
ClassNotFoundException {
byte[] data = Base64.decode(s, Base64.DEFAULT);
// byte[] data = Base64Coder.decode(s);
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(
data));
Object o = ois.readObject();
ois.close();
return o;
}
/** Write the object to a Base64 string. */
public static String toString(Serializable o) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(o);
oos.close();
return new String(Base64.encode(baos.toByteArray(),Base64.DEFAULT));
}
}
public class DBConnect extends SQLiteOpenHelper {
// The Android's default system path of your application database.
private String DB_PATH;
private String DB_NAME;
public SQLiteDatabase db;
private final Context myContext;
private final static int DATABASE_VERSION = 1;
/**
* Constructor Takes and keeps a reference of the passed context in order to
* access to the application assets and resources.
*
* @param context
* @param db_name
*/
public DBConnect(Context context, String db_name) {
super(context, db_name, null, DATABASE_VERSION);
this.myContext = context;
DB_PATH = (context.getApplicationInfo().dataDir + "/databases/");
DB_NAME = db_name;
try {
createDataBase();
openDataBase();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Creates a empty database on the system and rewrites it with your own
* database.
* */
public void createDataBase() throws Exception {
boolean dbExist = checkDataBase();
if (dbExist) {
System.out.println("Database Exist");
} else {
this.getReadableDatabase();
try {
copyDataBase();
} catch (Exception e) {
e.printStackTrace();
throw new Error(e.getMessage());
}
}
}
/**
* Check if the database already exist to avoid re-copying the file each
* time you open the application.
*
* @return true if it exists, false if it doesn't
*/
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
} catch (Exception e) {
System.out.println("database does't exist yet.");
}
if (checkDB != null) {
checkDB.close();
System.out.println("My db is:- " + checkDB.isOpen());
return true;
} else
return false;
}
public void copyCacheToMain(DBConnect objCache) throws IOException {
// Open your local db as the input stream
String inFileName = objCache.DB_PATH + objCache.DB_NAME;
InputStream myInput = new FileInputStream(inFileName);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
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();
Log.d("CTM", "Cache To Main Database Copied !");
}
/**
* Copies your database from your local assets-folder to the just created
* empty database in the system folder, from where it can be accessed and
* handled. This is done by transfering bytestream.
* */
// DB Joiner
private void copyDataBase() throws Exception {
try {
InputStream myInput = myContext.getAssets().open(
com.vivacious.database.Constants.Database.DB_NAME
);
com.vivacious.database.Log.v("Assets input: "+myInput.available());
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);
}
myInput.close();
System.out.println(DB_NAME + "Database Copied !");
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
public void openDataBase() throws SQLException {
// Open the database
String myPath = DB_PATH + DB_NAME;
if (db != null && db.isOpen())
db.close();
db = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
}
@Override
public synchronized void close() {
if (db != null)
db.close();
System.out.println("My db is:- " + db.isOpen());
super.close();
}
public synchronized void execNonQuery(String sql) {
try {
db.execSQL(sql);
Log.d("SQL", sql);
} catch (Exception e) {
Log.e("Err", e.getMessage());
} finally {
// closeDb();
}
}
public synchronized Cursor execQuery(String sql) {
Cursor cursor = null;
try {
cursor = db.rawQuery(sql, null);
Log.d("SQL", sql);
} catch (Exception e) {
Log.e("Err", e.getMessage());
} finally {
// closeDb();
}
return cursor;
}
public synchronized Cursor getFullTable(String table) {
Cursor cursor = null;
try {
cursor = db.query(table, null, null, null, null, null, null);
} catch (Exception e) {
Log.e("Err", e.getMessage());
} finally {
// closeDb();
}
return cursor;
}
public synchronized HashMap<String, String> getColumns(String table) {
Cursor cursor = null;
HashMap<String, String> colums = new HashMap<String, String>();
try {
cursor = db.query(table, null, null, null, null, null, null);
for (int i = 0; i < cursor.getColumnCount(); i++) {
colums.put(cursor.getColumnName(i), cursor.getColumnName(i));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// closeDb();
if (cursor != null)
cursor.close();
}
return colums;
}
public synchronized Cursor execQuery(String sql, String[] selectionArgs) {
Cursor cursor = null;
try {
cursor = db.rawQuery(sql, selectionArgs);
Log.d("SQL", sql);
} catch (Exception e) {
e.printStackTrace();
} finally {
// closeDb();
}
return cursor;
}
public int update(String tblName, String fieldName, String fieldValue,
String whereClause, String[] whereArgs) {
ContentValues initialValues = new ContentValues();
int result = -1;
try {
initialValues.put(fieldName, fieldValue);
result = db.update(tblName, initialValues, whereClause, whereArgs);
} catch (IllegalArgumentException e) {
e.printStackTrace();
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public int update(String tblName, Object myObj, String whereClause,
String[] whereArgs) {
ContentValues initialValues = new ContentValues();
int result = -1;
Field[] fields = myObj.getClass().getFields();
try {
for (Field field : fields) {
String fieldName = field.getName() + "=?";
if (whereClause.indexOf(fieldName) == -1)
initialValues.put(field.getName(),
(String) field.get(myObj));
}
result = db.update(tblName, initialValues, whereClause, whereArgs);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public long insert(String tblName, Object myObj) {
ContentValues initialValues = new ContentValues();
long result = -1;
Field[] fields = myObj.getClass().getFields();
try {
for (Field field : fields) {
String value = (String) field.get(myObj);
if (value != null && value.length() > 0
&& !value.equalsIgnoreCase("<null>")) {
initialValues.put(field.getName(), value);
}
}
result = db.insertOrThrow(tblName, null, initialValues);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
*
* @param sqlQuery
* SQL query to be fired
* @param myObj
* Object to be fetched
* @return Returns a Vector object containing raws fetched by the sqlQuery
*/
public ArrayList<Object> fetchAllRows(String sqlQuery, Object myObj) {
ArrayList<Object> records = new ArrayList<Object>();
Object newObj;
Cursor cursor = execQuery(sqlQuery);
if (cursor != null) {
while (cursor.moveToNext()) {
newObj = ClassUtils.newObject(myObj);
for (int i = 0; i < cursor.getColumnCount(); i++) {
String key = cursor.getColumnName(i);
String value = cursor.getString(i);
if (value == null) {
value = "";
}
ClassUtils.objectMapping(newObj, key, value);
}
records.add(newObj);
}
cursor.close();
}
return records;
}
public int delete(String tblName, String whereClause, String[] whereArgs) {
int result = -1;
try {
result = db.delete(tblName, whereClause, whereArgs);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public long insert(String tblAudit, ContentValues initialValues) {
// TODO Auto-generated method stub
long result = -1;
try {
result = db.insertWithOnConflict(tblAudit, null, initialValues, 0);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public class MainActivity extends Activity {
List<Object> alProducts;
Product product1, product2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
intializeDB();
// insertObject();
// updateObject();
// getObject();
// deleteObject();
}
private void init() {
// TODO Auto-generated method stub
}
private void intializeDB() {
// TODO Auto-generated method stub
try {
if (Global.dbObject != null) {
Global.dbObject.close();
}
Global.dbObject = new DBConnect(getApplicationContext(),
Constants.Database.DB_NAME);
} catch (Exception e) {
e.printStackTrace();
}
}
private void insertObject() {
// TODO Auto-generated method stub
product1 = new Product();
product1.prod_id = "223";
product1.name = "_name";
product1.details = "details product";
product1.price = "2244";
Global.dbObject.insert("Product", product1);
}
private void updateObject() {
// TODO Auto-generated method stub
// Global.dbObject.update("Product", product1, "prod_id= ?", new
// String[] {"223"});
// Global.dbObject.update("Product", "details", "Testing", "prod_id=?",
// new String[] { "223" });
}
private void deleteObject() {
// TODO Auto-generated method stub
// Global.dbObject.delete("Product","prod_id=?",new String[]{"123"});
Global.dbObject.execNonQuery("delete from Product where prod_id='223'");
}
private void getObject() {
// TODO Auto-generated method stub
try {
alProducts = Global.dbObject.fetchAllRows("select * from Product",
new Product());
if (alProducts.size() != 0) {
for (int i = 0; i < alProducts.size(); i++) {
Product product3 = (Product) alProducts.get(i);
Log.v("Product Id: " + product3.prod_id);
Log.v("Product Id: " + product3.name);
Log.v("Product Id: " + product3.details);
Log.v("Product Id: " + product3.price);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class Product implements Serializable {
public String prod_id;
public String name;
public String details;
public String price;
public Product(){
}
public Product(String prod_id, String name, String details, String price) {
super();
this.prod_id = prod_id;
this.name = name;
this.details = details;
this.price = price;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment