Sei sulla pagina 1di 13

Gua de Laboratorio 12

Programacin de Aplicaciones Mviles


Prof. : Ing. DANY MONTOYA NEGRILLO.


SQLite
Entidad
SqliteOpenHelper
CRUD
Ejemplo


Table : Contacts
Campos Tipo


id INT PRI KEY
name TEXT
phone_number TEXT




Entidad : ContactEntity


Constructor con campos y mtodos de acceso GET y SET





ContactEntity.java
package com.example.examplesqlite.entity;

import java.io.Serializable;

public class ContactEntity implements Serializable {

private int id;
private String name;
private String phone_number;

public ContactEntity(int id, String name, String phone_number) {
super();
this.id = id;
this.name = name;
this.phone_number = phone_number;
}

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_number() {
return phone_number;
}

public void setPhone_number(String phone_number) {
this.phone_number = phone_number;
}




}



Creamos un clase MyDataBase que implemente SQLiteOpenHelper
android.database.sqlite.SQLiteOpenHelper



Creamos variables estticas
package com.example.examplesqlite.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;



Creamos el constructor con los mtodos onCreate y onUpgrade

Creamos otra clase llamada CRUDOperations para realizar todas las operaciones de
CRUD (Create, Read, Update , Delete)

CRUD CREATE :


CRUD READ :

CRUD UPDATE :


CRUD DELETE :


CRUD ALL CONTACTS :





Implementamos en la actividad principal

HomeActivity
package com.example.examplesqlite;

import java.util.List;

import com.example.examplesqlite.db.CRUDOperations;
import com.example.examplesqlite.db.MyDatabase;
import com.example.examplesqlite.entity.ContactEntity;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;

public class MainActivity extends Activity {

private ListView lstContact;
private List<ContactEntity> data;

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

lstContact=(ListView)findViewById(R.id.lstContact);
app();
}

private void app() {
// TODO Auto-generated method stub
MyDatabase helper = new MyDatabase(this);
CRUDOperations op= new CRUDOperations(helper);

//add
/*op.addContact(new ContactEntity("DANY MONTOYA", "97854632"));
op.addContact(new ContactEntity("Carlos Polo", "993387484"));
op.addContact(new ContactEntity("Otro Nombre", "976052585"));
op.addContact(new ContactEntity("ALARCON SOSA", "976052585"));
op.addContact(new ContactEntity("ALEKS MARTIN ", "976052585"));
op.addContact(new ContactEntity("JHAIT STHIWAR", "976052585"));
*/
//listado Contactos
data = op.allContact();

ContactEntity entity=null;
//String listar="";
for (int i = 0; i < data.size(); i++)
{
entity =data.get(i);
//listar+=entity.getId() +" "+entity.getName()+" "+entity.getPhone_number();
Log.v("CONSOLE",entity.getId() +" "+entity.getName()+"
"+entity.getPhone_number());
}
//Toast.makeText(getApplicationContext(), listar, 3000).show();


List<ContactEntity> lst = crud.getAllContacts();
for (ContactEntity c : lst)
{
Log.v("CONSOLE","Contact item "+ c.getId()+" "+c.getName()+"
"+c.getPhone_number());
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflar el men; esto agrega elementos a la barra de accin, si est presente.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}

}




CRUDOperations
package com.example.examplesqlite.db;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.example.examplesqlite.entity.ContactEntity;

public class CRUDOperations {

private MyDatabase helper;
public CRUDOperations(SQLiteOpenHelper _helper) {
super();
// TODO Auto-generated constructor stub
helper =(MyDatabase)_helper;
}

public void addContact(ContactEntity contact)
{
SQLiteDatabase db = helper.getWritableDatabase(); //modo escritura
ContentValues values = new ContentValues();
values.put(MyDatabase.KEY_NAME, contact.getName());
values.put(MyDatabase.KEY_PHONE_NUMBER,
contact.getPhone_number());

db.insert(MyDatabase.TABLE_CONTACTS, null, values);
db.close();
}

public ContactEntity getContact(int id)
{
SQLiteDatabase db = helper.getReadableDatabase(); //modo lectura
Cursor cursor = db.query(MyDatabase.TABLE_CONTACTS,
new
String[]{MyDatabase.KEY_ID,MyDatabase.KEY_NAME,
MyDatabase.KEY_PHONE_NUMBER},
MyDatabase.KEY_ID+"=?",
new String[]{String.valueOf(id)}, null, null, null);
if(cursor!=null)
{
cursor.moveToFirst();
}
int nid = Integer.parseInt(cursor.getString(0));
String name = cursor.getString(1);
String phone_number = cursor.getString(2);

ContactEntity contact= new ContactEntity(
nid, name, phone_number);
return contact;
}

public List<ContactEntity> getAllContacts()
{
List<ContactEntity> lst =new ArrayList<ContactEntity>();
String sql= "SELECT * FROM " + MyDatabase.TABLE_CONTACTS;
SQLiteDatabase db = helper.getWritableDatabase();
Cursor cursor = db.rawQuery(sql, null);
if(cursor.moveToFirst())
{
do
{
ContactEntity contact =new ContactEntity();
contact.setId(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhone_number(cursor.getString(2));

lst.add(contact);
}while(cursor.moveToNext());
}
return lst;
}

public int getContactsCount()
{
String sql= "SELECT * FROM "+MyDatabase.TABLE_CONTACTS;
SQLiteDatabase db = helper.getReadableDatabase();
Cursor cursor = db.rawQuery(sql, null);
cursor.close();

return cursor.getCount();
}

//--------------------------------------------

public int updateContact(ContactEntity contact)
{
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(MyDatabase.KEY_NAME, contact.getName());
values.put(MyDatabase.KEY_PHONE_NUMBER,
contact.getPhone_number());

return db.update(MyDatabase.TABLE_CONTACTS,
values,
MyDatabase.KEY_ID+"=?",
new String[]{String.valueOf(contact.getId())});
}
//--------------------------------------------

public int deleteContact(ContactEntity contact)
{
SQLiteDatabase db = helper.getWritableDatabase();
int row= db.delete(MyDatabase.TABLE_CONTACTS,
MyDatabase.KEY_ID+"=?",
new String[]{String.valueOf(contact.getId())});
db.close();
return row;
}
}



Recursos
SQLiteOpenHelper
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.
html
Storage Options http://developer.android.com/guide/topics/data/data-
storage.html
SQL Databases http://developer.android.com/training/basics/data-
storage/databases.html

Potrebbero piacerti anche