Store Data in SQLite Database Android:
many ways to storage data in android like Share Preference and other but store data using SQLite is parmanent and can be in many format. In Share Preference save data in key-value pair.
For SQLite we extend SQLiteOpenHelper and @Override write query and save data.
Add Data in Android Using SQLite Database |
HomeActivity :
This Activity we add data to database sqlite in android:
public class HomeActivity extends Activity {
private EditText firstnameET, lastNameET;
private Button add, showAllData;
private DataBaseHandler databaseHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_layout);
init();
}
private void init() {
// TODO Auto-generated method stub
databaseHandler = new DataBaseHandler(HomeActivity.this);
firstnameET = (EditText) findViewById(R.id.firstnameET);
lastNameET = (EditText) findViewById(R.id.lastNameET);
add = (Button) findViewById(R.id.add);
showAllData = (Button) findViewById(R.id.showAllData);
add.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
hideSoftKeyboard();
String getFirstName = firstnameET.getText().toString().trim();
String getLastName = lastNameET.getText().toString().trim();
if (getFirstName.equalsIgnoreCase("")) {
showToast("please enter first name");
} else if (getLastName.equalsIgnoreCase("")) {
showToast("please enter last name");
} else {
firstnameET.setText("");
lastNameET.setText("");
databaseHandler.saveData(getFirstName, getLastName);
showToast("add data sucessfully");
}
}
});
showAllData.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
hideSoftKeyboard();
Intent i = new Intent(HomeActivity.this, DataListActivity.class);
startActivity(i);
}
});
}
@Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
hideSoftKeyboard();
}
private void showToast(String message) {
// TODO Auto-generated method stub
Toast.makeText(HomeActivity.this, message, Toast.LENGTH_SHORT).show();
}
public void hideSoftKeyboard() {
try {
InputMethodManager inputMethodManager = (InputMethodManager) HomeActivity.this
.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(HomeActivity.this
.getCurrentFocus().getWindowToken(), 0);
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
private EditText firstnameET, lastNameET;
private Button add, showAllData;
private DataBaseHandler databaseHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_layout);
init();
}
private void init() {
// TODO Auto-generated method stub
databaseHandler = new DataBaseHandler(HomeActivity.this);
firstnameET = (EditText) findViewById(R.id.firstnameET);
lastNameET = (EditText) findViewById(R.id.lastNameET);
add = (Button) findViewById(R.id.add);
showAllData = (Button) findViewById(R.id.showAllData);
add.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
hideSoftKeyboard();
String getFirstName = firstnameET.getText().toString().trim();
String getLastName = lastNameET.getText().toString().trim();
if (getFirstName.equalsIgnoreCase("")) {
showToast("please enter first name");
} else if (getLastName.equalsIgnoreCase("")) {
showToast("please enter last name");
} else {
firstnameET.setText("");
lastNameET.setText("");
databaseHandler.saveData(getFirstName, getLastName);
showToast("add data sucessfully");
}
}
});
showAllData.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
hideSoftKeyboard();
Intent i = new Intent(HomeActivity.this, DataListActivity.class);
startActivity(i);
}
});
}
@Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
hideSoftKeyboard();
}
private void showToast(String message) {
// TODO Auto-generated method stub
Toast.makeText(HomeActivity.this, message, Toast.LENGTH_SHORT).show();
}
public void hideSoftKeyboard() {
try {
InputMethodManager inputMethodManager = (InputMethodManager) HomeActivity.this
.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(HomeActivity.this
.getCurrentFocus().getWindowToken(), 0);
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Layout Design: home_layout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#B9F6CA" >
<EditText
android:id="@+id/firstnameET"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="60dp"
android:background="@drawable/border"
android:gravity="center"
android:hint="Enter First Name"
android:padding="13dp"
android:singleLine="true"
android:textColor="#000000"
android:textSize="15sp" />
<EditText
android:id="@+id/lastNameET"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/firstnameET"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:background="@drawable/border"
android:gravity="center"
android:hint="Enter Last Name"
android:padding="13dp"
android:singleLine="true"
android:textColor="#000000"
android:textSize="15sp" />
<Button
android:id="@+id/add"
android:layout_width="fill_parent"
android:layout_height="30dp"
android:layout_below="@+id/lastNameET"
android:layout_centerInParent="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:background="#006064"
android:text="ADD TO DATABASE"
android:textColor="#FFFFFF"
android:textSize="16sp" />
<Button
android:id="@+id/showAllData"
android:layout_width="fill_parent"
android:layout_height="30dp"
android:layout_below="@+id/add"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="60dp"
android:background="#006064"
android:text="SHOW ADDED DATA"
android:textColor="#FFFFFF"
android:textSize="16sp" />
</RelativeLayout>
Database In SQLite:
Create database for add and retrieve data, create tables and field.
DataBaseHandler .java Class:
public class DataBaseHandler extends SQLiteOpenHelper {
// database name and version
private final static int DATABASE_VERSION = 1;
private final static String DATABASE_NAME = "add_data";
// for add table
private final String TABLE_ADD = "add_table";
private final String ADD_FIRST_NAME = "firstname";
private final String ADD_LAST_NAME = "lastname";
public DataBaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase arg0) {
// TODO Auto-generated method stub
String addTable = "create table if not exists " + TABLE_ADD + "("
+ ADD_FIRST_NAME + " TEXT NOT NULL," + ADD_LAST_NAME
+ " TEXT NOT NULL)";
arg0.execSQL(addTable);
}
public void saveData(String firstname, String lastname) {
// TODO Auto-generated method stub
SQLiteDatabase db = this.getWritableDatabase();
ContentValues value = new ContentValues();
value.put(ADD_FIRST_NAME, firstname);
value.put(ADD_LAST_NAME, lastname);
db.insert(TABLE_ADD, null, value);
db.close();
}
/// get data
public ArrayList<Model> getAllData() {
// TODO Auto-generated method stub
ArrayList<Model> arrayOFData = new ArrayList<Model>();
String selectQuery = "SELECT "+ "*" +" FROM "+ TABLE_ADD ;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Model model=new Model();
model.setFirstName(cursor.getString(0));
model.setLastName(cursor.getString(1));
arrayOFData.add(model);
} while (cursor.moveToNext());
}
return arrayOFData;
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
Retrieve data in SQLite:
Retrieve data from SQLite, above Databasehandler.this we create all method for add and retrieve data.
private DataBaseHandler databaseHandler;
private ListView list;
private ArrayList<Model> arrayOfData;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.list_layout);
init();
}
private void init() {
// TODO Auto-generated method stub
list=(ListView) findViewById(R.id.list);
databaseHandler=new DataBaseHandler(DataListActivity.this);
arrayOfData=new ArrayList<Model>();
arrayOfData.clear();
arrayOfData=databaseHandler.getAllData();
CustomAdapter adapter=new CustomAdapter(DataListActivity.this,arrayOfData ,R.layout.row_layout);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Toast.makeText(DataListActivity.this, arrayOfData.get(arg2).getFirstName()+" "+arrayOfData.get(arg2).getLastName(), Toast.LENGTH_SHORT).show();
}
});
}
}
Show Data in ListView From SQLite:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
<ListView
android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:padding="10dp">
</ListView>
</RelativeLayout>
Download Complete Source Code Click Here
If any problem to Implement this then Please Comments.
Thank You !!
android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:padding="10dp">
</ListView>
</RelativeLayout>
Retrieve Data From SQLite Database in Android |
Download Complete Source Code Click Here
If any problem to Implement this then Please Comments.
Thank You !!
No comments :
Post a Comment