Session 2- day 3

Embed Size (px)

Citation preview

ListView

ListViews

Displays a group of scrollable items.

The items are automatically inserted to list using an Adapter that pull content from a source.

Implementation

Create a layout with listview

In MainActivity

Define the listviewlistView = (ListView) findViewById(R.id.list);

Define arrays to show in the ListViewString[] values = { abc, def , ijk , xyz};

Use AdapterHelper to feed data into the list view

Using Adapter: ArrayAdapter

What are the parameters to be passed in this adapter ?First parameter - Context

Second parameter - Layout for the row

Third parameter - ID of the TextView to which the data is written

Forth - the Array of data

Define a new AdapterArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, android.R.id.text1, values);These are all generic layouts defined by Android for us

Set the adapterlistView.setAdapter(adapter);

Notice android being referenced at first

Set onItemClickListener listView.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView parent, View view, int position, long id) { int itemPosition = position; String itemValue = (String) listView.getItemAtPosition(position); Toast.makeText(getApplicationContext(), "Position :"+itemPosition+" ListItem : " +itemValue , Toast.LENGTH_LONG).show(); }

ListView Usage

ListView with SimpleAdapter

Similar to what we have discussed.

Can be used to create a more dynamic layout.

NameAddressDetails ...Layout for our program

Implementation

Same as earlier.

Store all the contents that are to be filled inside an array.String[] name = {abc, def, xyz};String[] address = {abc, def, xyz};String[] details = {abc, def, xyz};

HashMaps

They are used to store data in a key/value pair.

Iterate all the arrays inside the HashMapfor (int i = 0; i < name.length; i++) {HashMap toFill = new HashMap();toFill.put("name", name[i]);toFill.put("address", address[i]);toFill.put("details", details[i]);// fill this HashMap inside an ArrayListlistFill.add(toFill);

}

ArrayList

ArrayList is the most frequently used collection class after HashMap

They represent an automatic, re-sizable array and are much more dynamic than your average java array.

We use this ArrayList here to fill in all the HashMap entiresArrayList listFill;listFill = new ArrayList();

Using Adapter: SimpleAdapter

What are the parameters to be passed ?First-parameter: Context

Second-parameter: ArrayList initialized

Third-parameter: Layout file

Forth-parameter: HashMap references

Fifth-parameter: Reference Id's from the layout

Defining the adapter:ListAdapter adapter = new SimpleAdapter(MainActivity.this, listFill,R.layout.custom_layout, new String[] { "name", "address","details" }, new int[] { R.id.list_name,R.id.list_add, R.id.list_details });

Setting up adapter:

listView.setAdapter(adapter);

Implementing the onItemClickListener:listView.setOnItemClickListener(new OnItemClickListener() {@Overridepublic void onItemClick(AdapterView parent, View view, int position,long id) {int itemPosition = position;HashMap hashReference = (HashMap)parent.getItemAtPosition(position);String name = hashReference.get("name");String address = hashReference.get("address");Toast.makeText(getApplicationContext(), itemPosition+"\n"+name"\n" + address, Toast.LENGTH_SHORT).show();

}

});

SQLite and Android

SQLite is an open source database.

Supports standard relational database features like the SQL syntax, transactions and prepared statements.

Why SQLite?These databases require limited memory at runtime

SQLiteOpenHelper

From a programming perspective, the SQLiteOpenHelper is to be extended.

In the constructor the super() of SQLiteOpenHelper is called specifying the name and the current database version along with the context.

e.g.:public DatabaseHandler(Context context){super (context, DB_NAME, null, DB_VERSION);

}

SQLiteOpenHelper

On using this class, two methods are to be overridden:onCreate() - is called when the database is first created.

onUpgrade() - called, if the database version is increased in the code. This method allows to update/drop the database and recreate it via the onCreate() method.

Both method receive a SQLiteDatabase object as parameter which is the Java representation of the database

Creating databases and tables

As mentioned earlier, the database is created in the constructor call.

For table construction, onCreate() is usedpublic void onCreate(SQLiteDatabase db){String query = CREATE TABLE demo ( id INTEGER PRIMARY KEY, name TEXT, phone TEXT );db.execSQL(query);

}

SQLiteDatabase

All operations regarding the database is to be performed by the SQLiteDatabase object

Either the:getWritableDatabase() : Write mode

getReadableDatabase() : Read mode

used with the SQLiteDatabase object. SQLiteDatabase db = this.getWritableDatabase()db.insert(...)

SQLiteDatabase

This is the base class for working with the SQLite database in Android.

Provides methods to open, query, update and close the database:insert()

update()

delete()

To execute SQL statements, execSQL()

SQLiteDatabase

Queries can be created via the rawQuery() and query() methods or via the SQLiteQueryBuilder class.rawQuery() directly accepts an SQL select statement as input.

query() provides a structured interface for specifying the SQL query.

Inserting data into database

While inserting data into the database we always use ContentValues in Android

ContentValues allows definition of key/values.Key represents column identifier.

Values represents the content for the table record in the column.

public void addContact(String name, String address) {SQLiteDatabase db = this.getWritableDatabase();ContentValues values = new ContentValues();values.put(KEY_NAME, name);values.put(KEY_PHONE_NO, address);db.insert(TABLE_CONTACTS, null, values);db.close();

}

Extracting data

A query always returns a Cursor object.

A Cursor represents the result of a query and basically points to one row of the query result.

To move between individual data rows, we use the moveToFirst() and moveToNext() methods.

Extracting data

public Cursor getAllRows() {String where = null;Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null, null, null, null);if (c != null) {c.moveToFirst();

}return c;

}

Creating a simple application

Take inputs from the EditTexts.

Save to enter into database.

Show to display the database entries.

Clear to wipe the shown entries.

Logic

Save: call a function on Android's database to save the entry.

Show: call Cursor from the database and display the results respectively.

Programming the app

Create a separate class to handle all the database operations.

Follow the following steps:Declare all the variables needed.

Instantiate the Context and SQLiteDatabase object.

Declare the functions required to insert data into database as well as retrieve.

Declare another helper class that extends SQLiteOpenHelper.

Declare all the variables needed

public static final String DB_NAME = "demo_db";public static final String TABLE_NAME = "demo_table";

public static final int DB_VERSION = 1;

public final static String KEY_ROWID = "_id";// similarly declare static variables KEY_NAME and KEY_ADD

public final static String[] ALL_KEYS = { KEY_ROWID, KEY_NAME, KEY_ADD };public final static String TABLE_CREATE = "CREATE TABLE ;private final Context context;private SQLiteDatabase db;

Instantiate Context and SQLiteDatabase

Creating a constructor we declare the following://DBHelper is the class implementing the SQLiteOpenHelper DBHelper myDBHelper;public DBAdapter(Context cnt) {this.context = cnt;myDBHelper = new DBHelper(context);

}

Function to insert data

public long insertRow(String name, String add) {ContentValues initialValues = new ContentValues();initialValues.put(KEY_NAME, name);initialValues.put(KEY_ADD, add);

return db.insert(TABLE_NAME, null, initialValues);

}

Function to retrieve data

//Remember we are returning a Cursorpublic Cursor getAllRows() {String where = null;Cursor c = db.query(true, TABLE_NAME, ALL_KEYS,where, null, null, null, null, null);if (c != null) {c.moveToFirst();

}return c;

}

Extending the SQLiteOpenHelper

private static class DBHelper extends SQLiteOpenHelper {

public DBHelper(Context context) {super(context, DB_NAME, null, DB_VERSION);

}//onCreate and onUpdate are overridden

}

Programming the app

Use the functions declared in the helper classes in your main activity.

Retrieving entry from the Cursor:if (cursor.moveToFirst()) {do {int id = cursor.getInt(DBAdapter.COL_ROWID);String name = cursor.getString(DBAdapter.COL_NAME);String add = cursor.getString(DBAdapter.COL_ADD);message += "id= " + id +", name= " + name+", add= " + add +"\n";} while(cursor.moveToNext());

}

Full source code:http://bit.ly/1cFJApL