SQLite is an Open Source database. SQLite supports standard relational database features like SQL syntax, transactions and prepared statements. The database requires limited memory at runtime
==> DatabaseHandler.java
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "contactsManager";
// Contacts table name
private static final String TABLE_CONTACTS = "contacts";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_PH_NO = "phone_number";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_PH_NO + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new contact
public void addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName()); // Contact Name
values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
// Getting single contact
public Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[]{KEY_ID,
KEY_NAME, KEY_PH_NO}, KEY_ID + "=?",
new String[]{String.valueOf(id)}, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
// return contact
return contact;
}
// Getting All Contacts
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
// Updating single contact
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_PH_NO, contact.getPhoneNumber());
// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[]{String.valueOf(contact.getID())});
}
// Deleting single contact
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[]{String.valueOf(contact.getID())});
db.close();
}
// Getting contacts Count
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
==> activity_db.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimary"
android:titleTextColor="@color/white"
app:titleTextColor="@color/white"></android.support.v7.widget.Toolbar>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="15dp"
android:text="Demo" />
<AutoCompleteTextView
android:id="@+id/autoCompleteTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Name"
android:padding="5dp"
android:textSize="18dp" />
<TextView
android:id="@+id/txt_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:padding="5dp"
android:textSize="18dp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="15dp"
android:text="AddNew" />
<EditText
android:id="@+id/edt_name"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:id="@+id/edt_mno"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/btn_addnew"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Add New" />
</LinearLayout>
==> Contact.java
public class Contact {
//private variables
int _id;
String _name;
String _phone_number;
// Empty constructor
public Contact() {
}
// constructor
public Contact(int id, String name, String _phone_number) {
this._id = id;
this._name = name;
this._phone_number = _phone_number;
}
// constructor
public Contact(String name, String _phone_number) {
this._name = name;
this._phone_number = _phone_number;
}
// getting ID
public int getID() {
return this._id;
}
// setting id
public void setID(int id) {
this._id = id;
}
// getting name
public String getName() {
return this._name;
}
// setting name
public void setName(String name) {
this._name = name;
}
// getting phone number
public String getPhoneNumber() {
return this._phone_number;
}
// setting phone number
public void setPhoneNumber(String phone_number) {
this._phone_number = phone_number;
}
}
==> CustomerAdapter.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.TextView;
import java.util.ArrayList;
public class CustomerAdapter extends ArrayAdapter<Contact> {
private final String MY_DEBUG_TAG = "CustomerAdapter";
private ArrayList<Contact> items;
private ArrayList<Contact> itemsAll;
private ArrayList<Contact> suggestions;
private int viewResourceId;
public CustomerAdapter(Context context, int viewResourceId, ArrayList<Contact> items) {
super(context, viewResourceId, items);
this.items = items;
this.itemsAll = (ArrayList<Contact>) items.clone();
this.suggestions = new ArrayList<Contact>();
this.viewResourceId = viewResourceId;
}
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(viewResourceId, null);
}
Contact customer = items.get(position);
if (customer != null) {
TextView customerNameLabel = (TextView) v.findViewById(R.id.txt_name);
if (customerNameLabel != null) {
// Log.i(MY_DEBUG_TAG, "getView Customer Name:"+customer.getName());
customerNameLabel.setText(customer.getName());
}
}
return v;
}
@Override
public Filter getFilter() {
return nameFilter;
}
Filter nameFilter = new Filter() {
@Override
public String convertResultToString(Object resultValue) {
String str = ((Contact) (resultValue)).getName();
return str;
}
@Override
protected FilterResults performFiltering(CharSequence constraint) {
if (constraint != null) {
suggestions.clear();
for (Contact customer : itemsAll) {
if (customer.getName().toLowerCase().startsWith(constraint.toString().toLowerCase())) {
suggestions.add(customer);
}
}
FilterResults filterResults = new FilterResults();
filterResults.values = suggestions;
filterResults.count = suggestions.size();
return filterResults;
} else {
return new FilterResults();
}
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
ArrayList<Contact> filteredList = (ArrayList<Contact>) results.values;
if (results != null && results.count > 0) {
clear();
for (Contact c : filteredList) {
add(c);
}
notifyDataSetChanged();
}
}
};
}
==> DBAcitivity.java
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
public class DBActicvity extends AppCompatActivity {
@BindView(R.id.autoCompleteTextView)
AutoCompleteTextView autoCompleteTextView;
@BindView(R.id.txt_title)
TextView txt_title;
@BindView(R.id.edt_name)
EditText edt_name;
@BindView(R.id.edt_mno)
EditText edt_mno;
@BindView(R.id.btn_addnew)
Button btn_addnew;
@BindView(R.id.toolbar)
Toolbar toolbar;
DatabaseHandler db;
ArrayList<Contact> contacts;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_db);
ButterKnife.bind(this);
db = new DatabaseHandler(this);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("DB");
fillData();
autoCompleteTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Log.e("selected Item==>", contacts.get(i).getName());
for (Contact contact : contacts) {
if (contacts.get(i).getName().equalsIgnoreCase(contact.getName())) {
txt_title.setText(contact.getID() + " " + contact.getName() + " " + contact.getPhoneNumber());
}
}
}
});
btn_addnew.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
db.addContact(new Contact(edt_name.getText().toString(), edt_mno.getText().toString()));
edt_name.setText("");
edt_mno.setText("");
Toast.makeText(DBActicvity.this, "New Record Added", Toast.LENGTH_SHORT).show();
fillData();
}
});
}
private void fillData() {
//fill data with new value using adapter
contacts = db.getAllContacts();
for (Contact cn : contacts) {
String log = "Id: " + cn.getID() + " ,Name: " + cn.getName() + " ,Phone: " + cn.getPhoneNumber();
// Writing Contacts to log
Log.d("Name: ", log);
}
CustomerAdapter customerAdapter = new CustomerAdapter(this, R.layout.ac_list_item, contacts);
autoCompleteTextView.setAdapter(customerAdapter);
}
}
No comments:
Post a Comment