Unit - 7 Advanced Android Concepts
Unit - 7 Advanced Android Concepts
The version of SQLite depends on the version of Android. See the following table:
Features of SQLite:
Following is a list of features which makes SQLite popular among other lightweight
databases:
o SQLite is totally free: SQLite is open-source. So, no license is required to work with
it.
o SQLite is server less: SQLite doesn't require a different server process or system to
operate.
o SQLite is very flexible: It facilitates you to work on multiple databases on the same
session on the same time.
o Configuration Not Required: SQLite doesn't require configuration. No setup or
administration required.
o SQLite is a cross-platform DBMS: You don't need a large range of different
platforms like Windows, Mac OS, Linux, and Unix. It can also be used on a lot of
embedded operating systems like Symbian, and Windows CE.
o Storing data is easy: SQLite provides an efficient way to store data.
o Variable length of columns: The length of the columns is variable and is not fixed.
It facilitates you to allocate only the space a field needs. For example, if you have a
varchar (200) column, and you put a 10 characters' length value on it, then SQLite
will allocate only 20 characters' space for that value not the whole 200 space.
o Provide large number of API's: SQLite provides API for a large range of
programming languages. For example: .Net languages (Visual Basic, C#), PHP, Java,
Objective C, Python and a lot of other programming language.
1
o SQLite is written in ANSI-C and provides simple and easy-to-use API.
o SQLite is available on UNIX (Linux, Mac OS-X, Android, iOS) and Windows (Win32,
WinCE, WinRT).
SQL vs SQLite
2
3. No Installation Needed
SQLite is very easy to learn. You don’t need to install and configure it. Just download
SQLite libraries in your computer and it is ready for creating the database.
4. Reliable
It updates your content continuously so, little or no work is lost in a case of power
failure or crash. SQLite is less bugs prone rather than custom written file I/O codes.
SQLite queries are smaller than equivalent procedural codes so, chances of bugs
are minimal.
5. Portable
SQLite is portable across all 32-bit and 64-bit operating systems and big- and little-
endian architectures. Multiple processes can be attached with same application file
and can read and write without interfering each other. It can be used with all
programming languages without any compatibility issue.
6. Accessible
SQLite database is accessible through a wide variety of third-party tools. SQLite
database's content is more likely to be recoverable if it has been lost. Data lives
longer than code.
7. Reduce Cost and Complexity
It reduces application cost because content can be accessed and updated using
concise SQL queries instead of lengthy and error-prone procedural queries. SQLite
can be easily extended in in future releases just by adding new tables and/or
columns. It also preserves the backwards compatibility.
Establishing Connection
To use SQLite database in android two classes are used for creating database and
manipulating data. They are SQLiteOpenHelper and SQLiteDatabase class.
The SQLiteOpenHelper class is used for database creation and version management. For
performing any database operation, you have to provide the implementation
of onCreate() and onUpgrade() methods of SQLiteOpenHelper class.
There are many methods in SQLiteOpenHelper class. Some of them are as follows:
Method Description
public abstract void onCreate(SQLiteDatabase called only once when database is created for
db) the first time.
public abstract void onUpgrade(SQLiteDatabase called when database needs to be upgraded.
db, int oldVersion, int newVersion)
public synchronized void close () closes the database object.
public void onDowngrade(SQLiteDatabase db, called when database needs to be
int oldVersion, int newVersion) downgraded.
3
SQLiteDatabase class contains methods to be performed on SQLite database such as
create, update, delete, select etc. There are many methods in SQLiteDatabase class. Some
of them are as follows:
Method Description
void execSQL(String sql) executes the sql query not select query. Basically used for
creating database and tables.
long insert(String table, String inserts a record on the database. The table specifies the
nullColumnHack, ContentValues table name, nullColumnHack doesn't allow completely
values) null values. If second argument is null, android will store
null values if values are empty. The third argument
specifies the values to be stored.
int update(String table, updates a row.
ContentValues values, String
whereClause, String[] whereArgs)
Cursor rawQuery(String query, returns a cursor over the result set.
String[] selectionArgs)
// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
// create notes table
String createQuery="CREATE TABLE mytable(id INTEGER PRIMARY
KEY,name TEXT,address TEXT)";
db.execSQL(createQuery);
}
// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_NAME);
// Create tables again
onCreate(db);
}
}
4
Data Manipulation
Following code snippet can be used to perform various manipulation operation like insert,
update, select and delete.
Following example will demonstrate the use of SQLite in Android. In this example, we are
creating three columns id, name and address in database table. Also we are creating
effective UI for showing different data manipulation operations.
sqlite_example.xml
5
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Id"
android:inputType="number"
android:id="@+id/edtId" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Name"
android:layout_below="@+id/edtId"
android:id="@+id/edtName" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Address"
android:layout_below="@+id/edtName"
android:id="@+id/edtAddress" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/edtAddress"
android:id="@+id/btnInsert"
android:text="Insert" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/edtAddress"
android:layout_toRightOf="@+id/btnInsert"
android:id="@+id/btnSelect"
android:layout_marginLeft="10dp"
android:text="Select" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/edtAddress"
android:layout_toRightOf="@+id/btnSelect"
android:id="@+id/btnUpdate"
android:layout_marginLeft="10dp"
android:text="Update" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/edtAddress"
android:layout_toRightOf="@+id/btnUpdate"
android:id="@+id/btnDelete"
android:layout_marginLeft="10dp"
android:text="Delete" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Selected Data:"
android:layout_below="@+id/btnSelect"
6
android:layout_marginTop="10dp"
android:id="@+id/txtData"
android:textSize="18sp" />
</RelativeLayout>
Now we are creating Helper class for SQLite operations by extending SQLiteOpenHelpter
as follows:
// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
// create notes table
String createQuery="CREATE TABLE mytable(id INTEGER PRIMARY
KEY,name TEXT, address TEXT)";
db.execSQL(createQuery);
}
// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_NAME);
// Create tables again
onCreate(db);
}
7
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put("name",name);
contentValues.put("address",address);
//updating row
db.update("mytable",contentValues,"id=?",new String[]{id});
db.close();
}
edtId=findViewById(R.id.edtId);
edtName=findViewById(R.id.edtName);
edtAddress=findViewById(R.id.edtAddress);
btnInsert=findViewById(R.id.btnInsert);
btnUpdate=findViewById(R.id.btnUpdate);
btnSelect=findViewById(R.id.btnSelect);
btnDelete=findViewById(R.id.btnDelete);
txtData=findViewById(R.id.txtData);
btnInsert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int id=Integer.parseInt(edtId.getText().toString());
String name=edtName.getText().toString();
String address=edtAddress.getText().toString();
//calling insert function
myDbHelper.insertData(id,name,address);
Toast.makeText(getApplicationContext(),"Data Inserted
Successfully !", Toast.LENGTH_SHORT).show();
}
});
btnSelect.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//retrieving data
int id=0;
8
String name="",address="";
//calling select function
Cursor cursor=myDbHelper.selectData();
while (cursor.moveToNext()){
id=cursor.getInt(0);
name=cursor.getString(1);
address=cursor.getString(2);
}
//displaying data in TextView
txtData.setText("Id="+id+"\t Name="+name+"\tAddress="
+address);
}
});
btnUpdate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String id=edtId.getText().toString();
String name=edtName.getText().toString();
String address=edtAddress.getText().toString();
//calling insert function
myDbHelper.updateData(id,name,address);
Toast.makeText(getApplicationContext(),"Data Updated
Successfully !",Toast.LENGTH_SHORT).show();
}
});
btnDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String id=edtId.getText().toString();
//calling delete function
myDbHelper.deleteData(id);
Toast.makeText(getApplicationContext(),"Data Deleted
Successfully !",Toast.LENGTH_SHORT).show();
}
});
}
}
9
Figure 7-1. Output demonstrating various operation using SQLite
list_items.xml
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:layout_margin="10dp"
android:text="Id"
android:textStyle="bold"
10
android:id="@+id/txtId" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:id="@+id/txtName"
android:textStyle="bold"
android:layout_toRightOf="@+id/txtId"
android:layout_marginTop="10dp"
android:text="Name" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:id="@+id/txtAddress"
android:text="Address"
android:layout_marginLeft="10dp"
android:layout_below="@+id/txtName" />
</RelativeLayout>
sqlite_example.xml
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Id"
android:inputType="number"
android:id="@+id/edtId" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Name"
android:layout_below="@+id/edtId"
android:id="@+id/edtName" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Address"
android:layout_below="@+id/edtName"
android:id="@+id/edtAddress" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/edtAddress"
android:id="@+id/btnInsert"
android:text="Insert" />
11
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/edtAddress"
android:layout_toRightOf="@+id/btnInsert"
android:id="@+id/btnSelect"
android:layout_marginLeft="10dp"
android:text="Select" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/edtAddress"
android:layout_toRightOf="@+id/btnSelect"
android:id="@+id/btnUpdate"
android:layout_marginLeft="10dp"
android:text="Update" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/edtAddress"
android:layout_toRightOf="@+id/btnUpdate"
android:id="@+id/btnDelete"
android:layout_marginLeft="10dp"
android:text="Delete" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Selected Data:"
android:layout_below="@+id/btnSelect"
android:layout_marginTop="10dp"
android:id="@+id/txtData"
android:textSize="18sp" />
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/mylist"
android:layout_below="@+id/txtData" />
</RelativeLayout>
ListAdapter.java
12
this.address=address;
}
txtId.setText(id.get(position).toString());
txtName.setText(name.get(position).toString());
txtAddress.setText(address.get(position).toString());
return rowView;
};
}
SqliteExample.java
edtId=findViewById(R.id.edtId);
edtName=findViewById(R.id.edtName);
edtAddress=findViewById(R.id.edtAddress);
btnInsert=findViewById(R.id.btnInsert);
btnUpdate=findViewById(R.id.btnUpdate);
btnSelect=findViewById(R.id.btnSelect);
btnDelete=findViewById(R.id.btnDelete);
listView=findViewById(R.id.mylist);
btnInsert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int id=Integer.parseInt(edtId.getText().toString());
String name=edtName.getText().toString();
String address=edtAddress.getText().toString();
//calling insert function
myDbHelper.insertData(id,name,address);
Toast.makeText(getApplicationContext(),"Data Inserted
Successfully !",Toast.LENGTH_SHORT).show();
}
});
btnSelect.setOnClickListener(new View.OnClickListener() {
@Override
13
public void onClick(View view) {
//creating dynamic array using Arraylist
//array is not suitable for this example
ArrayList<Integer> id=new ArrayList<>();
ArrayList<String> name=new ArrayList<>();
ArrayList<String> address=new ArrayList<>();
//calling select function
Cursor cursor=myDbHelper.selectData();
while (cursor.moveToNext()){
id.add(cursor.getInt(0));
name.add(cursor.getString(1));
address.add(cursor.getString(2));
}
ListAdapter adapter=new ListAdapter
(SqliteExample.this,id,name,address);
listView.setAdapter(adapter);
}
});
btnUpdate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String id=edtId.getText().toString();
String name=edtName.getText().toString();
String address=edtAddress.getText().toString();
//calling insert function
myDbHelper.updateData(id,name,address);
Toast.makeText(getApplicationContext(),"Data Updated
Successfully !",Toast.LENGTH_SHORT).show();
}
});
btnDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String id=edtId.getText().toString();
//calling delete function
myDbHelper.deleteData(id);
Toast.makeText(getApplicationContext(),"Data Deleted
Successfully !",Toast.LENGTH_SHORT).show();
}
});
}
}
14
Figure 7-2. Output demonstrating displaying retrieved data in ListView
sqlite_example.xml
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Id"
android:inputType="number"
android:id="@+id/edtId" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Name"
15
android:layout_below="@+id/edtId"
android:id="@+id/edtName" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Address"
android:layout_below="@+id/edtName"
android:id="@+id/edtAddress" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/edtAddress"
android:id="@+id/btnInsert"
android:text="Insert" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/edtAddress"
android:layout_toRightOf="@+id/btnInsert"
android:id="@+id/btnSelect"
android:layout_marginLeft="10dp"
android:text="Select" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/edtAddress"
android:layout_toRightOf="@+id/btnSelect"
android:id="@+id/btnUpdate"
android:layout_marginLeft="10dp"
android:text="Update" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/edtAddress"
android:layout_toRightOf="@+id/btnUpdate"
android:id="@+id/btnDelete"
android:layout_marginLeft="10dp"
android:text="Delete" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Selected Data:"
android:layout_below="@+id/btnSelect"
android:layout_marginTop="10dp"
android:id="@+id/txtData"
android:textSize="18sp" />
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/recyclerview"
android:layout_below="@+id/txtData" />
</RelativeLayout>
16
DataModel.java
RecyclerViewAdapter.java
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
LayoutInflater layoutInflater = LayoutInflater.from(context);
View listItem= layoutInflater.inflate(R.layout.list_items,
parent, false);
ViewHolder viewHolder = new ViewHolder(listItem);
return viewHolder;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
final DataModel current=data.get(position);
holder.txtId.setText(current.getId()+"");
holder.txtName.setText(current.getName());
holder.txtAddress.setText(current.getAddress());
}
17
@Override
public int getItemCount() {
return data.size();
}
SqliteExample.java
edtId=findViewById(R.id.edtId);
edtName=findViewById(R.id.edtName);
edtAddress=findViewById(R.id.edtAddress);
btnInsert=findViewById(R.id.btnInsert);
btnUpdate=findViewById(R.id.btnUpdate);
btnSelect=findViewById(R.id.btnSelect);
btnDelete=findViewById(R.id.btnDelete);
recyclerView=findViewById(R.id.recyclerview);
btnInsert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int id=Integer.parseInt(edtId.getText().toString());
String name=edtName.getText().toString();
String address=edtAddress.getText().toString();
//calling insert function
myDbHelper.insertData(id,name,address);
Toast.makeText(getApplicationContext(),"Data Inserted
Successfully !",Toast.LENGTH_SHORT).show();
}
});
btnSelect.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
18
ArrayList<DataModel> data=new ArrayList<>();
//calling select function
Cursor cursor=myDbHelper.selectData();
while (cursor.moveToNext()){
int id=cursor.getInt(0);
String name=cursor.getString(1);
String address=cursor.getString(2);
DataModel dataModel=new DataModel(id,name,address);
data.add(dataModel);
}
//plotting in recyclerview
layoutManager=new LinearLayoutManager
(SqliteExample.this);
recyclerView.setLayoutManager(layoutManager);
recyclerViewAdapter=new RecyclerViewAdapter
(SqliteExample.this,data);
recyclerView.setAdapter(recyclerViewAdapter);
}
});
btnUpdate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String id=edtId.getText().toString();
String name=edtName.getText().toString();
String address=edtAddress.getText().toString();
//calling insert function
myDbHelper.updateData(id,name,address);
Toast.makeText(getApplicationContext(),"Data Updated
Successfully !",Toast.LENGTH_SHORT).show();
}
});
btnDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String id=edtId.getText().toString();
//calling delete function
myDbHelper.deleteData(id);
Toast.makeText(getApplicationContext(),"Data Deleted
Successfully !",Toast.LENGTH_SHORT).show();
}
});
}
}
19
Figure 7-3. Output demonstrating displaying retrieved data in RecyclerView
Introduction to API
API is an abbreviation for Application Programming Interface which is a collection of
communication protocols and subroutines used by various programs to communicate
between them. A programmer can make use of various API tools to make its program easier
and simpler. Also, an API facilitates the programmers with an efficient way to develop their
software programs.
Thus in simpler terms, an API helps two programs or applications to communicate with
each other by providing them with necessary tools and functions. It takes the request from
the user and sends it to the service provider and then again sends the result generated
from the service provider to the desired user.
A developer extensively uses API’s in his software to implement various features by using
an API call without writing the complex codes for the same. We can create an API for an
operating system, database systems, hardware system, for a JavaScript file or similar object
oriented files. Also, an API is similar to a GUI (Graphical User Interface) with one major
difference. Unlike GUI’s, an API helps the software developers to access the web tools while
a GUI helps to make a program easier to understand by the users.
20
Real life example of an API:
Suppose, we are searching for a hotel room on an online website. In this case, you have a
vast number of options to choose from and this may include the hotel location, the check-
in and check-out dates, price, accommodation details and many more factors. So in order
to book the room online, you need to interact with the hotel booking’s website which in
further will let you know if there is a room available on that particular date or not and at
what price.
Now in the above example, the API is the interface that actually communicates in between.
It takes the request of the user to the hotel booking’s website and in turn returns back the
most relevant data from the website to the intended user. Thus, we can see from this
example how an API works and it has numerous applications in real life from switching on
mobile phones to maintaining a large amount of databases from any corner of the world.
Types of API
There are various kinds of API’s available according to their uses and applications like the
Browser API which is created for the web browsers to abstract and to return the data from
surroundings or the Third party API’s, for which we have to get the codes from other sites
on the web (e.g. Facebook, Twitter).
2. Local APIs:
In this types of API, the programmers get the local middleware services. TAPI
(Telephony Application Programming Interface), .NET are common examples of
Local API’s.
3. Program APIs:
It makes a remote program appears to be local by making use of RPC’s (Remote
Procedural Calls). SOAP is a well-known example of this type of API.
21
Few other types of APIs:
• SOAP (SIMPLE OBJECT ACCESS PROTOCOL): It defines messages in XML format
used by web applications to communicate with each other.
• REST (Representational State Transfer): It makes use of HTTP to GET, POST, PUT,
or DELETE data. It is basically used to take advantage of the existing data.
• JSON-RPC: It use JSON for data transfer and is a light-weight remote procedural call
defining few data structure types.
• XML-RPC: It is based on XML and uses HTTP for data transfer. This API is widely used
to exchange information between two or more networks.
Introduction to JSON
JSON — short for JavaScript Object Notation — is a format for sharing data. As its name
suggests, JSON is derived from the JavaScript programming language, but it’s available for
use by many languages including Python, Ruby, PHP, and Java.
JSON uses the .json extension when it stands alone. When it’s defined in another file
format (as in .html), it can appear inside of quotes as a JSON string, or it can be an object
assigned to a variable. This format is easy to transmit between web server and client or
browser.
Very readable and lightweight, JSON offers a good alternative to XML and requires much
less formatting. This informational guide will get you up to speed with the data you can use
in JSON files, and the general structure and syntax of this format.
22
A JSON object looks something like this:
{
"sid" : "111",
"name" : "Raazu Poudel",
"address" : "Birtamode"
}
Although this is a very short example, and JSON could be many lines long, this shows that
the format is generally set up with two curly braces (or curly brackets) that look like this
{ } on either end of it, and with key-value pairs populating the space between. Most data
used in JSON ends up being encapsulated in a JSON object.
Key-value pairs have a colon between them as in "key" : "value". Each key-value pair is
separated by a comma, so the middle of a JSON looks like this: "key" : "value", "key" :
"value", "key": "value". In our example above, the first key-value pair is "sid" : "111".
getdata.php
<?php
$server="localhost";
$username="root";
$password="";
$database="bcatest";
// Create connection
$conn = new mysqli($server, $username, $password,$database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
23
//retrieving data
$sql = "SELECT * FROM student";
$result = $conn->query($sql);
echo json_encode($json);
$conn->close();
?>
Testing in browser:
DecodingJSON.java
24
" ]\n" +
"}";
//decoding JSON
JSONObject result=new JSONObject(json_data);
JSONArray data=result.getJSONArray("data");
for(int i=0;i<data.length();i++){
//fetching each row
JSONObject student=data.getJSONObject(i);
int sid=student.getInt("sid");
String name=student.getString("name");
String address=student.getString("address");
//displaying data
Log.d("Row "+i,sid+" "+name+" "+address);
}
}catch (Exception ex){
Log.d("exception",ex.toString());
}
}
}
25
To use volley in your application, we need to add following dependency in our project:
dependencies {
...
implementation 'com.android.volley:volley:1.1.1'
}
Also, to use Volley, you must add the android.permission.INTERNET permission to your
app's manifest. Without this, your app won't be able to connect to the network.
<uses-permission android:name="android.permission.INTERNET"/>
26
Displaying Retrieved data in RecyclerView
json_example.xml
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/recyclerview" />
</RelativeLayout>
list_items.xml
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:layout_margin="10dp"
android:text="Id"
android:textStyle="bold"
android:id="@+id/txtId" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:id="@+id/txtName"
android:textStyle="bold"
android:layout_toRightOf="@+id/txtId"
android:layout_marginTop="10dp"
android:text="Name" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:id="@+id/txtAddress"
android:text="Address"
android:layout_marginLeft="10dp"
android:layout_below="@+id/txtName" />
</RelativeLayout>
27
DataModel.java
RecyclerViewAdapter.java
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
LayoutInflater layoutInflater = LayoutInflater.from(context);
View listItem= layoutInflater.inflate(R.layout.list_items,
parent, false);
ViewHolder viewHolder = new ViewHolder(listItem);
return viewHolder;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
final DataModel current=data.get(position);
holder.txtId.setText(current.getId()+"");
holder.txtName.setText(current.getName());
holder.txtAddress.setText(current.getAddress());
}
28
@Override
public int getItemCount() {
return data.size();
}
JsonExample.java
29
public void decodeJson(String response){
try{
ArrayList<DataModel> data=new ArrayList<>();
JSONObject result=new JSONObject(response);
JSONArray array=result.getJSONArray("data");
for(int i=0;i<array.length();i++){
//fetching each row
JSONObject student=array.getJSONObject(i);
int sid=student.getInt("sid");
String name=student.getString("name");
String address=student.getString("address");
DataModel dataModel=new DataModel(sid,name,address);
data.add(dataModel);
}
30
Sending Contents to Remote Server
send_data.xml
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Id"
android:inputType="number"
android:id="@+id/edtId" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Name"
android:layout_below="@+id/edtId"
android:id="@+id/edtName" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Address"
android:layout_below="@+id/edtName"
android:id="@+id/edtAddress" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/edtAddress"
android:id="@+id/btnSubmit"
android:layout_centerHorizontal="true"
android:text="Submit" />
</RelativeLayout>
SendData.java
edtId=findViewById(R.id.edtId);
edtName=findViewById(R.id.edtName);
edtAddress=findViewById(R.id.edtAddress);
btnSubmit=findViewById(R.id.btnSubmit);
31
btnSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
volleyRequest();
}
});
};;
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
}
setdata.php
<?php
32
//server credentials
$server="localhost";
$username="root";
$password="";
$database="bcatest";
// Create connection
$conn = new mysqli($server, $username, $password,$database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//inserting data
$sql = "INSERT INTO student(sid,name,address)
VALUES('".$sid."','".$name."','".$address."')";
$result = $conn->query($sql);
if($result)
echo"Data Inserted Successfully !";
else
echo"Failed to Insert Data !";
$conn->close();
?>
33
Implementing Google Maps in Android Application
Android allows us to integrate Google Maps in our application. For this Google provides us
a library via Google Play Services for using maps. In order to use the Google Maps API, you
must register your application on the Google Developer Console and enable the API.
An API key is needed to access the Google Maps servers. This key is free and you can use
it with any of your applications. If you haven’t created project, you can follow the below
steps to get started:
Step 1: Open Google developer console and sign in with your Gmail
account: https://console.developers.google.com/project
Step 2: Now create new project. You can create new project by clicking on the Create
Project button and give name to your project.
Step 3: Now click on APIs & Services and open Dashboard from it.
34
Step 5: Now search for Google Map Android API and enable it.
Step 7: Now click on Create credentials and choose API key. It will create API key to
integrate maps in your application.
35
Step 8: Now API your API key will be generated. Copy it and save it somewhere as we will
need it when implementing Google Map in our Android project.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
Step 2: Add your generated API Key in your manifest file inside application tag as follows.
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="AIzaSyCWIdlyqlFhC7lOthG164H42heV1F7N3v0" />
dependencies {
. . .
. . .
implementation 'com.google.android.gms:play-services-maps:15.0.1'
}
map_activity.xml
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
tools:context=".MapsActivity"
android:layout_width="match_parent"
36
android:layout_height="match_parent" />
</RelativeLayout>
MapsActivity.java
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Adding latitude and longitude
LatLng location = new LatLng(26.644096, 87.989391);
//Adding red marker to point location
mMap.addMarker(new MarkerOptions().position(location).
title("Marker in Birtamode"));
//Moving camera to desired location
mMap.moveCamera(CameraUpdateFactory.newLatLng(location));
//Adding zoom effect
mMap.animateCamera(CameraUpdateFactory.zoomTo(12.0f) );
}
}
37
Figure 7-7. Output Demonstrating Google Map.
Note: Don’t use com.example…. as a package name because example is not supported by
play store. Instead you can rename your package name.
38
Step 2: Now click Create new keystore file. This keystore file is necessary to upload new
app and for updating existing app. If you have already created keystore file, then you can
click Choose existing keystore file.
Step 3: Now fill up information for creating new keystore file and click ok. Example is shown
below.
Note: Please remember keystore file, username and password because if it is lost, then
you will be unable to update your application.
39
Step 4: Now select V1 (Jar Signature) and click Finish. This will create signed APK for
release.
40
Step 5: Now click Event Log and locate to the folder where signed APK has been placed.
You can get your signed APK file inside release folder.
Here you need to create your developer account for lifetime by paying $25 using your
credit card. There is no limitation for number of apps. You can upload multiple apps using
a single account.
Step 2: Once you’ve created developer account following page will be displayed on screen.
Click Create Application.
41
Step 3: Next, give your application a title and the default language. You will now be moved
to the Store listing screen.
In store listing page you must add everything related to how your app will look in the store.
Following information must be added in this page:
• A short description of your application
• A full description
• Screenshots (at least 2)
• A Hi Resolution Icon
• A Feature Graphic
• The application’s type and its category
• Your email
• Your privacy policy (if you don’t have one, check the Not submitting a privacy policy
checkbox)
Step 4: Now go to the App Releases page and click Create Release button. Following page
will be displayed on screen.
42
Here you can upload your signed APK. Here you can also give the release a name and
specify what is new in this release. Pay special attention to whatever you type in what is
new in this release because it will appear in the Play store under the What’s New section.
Once you are done, you can press the Review button on the lower right corner of the page.
After pressing the Continue button, you will be asked several questions regarding the
content of your application. Just follow them in order, filling one by one.
43
Step 6: Last but not least, go to Pricing & distribution page. Be aware to fill in all the
required fields. In this last page, you can decide on:
• If your application will be free or not
• Which countries your application will be available to
• If it contains ads
• User programs
Step 7: After filling up all the information regarding Store Listings, Content Rating, Pricing
& Distribution etc. Now you can go to App Release page to publish your application. To
publish app in play store, click Rollout Button.
Exercise
44
12. Explain the advantages of JSON over XML.
13. How do your communication your application with remote server? Explain with the
help of suitable example.
14. Develop an android application that demonstrates retrieval of contents from
remote server.
15. Develop an android application that demonstrates sending of contents to remote
server.
16. Develop a phone directory application (Phone records must be stored in remote
server).
17. Explain the procedure for generating API key for displaying google map in your
application.
18. Develop an android application that displays google map.
19. Explain the procedure for generating signed APK.
20. Explain the procedure for publishing signed APK in play store.
45