SlideShare une entreprise Scribd logo
1  sur  35
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
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/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>
In MainActivity
●

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

●

Define arrays to show in the ListView
String[] values = { “abc”, “def” , “ijk” , “xyz”};

●

Use Adapter
–

Helper to feed data into the list view
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
●

Define a new Adapter
ArrayAdapter<String> adapter = new
ArrayAdapter<String>(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 adapter
listView.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.

Name

Address
Details ...
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 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);
}
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>>();
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() {
@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();
}
});
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 used
public 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:
–
–

update()

–
●

insert()
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 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;
}
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

Contenu connexe

Tendances

Android training day 5
Android training day 5Android training day 5
Android training day 5Vivek Bhusal
 
SenchaCon 2016: Keynote Presentation - Art Landro, Gautam Agrawal, Mark Brocato
SenchaCon 2016: Keynote Presentation - Art Landro, Gautam Agrawal, Mark BrocatoSenchaCon 2016: Keynote Presentation - Art Landro, Gautam Agrawal, Mark Brocato
SenchaCon 2016: Keynote Presentation - Art Landro, Gautam Agrawal, Mark BrocatoSencha
 
Workshop 26: React Native - The Native Side
Workshop 26: React Native - The Native SideWorkshop 26: React Native - The Native Side
Workshop 26: React Native - The Native SideVisual Engineering
 
Building Web Interface On Rails
Building Web Interface On RailsBuilding Web Interface On Rails
Building Web Interface On RailsWen-Tien Chang
 
Workshop 25: React Native - Components
Workshop 25: React Native - ComponentsWorkshop 25: React Native - Components
Workshop 25: React Native - ComponentsVisual Engineering
 
Learning Appcelerator® Alloy™
Learning Appcelerator® Alloy™Learning Appcelerator® Alloy™
Learning Appcelerator® Alloy™Ricardo Alcocer
 
Filters in AngularJS
Filters in AngularJSFilters in AngularJS
Filters in AngularJSBrajesh Yadav
 
Violet Peña - Storybook: A React Tool For Your Whole Team
Violet Peña - Storybook: A React Tool For Your Whole TeamViolet Peña - Storybook: A React Tool For Your Whole Team
Violet Peña - Storybook: A React Tool For Your Whole TeamAnton Caceres
 
Design for succcess with react and storybook.js
Design for succcess with react and storybook.jsDesign for succcess with react and storybook.js
Design for succcess with react and storybook.jsChris Saylor
 
Academy PRO: React native - navigation
Academy PRO: React native - navigationAcademy PRO: React native - navigation
Academy PRO: React native - navigationBinary Studio
 
Rails Best Practices
Rails Best PracticesRails Best Practices
Rails Best PracticesIcalia Labs
 
Styling recipes for Angular components
Styling recipes for Angular componentsStyling recipes for Angular components
Styling recipes for Angular componentsNir Kaufman
 
AngularJS - Services
AngularJS - ServicesAngularJS - Services
AngularJS - ServicesNir Kaufman
 
Angular2 & ngrx/store: Game of States
Angular2 & ngrx/store: Game of StatesAngular2 & ngrx/store: Game of States
Angular2 & ngrx/store: Game of StatesOren Farhi
 
Workshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte IIWorkshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte IIVisual Engineering
 
Introducing ExtReact: Adding Powerful Sencha Components to React Apps
Introducing ExtReact: Adding Powerful Sencha Components to React AppsIntroducing ExtReact: Adding Powerful Sencha Components to React Apps
Introducing ExtReact: Adding Powerful Sencha Components to React AppsSencha
 

Tendances (20)

Android training day 5
Android training day 5Android training day 5
Android training day 5
 
SenchaCon 2016: Keynote Presentation - Art Landro, Gautam Agrawal, Mark Brocato
SenchaCon 2016: Keynote Presentation - Art Landro, Gautam Agrawal, Mark BrocatoSenchaCon 2016: Keynote Presentation - Art Landro, Gautam Agrawal, Mark Brocato
SenchaCon 2016: Keynote Presentation - Art Landro, Gautam Agrawal, Mark Brocato
 
Workshop 26: React Native - The Native Side
Workshop 26: React Native - The Native SideWorkshop 26: React Native - The Native Side
Workshop 26: React Native - The Native Side
 
Building Web Interface On Rails
Building Web Interface On RailsBuilding Web Interface On Rails
Building Web Interface On Rails
 
Workshop 25: React Native - Components
Workshop 25: React Native - ComponentsWorkshop 25: React Native - Components
Workshop 25: React Native - Components
 
Workshop 17: EmberJS parte II
Workshop 17: EmberJS parte IIWorkshop 17: EmberJS parte II
Workshop 17: EmberJS parte II
 
Learning Appcelerator® Alloy™
Learning Appcelerator® Alloy™Learning Appcelerator® Alloy™
Learning Appcelerator® Alloy™
 
Extend sdk
Extend sdkExtend sdk
Extend sdk
 
Filters in AngularJS
Filters in AngularJSFilters in AngularJS
Filters in AngularJS
 
Rails Best Practices
Rails Best PracticesRails Best Practices
Rails Best Practices
 
Violet Peña - Storybook: A React Tool For Your Whole Team
Violet Peña - Storybook: A React Tool For Your Whole TeamViolet Peña - Storybook: A React Tool For Your Whole Team
Violet Peña - Storybook: A React Tool For Your Whole Team
 
Design for succcess with react and storybook.js
Design for succcess with react and storybook.jsDesign for succcess with react and storybook.js
Design for succcess with react and storybook.js
 
Academy PRO: React native - navigation
Academy PRO: React native - navigationAcademy PRO: React native - navigation
Academy PRO: React native - navigation
 
Rails Best Practices
Rails Best PracticesRails Best Practices
Rails Best Practices
 
Styling recipes for Angular components
Styling recipes for Angular componentsStyling recipes for Angular components
Styling recipes for Angular components
 
AngularJS - Services
AngularJS - ServicesAngularJS - Services
AngularJS - Services
 
Angular2 + rxjs
Angular2 + rxjsAngular2 + rxjs
Angular2 + rxjs
 
Angular2 & ngrx/store: Game of States
Angular2 & ngrx/store: Game of StatesAngular2 & ngrx/store: Game of States
Angular2 & ngrx/store: Game of States
 
Workshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte IIWorkshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte II
 
Introducing ExtReact: Adding Powerful Sencha Components to React Apps
Introducing ExtReact: Adding Powerful Sencha Components to React AppsIntroducing ExtReact: Adding Powerful Sencha Components to React Apps
Introducing ExtReact: Adding Powerful Sencha Components to React Apps
 

En vedette

Adapter & ListView & ExpandalbeListView
Adapter & ListView & ExpandalbeListViewAdapter & ListView & ExpandalbeListView
Adapter & ListView & ExpandalbeListViewYuki Anzai
 
Android development - ListView & Adapter
Android development - ListView & AdapterAndroid development - ListView & Adapter
Android development - ListView & AdapterLope Emano
 
Introduction to Listview in Android
Introduction to Listview in AndroidIntroduction to Listview in Android
Introduction to Listview in Androidtechnoguff
 
ListView and Custom ListView on Android Development [Thai]
ListView and Custom ListView on Android Development [Thai]ListView and Custom ListView on Android Development [Thai]
ListView and Custom ListView on Android Development [Thai]Somkiat Khitwongwattana
 
Library Management System
Library Management SystemLibrary Management System
Library Management SystemPankaj Kumar
 

En vedette (6)

Adapter & ListView & ExpandalbeListView
Adapter & ListView & ExpandalbeListViewAdapter & ListView & ExpandalbeListView
Adapter & ListView & ExpandalbeListView
 
Android development - ListView & Adapter
Android development - ListView & AdapterAndroid development - ListView & Adapter
Android development - ListView & Adapter
 
Introduction to Listview in Android
Introduction to Listview in AndroidIntroduction to Listview in Android
Introduction to Listview in Android
 
ListView and Custom ListView on Android Development [Thai]
ListView and Custom ListView on Android Development [Thai]ListView and Custom ListView on Android Development [Thai]
ListView and Custom ListView on Android Development [Thai]
 
Library Management System
Library Management SystemLibrary Management System
Library Management System
 
Cocomo model
Cocomo modelCocomo model
Cocomo model
 

Similaire à Session 2- day 3

Day 8: Dealing with Lists and ListViews
Day 8: Dealing with Lists and ListViewsDay 8: Dealing with Lists and ListViews
Day 8: Dealing with Lists and ListViewsAhsanul Karim
 
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...TAISEEREISA
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursorsinfo_zybotech
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursorsinfo_zybotech
 
RMySQL Tutorial For Beginners
RMySQL Tutorial For BeginnersRMySQL Tutorial For Beginners
RMySQL Tutorial For BeginnersRsquared Academy
 
jdbc_presentation.ppt
jdbc_presentation.pptjdbc_presentation.ppt
jdbc_presentation.pptDrMeenakshiS
 
Android database tutorial
Android database tutorialAndroid database tutorial
Android database tutorialinfo_zybotech
 
Spring data ii
Spring data iiSpring data ii
Spring data ii명철 강
 
React table tutorial project setup, use table, and usefilter
React table tutorial project setup, use table, and usefilterReact table tutorial project setup, use table, and usefilter
React table tutorial project setup, use table, and usefilterKaty Slemon
 
ZendCon2010 The Doctrine Project
ZendCon2010 The Doctrine ProjectZendCon2010 The Doctrine Project
ZendCon2010 The Doctrine ProjectJonathan Wage
 

Similaire à Session 2- day 3 (20)

Day 8: Dealing with Lists and ListViews
Day 8: Dealing with Lists and ListViewsDay 8: Dealing with Lists and ListViews
Day 8: Dealing with Lists and ListViews
 
spring-tutorial
spring-tutorialspring-tutorial
spring-tutorial
 
List Views
List ViewsList Views
List Views
 
Mysqlppt
MysqlpptMysqlppt
Mysqlppt
 
Mysqlppt
MysqlpptMysqlppt
Mysqlppt
 
Android L01 - Warm Up
Android L01 - Warm UpAndroid L01 - Warm Up
Android L01 - Warm Up
 
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursors
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursors
 
Android sq lite-chapter 22
Android sq lite-chapter 22Android sq lite-chapter 22
Android sq lite-chapter 22
 
Sql lite android
Sql lite androidSql lite android
Sql lite android
 
RMySQL Tutorial For Beginners
RMySQL Tutorial For BeginnersRMySQL Tutorial For Beginners
RMySQL Tutorial For Beginners
 
jdbc_presentation.ppt
jdbc_presentation.pptjdbc_presentation.ppt
jdbc_presentation.ppt
 
CS2309 JAVA LAB MANUAL
CS2309 JAVA LAB MANUALCS2309 JAVA LAB MANUAL
CS2309 JAVA LAB MANUAL
 
Android database tutorial
Android database tutorialAndroid database tutorial
Android database tutorial
 
Spring data ii
Spring data iiSpring data ii
Spring data ii
 
Sqlapi0.1
Sqlapi0.1Sqlapi0.1
Sqlapi0.1
 
List adapter with multiple objects
List adapter with multiple objectsList adapter with multiple objects
List adapter with multiple objects
 
React table tutorial project setup, use table, and usefilter
React table tutorial project setup, use table, and usefilterReact table tutorial project setup, use table, and usefilter
React table tutorial project setup, use table, and usefilter
 
ZendCon2010 The Doctrine Project
ZendCon2010 The Doctrine ProjectZendCon2010 The Doctrine Project
ZendCon2010 The Doctrine Project
 

Plus de Vivek Bhusal

Training Session 2
Training Session 2 Training Session 2
Training Session 2 Vivek Bhusal
 
Android training day 3
Android training day 3Android training day 3
Android training day 3Vivek Bhusal
 
Android training day 1
Android training day 1Android training day 1
Android training day 1Vivek Bhusal
 
Stores munk presentation_aug10 (1)
Stores munk presentation_aug10 (1)Stores munk presentation_aug10 (1)
Stores munk presentation_aug10 (1)Vivek Bhusal
 
Wisevote - opendataweek @
Wisevote - opendataweek @Wisevote - opendataweek @
Wisevote - opendataweek @Vivek Bhusal
 
Android training at GDG kathmandu Startup weekend bootcamp
Android training at GDG kathmandu Startup weekend bootcampAndroid training at GDG kathmandu Startup weekend bootcamp
Android training at GDG kathmandu Startup weekend bootcampVivek Bhusal
 

Plus de Vivek Bhusal (8)

Training Session 2
Training Session 2 Training Session 2
Training Session 2
 
Android training day 3
Android training day 3Android training day 3
Android training day 3
 
Android training day 1
Android training day 1Android training day 1
Android training day 1
 
Stores munk presentation_aug10 (1)
Stores munk presentation_aug10 (1)Stores munk presentation_aug10 (1)
Stores munk presentation_aug10 (1)
 
Mybudget
MybudgetMybudget
Mybudget
 
Wisevote - opendataweek @
Wisevote - opendataweek @Wisevote - opendataweek @
Wisevote - opendataweek @
 
Android training at GDG kathmandu Startup weekend bootcamp
Android training at GDG kathmandu Startup weekend bootcampAndroid training at GDG kathmandu Startup weekend bootcamp
Android training at GDG kathmandu Startup weekend bootcamp
 
My medical info
My medical infoMy medical info
My medical info
 

Dernier

Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 

Dernier (20)

Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 

Session 2- day 3

  • 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. Implementation ● Create a layout with listview <LinearLayout xmlns:android="http://schemas.android.com/apk/res/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. In MainActivity ● Define the listview listView = (ListView) findViewById(R.id.list); ● Define arrays to show in the ListView String[] values = { “abc”, “def” , “ijk” , “xyz”}; ● Use Adapter – Helper to feed data into the list view
  • 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. ● Define a new Adapter ArrayAdapter<String> adapter = new ArrayAdapter<String>(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 adapter listView.setAdapter(adapter); Notice android being referenced at first
  • 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(); }
  • 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. 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. 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. 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. 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. ● 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);
  • 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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()); }