Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

KeyValuePair Database / Serialisation of object/ Deserialisation of object /Store class object in sqlite database

KeyValuePair Database / Serialisation Of Object/ Deserialisation Of Object /Store Class Object In Sqlite Database

Hi Guys, Here is the demo of how you can create Database which can store whole Object (any type of object like class,string,int object) in Database. You can easily store, retrieve and delete stored object. You can use this type of database in any king of application. Get rid of multiple tables, keys just a single table with keyvalue pair.

This kind of database you can easily use when need to store multiple fields in database. You don't need to worry about all fields of tables. Just your class modal or pojo class is do all the things. Using object Serialization and Deserialization we store data in database


So let's see step by step process to create KeyValuePair sqlite database.


STEP : 1 Create Database Helper class


package com.example.chirag.databasedemo;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Hashtable;

/**
* Created by chirag on 6/2/18.
*/

public class KeyValueHelper extends SQLiteOpenHelper {

private static final String DB_NAME = "KEYVALUE",TABLE="alldata",KEY="key",VALUE = "value";
private static final String TABLE_CREATE = "CREATE TABLE "+TABLE+" ("+KEY+" VARCHAR,"+VALUE+" BLOB);";

private static HashtableString,Object> memTable = new Hashtable();

public KeyValueHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
if(memTable == null) {
memTable = new Hashtable();
}
}

public KeyValueHelper(Context context) {
super(context, DB_NAME, null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(TABLE_CREATE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

public void setValue(String key, Object value) {

delete(key);
ContentValues cv = null;
try {
cv = new ContentValues();
cv.put(KEY, key);
cv.put(VALUE, serializeObject(value));
} catch (Exception e) {
e.printStackTrace();
}


SQLiteDatabase db = this.getWritableDatabase();
db.insert(TABLE,null,cv);
db.close();
}

public T> T getValue(String key,ClassT> type) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("SELECT "+VALUE+" FROM "+TABLE+" WHERE "+KEY+"=?;", new String[]{key});
T ret = getNullFor(type);
if (c.moveToNext()) {
try {
ret = type.cast(deserializeObject(c.getBlob(c.getColumnIndex(VALUE))));
} catch(Exception e){
e.printStackTrace();
}
}
c.close();
return ret;
}

private T> T getNullFor(ClassT> type) {
if(type.equals(Integer.class)) {
return (T) new Integer(0);
} else if(type.equals(Boolean.class)) {
return (T) new Boolean(false);
}
return null;
}

public void delete(String key) {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM "+TABLE+" WHERE "+KEY+"=?;",new String[]{key});
db.close();
}

public void deleteLike(String pattern) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE,KEY+" LIKE ?", new String[]{pattern+"%"});
db.close();
}

public static Object deserializeObject(byte[] bytes) {
try {
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
return ois.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}

public static byte[] serializeObject(Object object) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(object);
return baos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}

STEP : 2 Create UserInfo class (Modal/Pojo) with fields you require to store


package com.example.chirag.databasedemo;

import java.io.Serializable;

/**
* Created by chirag on 6/2/18.
*/

public class UserInfo implements Serializable{
private static final long serialVersionUID = 0L;

private String name;
private String email;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}
}

STEP : 3 Create activity_layout.xml with required input



xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.chirag.databasedemo.MainActivity">


android:id="@+id/title1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="5dp"
android:gravity="center"
android:text="Store Object"
android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"
/>


android:id="@+id/input_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="16dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp">


android:id="@+id/edit_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Name" />



android:id="@+id/input_email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="16dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp">


android:id="@+id/edit_email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Email" />




android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:gravity="center_horizontal"
android:orientation="horizontal">




android:id="@+id/layout_response"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:background="#F5F5F5"
android:orientation="vertical"
android:visibility="gone">


android:id="@+id/title2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:gravity="center"
android:text="Get Object"
android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"
/>


android:id="@+id/text_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp" />


android:id="@+id/text_email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp" />






STEP : 4 Create ActivityMain.java


package com.example.chirag.databasedemo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

private KeyValueHelper keyValueHelper;
private EditText editName,editEmail;
private TextView textName, textEmail;
private Button btnStore,btnGet,btnDelete;
private LinearLayout layoutResponse;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

initObjects();
}

private void initObjects() {
/**
* init UI controls
*/
editName = findViewById(R.id.edit_name);
editEmail = findViewById(R.id.edit_email);
textName = findViewById(R.id.text_name);
textEmail = findViewById(R.id.text_email);
btnStore = findViewById(R.id.button_store);
btnGet = findViewById(R.id.button_get);
btnDelete = findViewById(R.id.button_delete);
layoutResponse = findViewById(R.id.layout_response);

/**
* init class object
*/
keyValueHelper = new KeyValueHelper(this);

/**
* Event listener
*/
btnStore.setOnClickListener(this);
btnGet.setOnClickListener(this);
btnDelete.setOnClickListener(this);
}

public void onStore(){

layoutResponse.setVisibility(View.GONE);

if(TextUtils.isEmpty(editName.getText().toString())){
Toast.makeText(this, "Enter Name", Toast.LENGTH_SHORT).show();
} else if(TextUtils.isEmpty(editEmail.getText().toString())){
Toast.makeText(this, "Enter Email", Toast.LENGTH_SHORT).show();
}
else{

UserInfo info = new UserInfo();
info.setName(editName.getText().toString());
info.setEmail(editEmail.getText().toString());

keyValueHelper.setValue("USER_DETAIL", info);
Toast.makeText(this, "Record Saved!", Toast.LENGTH_SHORT).show();

editName.setText("");
editEmail.setText("");
}
}

public void onGet(){
UserInfo userInfo = keyValueHelper.getValue("USER_DETAIL", UserInfo.class);
if(userInfo != null){
layoutResponse.setVisibility(View.VISIBLE);
textName.setText(userInfo.getName());
textEmail.setText(userInfo.getEmail());
}else{
Toast.makeText(this, "Empty!!", Toast.LENGTH_SHORT).show();
}
}

private void onDelete() {
keyValueHelper.deleteLike("USER_DETAIL");
layoutResponse.setVisibility(View.GONE);
}

@Override
public void onClick(View v) {
if(v.getId() == R.id.button_store){
onStore();
}
else if(v.getId() == R.id.button_get){
onGet();

Share the post

KeyValuePair Database / Serialisation of object/ Deserialisation of object /Store class object in sqlite database

×

Subscribe to Android Blog - Latest Android And Kotlin Development News And Tips To Help You Grow Your Programing

Get updates delivered right to your inbox!

Thank you for your subscription

×