0% found this document useful (0 votes)
104 views7 pages

I. Sqlite - Define A Schema and Contract Class: "Contact - Info" "Contact - Id" "Name" "Email"

1. The document describes how to create a SQLite database schema and contract class in Android. It defines a ContactEntry class to specify the table name and columns. 2. It then creates a ContactDbHelper class that extends SQLiteOpenHelper to define methods for creating the database and table based on the schema. 3. Methods are added to insert, update, delete contacts by executing the relevant SQL queries. 4. Fragments are created to display and manage the UI - a home fragment contains buttons to add, view contacts; an add fragment contains fields to insert a new contact record on clicking save.

Uploaded by

Mohamed Amine
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
104 views7 pages

I. Sqlite - Define A Schema and Contract Class: "Contact - Info" "Contact - Id" "Name" "Email"

1. The document describes how to create a SQLite database schema and contract class in Android. It defines a ContactEntry class to specify the table name and columns. 2. It then creates a ContactDbHelper class that extends SQLiteOpenHelper to define methods for creating the database and table based on the schema. 3. Methods are added to insert, update, delete contacts by executing the relevant SQL queries. 4. Fragments are created to display and manage the UI - a home fragment contains buttons to add, view contacts; an add fragment contains fields to insert a new contact record on clicking save.

Uploaded by

Mohamed Amine
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

I.

SQLite – define a schema and contract class

In this part we are going to see how to create a database schema and the contract class.

We are going to create a table containing three columns: id, name and email.

Create a new android project called “SQLite Example”.

Creating the contract class

Create a new class called “ContactContract” and make it as a final class.


package com.abc.sqliteexample;

public final class ContactContract


{
private ContactContract(){}

public static class ContactEntry


{
public static final String TABLE_NAME="contact_info";
public static final String CONTACT_ID ="contact_id";
public static final String NAME ="name";
public static final String EMAIL ="email";
}

Now we are going to create the database and table using the SQL open helper class.

Create another JAVA class “ContactDbHelper” that extends SQLiteOpenHelper


package com.abc.sqliteexample;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class ContactDbHelper extends SQLiteOpenHelper


{
public static final String DATABASE_NAME ="contact_db";

public static final int DATABASE_VERSION = 1;

public static final String CREATE_TABLE = "create table


"+ContactContract.ContactEntry.TABLE_NAME+
"("+ContactContract.ContactEntry.CONTACT_ID+" number,"+
ContactContract.ContactEntry.NAME+" text,"+
ContactContract.ContactEntry.EMAIL+" text);";

public static final String DROP_TABLE = "drop table if exists "+


ContactContract.ContactEntry.TABLE_NAME;
public ContactDbHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
Log.d("Database Operations", "Database created ....");

}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {

sqLiteDatabase.execSQL(CREATE_TABLE);
Log.d("Database Operations", "Table created ....");

@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

sqLiteDatabase.execSQL(DROP_TABLE);
onCreate(sqLiteDatabase);
}
}

II. SQLite – put information into a data base

To insert information into database, we need to add a method that execute the corresponding SQL
query.

Add the following code to the ContactDbHelper.


public void addContact(int id, String name, String email, SQLiteDatabase
database)
{
ContentValues contentValues = new ContentValues();
contentValues.put(ContactContract.ContactEntry.CONTACT_ID, id);
contentValues.put(ContactContract.ContactEntry.NAME, name);
contentValues.put(ContactContract.ContactEntry.EMAIL, email);

database.insert(ContactContract.ContactEntry.TABLE_NAME, null,
contentValues);
Log.d("Database Operations", "One row is inserted ....");
}

We are now going to create a fragment from where we launch an insertion.

Create a new fragment called « HomeFragment » having the following layout.


Modify the code of the MainActivity class to add the fragment to the main activity at run time.

Create another fragment called “AddFragmentContact” to add a contact having the following layout.
The AddContactFragment will be launched when we click on the “Add contact” button. Clicking on the
“SAVE” button enables inserting the given row contact into the DB. Modify the code of the
HomeFragment, MainActivity and AddContactFragment classes to implement this.

HomeFragment.java
package com.abc.sqliteexample;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

/**
* A simple {@link Fragment} subclass.
*/
public class HomeFragment extends Fragment implements View.OnClickListener {

private Button bnSave, bnView, bnDelete, bnUpdate;


OnDbOpListener dbOpListener;

public HomeFragment() {
// Required empty public constructor
}

public interface OnDbOpListener


{
public void dBOpPerformed(int method);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container,
false);

bnSave = view.findViewById(R.id.bn_add_contact);
bnSave.setOnClickListener(this);

return view;

@Override
public void onClick(View view)
{
switch(view.getId())
{
case R.id.bn_add_contact :
dbOpListener.dBOpPerformed(0);
break;
}

public void onAttach(Context context)


{
super.onAttach(context);

Activity activity = (Activity) context;


try {
dbOpListener = (OnDbOpListener) activity;

} catch (ClassCastException e){ throw new


ClassCastException(activity.toString()+" must implement the interface
method ...");}
}

MainActivity.java
package com.abc.sqliteexample;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity implements


HomeFragment.OnDbOpListener {

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

if (findViewById(R.id.fragment_container)!=null) {

if (savedInstanceState != null) {
return;
}

HomeFragment homeFragment = new HomeFragment();

getSupportFragmentManager().beginTransaction().add(R.id.fragment_container,
homeFragment).commit();

}
}

@Override
public void dBOpPerformed(int method)
{
switch(method)
{
case 0:

getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container
, new AddContactFragment()).addToBackStack(null).commit();
break;
}
}
}

AddContactFragment.java

package com.abc.sqliteexample;

import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

/**
* A simple {@link Fragment} subclass.
*/
public class AddContactFragment extends Fragment {

private Button bnSave;


EditText id, name, email;

public AddContactFragment() {
// Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_add_contact, container,
false);

bnSave = view.findViewById(R.id.bn_save);
id = view.findViewById(R.id.txt_contact_id);
name = view.findViewById(R.id.txt_contact_name);
email = view.findViewById(R.id.txt_contact_email);

bnSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

String sid = id.getText().toString();


String sname = name.getText().toString();
String semail = email.getText().toString();

ContactDbHelper contactDbHelper = new


ContactDbHelper(getActivity());

SQLiteDatabase databse= contactDbHelper.getWritableDatabase();

contactDbHelper.addContact(Integer.parseInt(sid),sname,semail,
databse);
contactDbHelper.close();
id.setText("");
name.setText("");
email.setText("");

Toast.makeText(getActivity(), "Contact saved succesfully ...


", Toast.LENGTH_SHORT).show();

}
});

return view;
}

You might also like