Create Project
Create new project in Android Studio with steps as below:
Step 1: Input Project Name and Select Project Location
Step 2: Select SDK for Android App
Step 3: Select Default Activity for App
Step 4: Finish create project
Create Entities
Create new package named entities. In this package, create new java class named Contact.java as below:
package android.demo.entities;
import java.io.Serializable;
public class Contact implements Serializable {
private int id;
private String name;
private String phone;
private String address;
private String email;
private String description;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
}
Create DatabaseHelper
Create new package named database. In this package, create new java class named DatabaseHelper.java as below:
package android.demo.database;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.demo.entities.Contact;
import java.util.ArrayList;
import java.util.List;
public class DatabaseHelper extends SQLiteOpenHelper {
private static String dbName = "ContactDB";
private static int dbVersion = 1;
private static String contactTable = "contact";
private static String idColumn = "id";
private static String nameColumn = "name";
private static String phoneColumn = "phone";
private static String addressColumn = "address";
private static String emailColumn = "email";
private static String descriptionColumn = "description";
public DatabaseHelper(Context context) {
super(context, dbName, null, dbVersion);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL("create table " + contactTable + "(" +
idColumn + " integer primary key autoincrement, " +
nameColumn + " tex, " +
phoneColumn + " text, " +
addressColumn + " text, " +
emailColumn + " text, " +
descriptionColumn + " text " +
")"
);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("drop table if exists " + contactTable);
onCreate(sqLiteDatabase);
}
public List<Contact> findAll() {
List<Contact> contacts = null;
try {
SQLiteDatabase sqLiteDatabase = getReadableDatabase();
Cursor cursor = sqLiteDatabase.rawQuery("select * from " + contactTable, null);
if (cursor.moveToFirst()) {
contacts = new ArrayList<Contact>();
do {
Contact contact = new Contact();
contact.setId(cursor.getInt(0));
contact.setName(cursor.getString(1));
contact.setPhone(cursor.getString(2));
contact.setAddress(cursor.getString(3));
contact.setEmail(cursor.getString(4));
contact.setDescription(cursor.getString(5));
contacts.add(contact);
} while (cursor.moveToNext());
}
} catch (Exception e) {
contacts = null;
}
return contacts;
}
public List<Contact> search(String keyword) {
List<Contact> contacts = null;
try {
SQLiteDatabase sqLiteDatabase = getReadableDatabase();
Cursor cursor = sqLiteDatabase.rawQuery("select * from " + contactTable + " where " + nameColumn + " like ?", new String[] { "%" + keyword + "%" });
if (cursor.moveToFirst()) {
contacts = new ArrayList<Contact>();
do {
Contact contact = new Contact();
contact.setId(cursor.getInt(0));
contact.setName(cursor.getString(1));
contact.setPhone(cursor.getString(2));
contact.setAddress(cursor.getString(3));
contact.setEmail(cursor.getString(4));
contact.setDescription(cursor.getString(5));
contacts.add(contact);
} while (cursor.moveToNext());
}
} catch (Exception e) {
contacts = null;
}
return contacts;
}
}
Add Strings
Open res\values\strings.xml file and add new string as below:
<resources>
<string name="app_name">Learn Android with Real Apps</string>
<string name="keyword">Keyword</string>
</resources>
Add Photos
Copy images to res\drawable folder
Add Menu
Create new Android Resource Directory named menu. In menu folder, create new menu file named main_menu.xml as below:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/searchView"
android:icon="@drawable/search"
android:title="@string/keyword"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="ifRoom|collapseActionView" />
</menu>
Main Activity Layout
Open res\layout\activity_main.xml file and create layout as below:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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=".MainActivity">
<ListView
android:id="@+id/listViewContact"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Main Activity Class
Add code to MainActivity.java in android.demo.learnandroidwithrealapps package as below:
package android.demo.learnandroidwithrealapps;
import android.app.SearchManager;
import android.demo.adapters.ContactListAdapter;
import android.demo.database.DatabaseHelper;
import android.demo.entities.Contact;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.widget.ListView;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private ListView listViewContact;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
loadData();
}
private void initView() {
listViewContact = findViewById(R.id.listViewContact);
registerForContextMenu(listViewContact);
}
private void loadData() {
DatabaseHelper databaseHelper = new DatabaseHelper(getApplicationContext());
List<Contact> contacts = databaseHelper.findAll();
if (contacts != null) {
listViewContact.setAdapter(new ContactListAdapter(getApplicationContext(), contacts));
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
SearchView searchView = (SearchView) menu.findItem(R.id.searchView).getActionView();
SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setSubmitButtonEnabled(true);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
searchContact(query);
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
searchContact(newText);
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
private void searchContact(String keyword) {
DatabaseHelper databaseHelper = new DatabaseHelper(getApplicationContext());
List<Contact> contacts = databaseHelper.search(keyword);
if (contacts != null) {
listViewContact.setAdapter(new ContactListAdapter(getApplicationContext(), contacts));
}
}
}
Structure of Project
Run App
Load SearchView
Search Contact with Keyword