Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Session 2- day 3


Published on

-> ListView
-> ArrayAdapter
-> SimpleAdapter
-> Customized ListView
-> SQLite
-> Cursor
-> SimpleCursorAdapter

Published in: Technology
  • Be the first to comment

Session 2- day 3

  1. 1. ListView
  2. 2. ListViews ● ● Displays a group of scrollable items. The items are automatically inserted to list using an Adapter that pull content from a source.
  3. 3. Implementation ● Create a layout with listview <LinearLayout xmlns:android="" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <ListView android:id="@+id/list" android:layout_height="wrap_content" android:layout_width="match_parent"> </ListView> </LinearLayout>
  4. 4. In MainActivity ● Define the listview listView = (ListView) findViewById(; ● Define arrays to show in the ListView String[] values = { “abc”, “def” , “ijk” , “xyz”}; ● Use Adapter – Helper to feed data into the list view
  5. 5. Using Adapter: ArrayAdapter<String> ● 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
  6. 6. ● Define a new Adapter ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_ item_1,, values); – ● These are all generic layouts defined by Android for us Set the adapter listView.setAdapter(adapter); Notice android being referenced at first
  7. 7. ● 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(); }
  8. 8. ListView Usage
  9. 9. ListView with SimpleAdapter ● Similar to what we have discussed. ● Can be used to create a more dynamic layout. Name Address Details ... Layout for our program
  10. 10. 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”};
  11. 11. HashMaps ● They are used to store data in a key/value pair. ● Iterate all the arrays inside the HashMap for (int i = 0; i < name.length; i++) { HashMap<String, String> toFill = new HashMap<String, String>(); toFill.put("name", name[i]); toFill.put("address", address[i]); toFill.put("details", details[i]); // fill this HashMap inside an ArrayList listFill.add(toFill); }
  12. 12. 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 entires ArrayList<HashMap<String, String>> listFill; listFill = new ArrayList<HashMap<String, String>>();
  13. 13. 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
  14. 14. ● Defining the adapter: ListAdapter adapter = new SimpleAdapter(MainActivity.this, listFill,R.layout.custom_layout, new String[] { "name", "address","details" }, new int[] {,, }); ● Setting up adapter: listView.setAdapter(adapter);
  15. 15. ● Implementing the onItemClickListener: listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position,long id) { int itemPosition = position; HashMap<String, String> 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(); } });
  16. 16. 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
  17. 17. 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); }
  18. 18. 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
  19. 19. Creating databases and tables ● ● As mentioned earlier, the database is created in the constructor call. For table construction, onCreate() is used public void onCreate(SQLiteDatabase db){ String query = “CREATE TABLE demo ( id INTEGER PRIMARY KEY, name TEXT, phone TEXT )”; db.execSQL(query); }
  20. 20. 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(...)
  21. 21. SQLiteDatabase ● ● This is the base class for working with the SQLite database in Android. Provides methods to open, query, update and close the database: – – update() – ● insert() delete() To execute SQL statements, execSQL()
  22. 22. 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.
  23. 23. 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(); }
  24. 24. 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.
  25. 25. 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; }
  26. 26. 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.
  27. 27. Logic ● ● Save: call a function on Android's database to save the entry. Show: call Cursor from the database and display the results respectively.
  28. 28. 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.
  29. 29. 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;
  30. 30. 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); }
  31. 31. 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); }
  32. 32. Function to retrieve data //Remember we are returning a Cursor public 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; }
  33. 33. 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 }
  34. 34. 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()); }
  35. 35. ● Full source code: