DatabaseConnectionAPI.java
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseConnectionAPI extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "contactsManager";
// Contact table name
private static final String TABLE_CONTACTS = "contacts";
// Contact 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 DatabaseConnectionAPI(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 int 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
int i= (int) db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
return i;
}
// Getting single contact
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 Contact
public ArrayList<Contact> getAllContacts() {
ArrayList<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(String id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { id });
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();
}
}
layout_add.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:padding="@dimen/margin_10dp"
android:layout_height="match_parent">
<android.support.design.widget.TextInputLayout
android:id="@+id/input_layout_email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/margin_10dp">
<EditText
android:id="@+id/edt_email"
style="@style/Edittext"
android:hint="Name" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="@+id/input_layout_pass"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/input_layout_email">
<EditText
android:id="@+id/edt_password"
style="@style/Edittext"
android:hint="Phone"
android:maxLength="10"
android:inputType="phone" />
</android.support.design.widget.TextInputLayout>
<TextView
android:id="@+id/txt_login"
style="@style/LargeTextView"
android:layout_below="@+id/input_layout_pass"
android:layout_centerHorizontal="true"
android:layout_marginTop="@dimen/margin_20dp"
android:padding="@dimen/margin_10dp"
android:text="ADD CONTACT"
android:textColor="@color/colorPrimary" />
</RelativeLayout>
layout_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/txt_no_data"
style="@style/LargeTextView"
android:text="There are no any data added yet."
android:layout_centerHorizontal="true"
android:layout_margin="@dimen/margin_10dp"/>
<RelativeLayout
android:id="@+id/rel_tops"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:cacheColorHint="@android:color/transparent"
android:divider="@android:color/transparent"
android:visibility="visible"
/>
</RelativeLayout>
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:layout_margin="@dimen/fab_margin"
android:src="@android:drawable/ic_input_add" />
</RelativeLayout>
row_list_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.CardView
android:id="@+id/card_view"
android:layout_gravity="center"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
card_view:cardCornerRadius="2dp"
card_view:contentPadding="10dp">
<RelativeLayout
android:id="@+id/rel_top"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp">
<TextView
android:id="@+id/row_txt_name"
style="@style/LargeTextView"
android:text="Name"/>
<TextView
android:id="@+id/row_txt_ph"
style="@style/NormalTextView"
android:layout_below="@+id/row_txt_name"
android:text="Name"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
package com.example.sphere65.sqlitedemoexample;
import android.os.Bundle;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class AddContact extends AppCompatActivity {
TextInputLayout mTextInputLayoutEmail;
EditText mEditTextEmail;
TextInputLayout mTextInputLayoutPassword;
EditText mEditTextPassword;
TextView mTextViewLogin;
DatabaseConnectionAPI mDatabaseConnectionAPI;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_add);
mDatabaseConnectionAPI=new DatabaseConnectionAPI(this);
mTextInputLayoutEmail=(TextInputLayout)findViewById(R.id.input_layout_email);
mTextInputLayoutPassword=(TextInputLayout)findViewById(R.id.input_layout_pass);
mEditTextEmail=(EditText)findViewById(R.id.edt_email);
mEditTextPassword=(EditText)findViewById(R.id.edt_password);
mTextViewLogin=(TextView)findViewById(R.id.txt_login);
mEditTextEmail.addTextChangedListener(new MyTextWatcher(mEditTextEmail));
mEditTextPassword.addTextChangedListener(new MyTextWatcher(mEditTextPassword));
mTextViewLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
loginDone();
}
});
}
private void loginDone() {
if (!validateEmail()) {
return;
}
else if (!validatePassword()) {
return;
}
else
{
int i= mDatabaseConnectionAPI.addContact(new Contact(mEditTextEmail.getText().toString(), mEditTextPassword.getText().toString()));
if (i>0)
{
Toast.makeText(getApplicationContext(), "Data inserted successfully.", Toast.LENGTH_SHORT).show();
clearAllField();
finish();
}
}
}
public void clearAllField()
{
mEditTextEmail.clearFocus();
mEditTextPassword.clearFocus();
}
private boolean validateEmail() {
String email = mEditTextEmail.getText().toString().trim();
if (email.isEmpty() ) {
mTextInputLayoutEmail.setError("Enter name");
requestFocus(mEditTextEmail);
return false;
} else {
mTextInputLayoutEmail.setErrorEnabled(false);
}
return true;
}
private boolean validatePassword() {
if (mEditTextPassword.getText().toString().trim().isEmpty()) {
mTextInputLayoutPassword.setError("Enter Phone");
requestFocus(mEditTextPassword);
return false;
} else {
mTextInputLayoutPassword.setErrorEnabled(false);
}
return true;
}
private void requestFocus(View view) {
if (view.requestFocus()) {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}
private class MyTextWatcher implements TextWatcher {
private View view;
private MyTextWatcher(View view) {
this.view = view;
}
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
public void afterTextChanged(Editable editable) {
switch (view.getId()) {
case R.id.edt_email:
validateEmail();
break;
case R.id.edt_password:
validatePassword();
break;
}
}
}
}
EditContact.java
package com.example.sphere65.sqlitedemoexample;
import android.os.Bundle;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class EditContact extends AppCompatActivity {
TextInputLayout mTextInputLayoutEmail;
EditText mEditTextEmail;
TextInputLayout mTextInputLayoutPassword;
EditText mEditTextPassword;
TextView mTextViewLogin;
DatabaseConnectionAPI mDatabaseConnectionAPI;
Contact mContact;
String value = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_add);
mDatabaseConnectionAPI = new DatabaseConnectionAPI(this);
Bundle extras = getIntent().getExtras();
if (extras != null) {
value = extras.getString("id");
}
mContact = new Contact();
mContact = mDatabaseConnectionAPI.getContact(Integer.parseInt(value));
mTextInputLayoutEmail = (TextInputLayout) findViewById(R.id.input_layout_email);
mTextInputLayoutPassword = (TextInputLayout) findViewById(R.id.input_layout_pass);
mEditTextEmail = (EditText) findViewById(R.id.edt_email);
mEditTextPassword = (EditText) findViewById(R.id.edt_password);
mTextViewLogin = (TextView) findViewById(R.id.txt_login);
mEditTextEmail.addTextChangedListener(new MyTextWatcher(mEditTextEmail));
mEditTextPassword.addTextChangedListener(new MyTextWatcher(mEditTextPassword));
mTextViewLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
loginDone();
}
});
mEditTextEmail.setText(mContact.getName());
mEditTextPassword.setText(mContact.getPhoneNumber());
mTextViewLogin.setText("EDIT CONTACT");
}
private void loginDone() {
if (!validateEmail()) {
return;
} else if (!validatePassword()) {
return;
} else {
int i = mDatabaseConnectionAPI.updateContact(new Contact(mEditTextEmail.getText().toString(), mEditTextPassword.getText().toString(), Integer.parseInt(value)));
if (i > 0) {
Toast.makeText(getApplicationContext(), "Data updated successfully.", Toast.LENGTH_SHORT).show();
clearAllField();
finish();
}
}
}
public void clearAllField() {
mEditTextEmail.clearFocus();
mEditTextPassword.clearFocus();
}
private boolean validateEmail() {
String email = mEditTextEmail.getText().toString().trim();
if (email.isEmpty()) {
mTextInputLayoutEmail.setError("Enter name");
requestFocus(mEditTextEmail);
return false;
} else {
mTextInputLayoutEmail.setErrorEnabled(false);
}
return true;
}
private boolean validatePassword() {
if (mEditTextPassword.getText().toString().trim().isEmpty()) {
mTextInputLayoutPassword.setError("Enter Phone");
requestFocus(mEditTextPassword);
return false;
} else {
mTextInputLayoutPassword.setErrorEnabled(false);
}
return true;
}
private void requestFocus(View view) {
if (view.requestFocus()) {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}
private class MyTextWatcher implements TextWatcher {
private View view;
private MyTextWatcher(View view) {
this.view = view;
}
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
public void afterTextChanged(Editable editable) {
switch (view.getId()) {
case R.id.edt_email:
validateEmail();
break;
case R.id.edt_password:
validatePassword();
break;
}
}
}
}
ContactListActivity.java
package com.example.sphere65.sqlitedemoexample;
import java.util.ArrayList;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class ContactListActivity extends Activity {
/**
* Called when the activity is first created.
*/
DatabaseConnectionAPI db;
ListView mListView;
CusTomListAdapter mCusTomListAdapter;
ArrayList<Contact> contacts;
TextView mTextViewNoData;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_main);
db = new DatabaseConnectionAPI(this);
mTextViewNoData=(TextView)findViewById(R.id.txt_no_data);
mListView = (ListView) findViewById(R.id.list);
/**
* CRUD Operations
* */
// Inserting Contact
/*Log.d("Insert: ", "Inserting ..");
db.addContact(new Contact("Harshal", "9100000000"));
db.addContact(new Contact("Srinivas", "9199999999"));
db.addContact(new Contact("Tommy", "9522222222"));
db.addContact(new Contact("Karthik", "9533333333"));*/
// Reading all contacts
Log.d("Reading: ", "Reading all contacts..");
contacts = db.getAllContacts();
if (contacts.size()>0)
{
mCusTomListAdapter=new CusTomListAdapter(AndroidSQLiteTutorialActivity.this,contacts);
mListView.setAdapter(mCusTomListAdapter);
mTextViewNoData.setVisibility(View.GONE);
mListView.setVisibility(View.VISIBLE);
}
else
{
mTextViewNoData.setVisibility(View.VISIBLE);
mListView.setVisibility(View.GONE);
}
for (Contact cn : contacts) {
String log = "Id: " + cn.getID() + " ,Name: " + cn.getName() + " ,Phone: " + cn.getPhoneNumber();
// Writing Contact to log
Log.d("Name: ", log);
}
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
/*Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();*/
Intent mIntent=new Intent(AndroidSQLiteTutorialActivity.this,AddContact.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(mIntent);
}
});
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view,final int i, long l) {
CharSequence colors[] = new CharSequence[] {"Edit", "Delete"};
AlertDialog.Builder builder = new AlertDialog.Builder(AndroidSQLiteTutorialActivity.this);
builder.setTitle("Choose Action");
builder.setItems(colors, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
Intent mIntent = new Intent(AndroidSQLiteTutorialActivity.this, EditContact.class);
mIntent.putExtra("id", String.valueOf(contacts.get(i).getID()));
startActivity(mIntent);
} else {
db.deleteContact(String.valueOf(contacts.get(i).getID()));
contacts = db.getAllContacts();
if (contacts.size() > 0) {
mCusTomListAdapter = new CusTomListAdapter(AndroidSQLiteTutorialActivity.this, contacts);
mListView.setAdapter(mCusTomListAdapter);
mTextViewNoData.setVisibility(View.GONE);
mListView.setVisibility(View.VISIBLE);
} else {
mListView.setVisibility(View.GONE);
mTextViewNoData.setVisibility(View.VISIBLE);
}
}
}
});
builder.show();
}
});
}
@Override
protected void onResume() {
super.onResume();
ArrayList<Contact> contacts = db.getAllContacts();
if (contacts.size()>0)
{
mCusTomListAdapter=new CusTomListAdapter(AndroidSQLiteTutorialActivity.this,contacts);
mListView.setAdapter(mCusTomListAdapter);
mListView.setVisibility(View.VISIBLE);
mTextViewNoData.setVisibility(View.GONE);
}
else
{
mListView.setVisibility(View.GONE);
mTextViewNoData.setVisibility(View.VISIBLE);
}
}
public class CusTomListAdapter extends BaseAdapter {
Activity mActivity;
ArrayList<Contact> list;
public CusTomListAdapter(AndroidSQLiteTutorialActivity mainActivity, ArrayList<Contact> contacts) {
list = contacts;
mActivity = mainActivity;
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int i) {
return i;
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View convertView, ViewGroup viewGroup) {
LayoutInflater inflator = mActivity.getLayoutInflater();
convertView = inflator.inflate(R.layout.row_list_layout, null);
TextView mTextViewName = (TextView) convertView.findViewById(R.id.row_txt_name);
TextView mTextViewPh = (TextView) convertView.findViewById(R.id.row_txt_ph);
mTextViewName.setText(list.get(i).getName());
mTextViewPh.setText(list.get(i).getPhoneNumber());
return convertView;
}
}
}
No comments:
Post a Comment