Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Android tutorial
1. The Android platform
With Android's breadth of capabilities, it would be easy to confuse it with a desktop operating
system. Android is a layered environment built upon a foundation of the Linux kernel, and it includes
rich functions. The UI subsystem includes:
Windows
Views
Widgets for displaying common elements such as edit boxes, lists, and drop-down lists
Android includes an embeddable browser built upon WebKit, the same open source browser engine
powering the iPhone's Mobile Safari browser.
Android boasts a healthy array of connectivity options, including WiFi, Bluetooth, and wireless data
over a cellular connection (for example, GPRS, EDGE, and 3G). A popular technique in Android
applications is to link to Google Maps to display an address directly within an application. Support for
location-based services (such as GPS) and accelerometers is also available in the Android software
stack, though not all Android devices are equipped with the required hardware. There is also camera
support.
Historically, two areas where mobile applications have struggled to keep pace with their desktop
counterparts are graphics/media, and data storage methods. Android addresses the graphics
challenge with built-in support for 2-D and 3-D graphics, including the OpenGL library. The data-
storage burden is eased because the Android platform includes the popular open source SQLite
database. Figure 1 shows a simplified view of the Android software layers.
Figure 1. Android software layers
Back to top
Application architecture
As mentioned, Android runs atop a Linux kernel. Android applications are written in the Java
programming language, and they run within a virtual machine (VM). It's important to note that the VM
is not a JVM as you might expect, but is the Dalvik Virtual Machine, an open source technology.
2. Each Android application runs within an instance of the Dalvik VM, which in turn resides within a
Linux-kernel managed process, as shown below.
Figure 2.Dalvik VM
An Android application consists of one or more of the following classifications:
Activities
An application that has a visible UI is implemented with an activity. When a user selects an
application from the home screen or application launcher, an activity is started.
Services
A service should be used for any application that needs to persist for a long time, such as a
network monitor or update-checking application.
Content providers
You can think of content providers as a database server. A content provider's job is to
manage access to persisted data, such as a SQLite database. If your application is very
simple, you might not necessarily create a content provider. If you're building a larger
application, or one that makes data available to multiple activities or applications, a content
provider is the means of accessing your data.
Intent/Broadcast receivers
An Android application may be launched to process an element of data or respond to an
event, such as the receipt of a text message.
An Android application, along with a file called AndroidManifest.xml, is deployed to a device.
AndroidManifest.xml contains the necessary configuration information to properly install it to the
device. It includes the required class names and types of events the application is able to process,
and the required permissions the application needs to run. For example, if an application requires
access to the network — to download a file, for example — this permission must be explicitly stated
in the manifest file. Many applications may have this specific permission enabled. Such declarative
security helps reduce the likelihood that a rogue application can cause damage on your device.
First Android Project
Go to File Menu and select New Project. Following dialog box will appear select Android Project and
press Next
3. Fill in the following detail i.e. Project Name, Package Name, Activity Name, Application Name and select
the Build Target (Android SDK Version) and press “Finish”
4. Following structure tree will appear in Package Explorer window.
In above structure following things are noticeable.
5. Src
o Package that will contain source code for project
Gen
o Package that will contain automatic generated code like R.java
Assets
o Folder that will contain the assets of application like DB, data storage files etc.
Res
o Folder that will contain all the resources like, layouts, graphics and constant values,
animations etc.
AndroidManifest.xml
o A Configuration file for android application.
Now make a Virtual Device by clicking on the mobile icon on you eclipse IDE or select from Window
menu “Android SDK and AVD Manager” a Dialog box like below will appear. Press New.
Create new AVD dialog will appear fill in the fields like given in the image.
11. Now Add the Following Code in start of class
//Private Controls
EditTexttxtFname,txtLastName,txtId,txtCourse;
Button btnSubmit,btnClear;
Add the following code after setContentView(R.layout.main);
//Getting layout's Controls
txtFname=(EditText)findViewById(R.id.txtFName);
txtLastName=(EditText)findViewById(R.id.txtLastName);
txtId=(EditText)findViewById(R.id.txtId);
txtCourse=(EditText)findViewById(R.id.txtCourse);
btnSubmit=(Button)findViewById(R.id.btn1);
btnClear=(Button)findViewById(R.id.btn2);
Now implement the OnClickListener Interface but add
Implements OnClickListener to Class definition i.e.
publicclassMainActivityextends Activity implementsOnClickListener
Now Implement the OnClick Method of OnClickListener Interface
@Override
publicvoidonClick(View v) {
// TODO Auto-generated method stub
}
Add the following code for Button Clicks in onClick Method
switch(v.getId())
{
case R.id.btn1:
break;
case R.id.btn2:
//Clear Controls
this.txtFname.setText("");
this.txtLastName.setText("");
this.txtId.setText("");
this.txtCourse.setText("");
break;
}
Now Register Buttons with Click Handler
13. Click “Finish” after entering File name
Now open the XML and Add following Code
<?xmlversion="1.0"encoding="UTF-8"?>
<LinearLayoutandroid:id="@+id/LinearLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical">
<LinearLayoutandroid:id="@+id/LinearLayout01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="20dip">
<TextViewandroid:text="FName: "
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextViewandroid:text="Name"
android:id="@+id/lblName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
15. Now Add a New class in Source Package and name it as StudentDetail. Extend it from Activity.
Add Following Code to OnClick method of MainActivity in first Case of switch statement now you onClick
Method should look like this
@Override
publicvoidonClick(View v) {
// TODO Auto-generated method stub
switch(v.getId())
{
case R.id.btn1:
//Code to submit data to next activity
Intent i=newIntent(this,StudentDetail.class);
i.putExtra("FName", txtFname.getText().toString());
i.putExtra("LName", txtLastName.getText().toString());
i.putExtra("Id", txtId.getText().toString());
i.putExtra("Course",txtCourse.getText().toString());
startActivity(i);
break;
case R.id.btn2:
this.txtFname.setText("");
this.txtLastName.setText("");
this.txtId.setText("");
this.txtCourse.setText("");
break;
}
}
Add the Following code in StudentDetail Class
TextViewlblFname, lblLastName,lblID,lblCourse;
Button btnBack;
@Override
protectedvoidonCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
//Setting the Layout
setContentView(R.layout.studentdetail);
lblFname=(TextView)findViewById(R.id.lblName);
lblLastName=(TextView)findViewById(R.id.lblLName);
lblID=(TextView)findViewById(R.id.lblId);
lblCourse=(TextView)findViewById(R.id.lblCourse);
btnBack=(Button)findViewById(R.id.btnBack);
//Setting on Click of Back Button
btnBack.setOnClickListener(this);
//Getting Student Detail from Intent and populating the controls
Bundle extras=getIntent().getExtras();
16. lblFname.setText(extras.getString("FName"));
lblLastName.setText(extras.getString("LName"));
lblID.setText(extras.getString("Id"));
lblCourse.setText(extras.getString("Course"));
}
@Override
publicvoidonClick(View v) {
// TODO Auto-generated method stub
this.finish();
}
Now Add you NewActivity(StudentDetail) in the AndroidManifest File
<activityandroid:name=".StudentDetail"android:label="Student Detail"/>
Add above line in AndroidManifest file right below the </Activity> Tag
Now Run you Application.
Using Database in Android Applications
Now we will extend our previous project to a database driven application.
Android Uses SQLite as Database Engine for its Application it is an embeded library that works with
general SQL and is generally use with mobile platforms .
Add a new class to your source package name it asDBHelper
Add a Constructor with one parameter Context.
Context ctx;
//Database Object
SQLiteDatabasedb;
//Create Table Statement
final String CREATE_TABLE_STUDENT =
"CREATE TABLE tbl_student ("
+ "id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "f_nameTEXT,l_nameTEXT,courseTEXT,std_id TEXT);";
//one argument Constructor
publicDBHandler(Context mContext){
ctx=mContext;
}
Now Add Following Function to Create new Database
17. privatevoidcreateOpenDB(){
try{db = ctx.openOrCreateDatabase(
"StudentData.db"
,
SQLiteDatabase.CREATE_IF_NECESSARY
, null
);
db.setVersion(1);
db.setLocale(Locale.getDefault());
db.setLockingEnabled(true);
db.execSQL(CREATE_TABLE_STUDENT);
}catch(Exception ex){
db=ctx.openOrCreateDatabase("StudentData.db",SQLiteDatabase.OPEN_READWRITE,nu
ll);
db.setVersion(2);
db.setLocale(Locale.getDefault());
db.setLockingEnabled(true);
}
}
Add Code of Record Insertion
publicvoidinsertDate(String fName,StringlName,String course, String stdId){
createDB();
ContentValues values = newContentValues();
values.put("f_name", fName);
values.put("l_name",lName);
values.put("course", course);
values.put("std_id",stdId);
db.insert("tbl_student", null, values);
Toast.makeText(ctx, "Record Saved",Toast.LENGTH_LONG).show();
}
Add an object of DBHandler Class in Main Activity first
DBHandlerobjDB;
Now initialize this object in OnCreate Method
objDB=new DBHandler(this);
Now Add the Code to insert record
//Code to submit data to next activity
Intent i=newIntent(this,StudentDetail.class);
i.putExtra("FName", txtFname.getText().toString());
18. i.putExtra("LName", txtLastName.getText().toString());
i.putExtra("Id", txtId.getText().toString());
i.putExtra("Course",txtCourse.getText().toString());
//
objDB.insertDate(txtFname.getText().toString(),txtLastName.getText().to
String(),txtCourse.getText().toString(), txtId.getText().toString());
startActivity(i);
Run your Application now on Submit button click it will save the record in
the database and show the current record on next screen.
Now Add Code to Fetch Record in DBHandler class
public Cursor fetchTableData(String sql) {
returndb.rawQuery(sql,null);
}
This method will fetch the data into a cursor
Now we will have to write a method to store retrieved data into a list so we
can use it on other places.
publicArrayList<String>getData(){
createDB();
ArrayListstudentList=newArrayList<String>();
Cursor cur =fetchTableData("select * from tbl_student");
cur.moveToFirst();
while (cur.isAfterLast() == false) {
studentList.add(cur.getString(1));
cur.moveToNext();
}
cur.close();
returnstudentList;
}
Now Add a New XML in layout folder name it as student_list.xml
Add following code in this newly created xml file.
<?xmlversion="1.0"encoding="UTF-8"?>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<ListViewandroid:id="@+id/listStudent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
19. Above design contains a ListView which will show a list in your Activity.
Now Create another XML file in layout folder as which will represent each
cell of ListView given in above design.
Name this new XML file as student_row.xml and paste the following code into
it.
<?xmlversion="1.0"encoding="UTF-8"?>
<TextViewandroid:id="@+id/text1"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15dip"/>
Now Add another class named StudentList.Java in you source package.
Extend it from Activity to make it an Activity. Implement OnCreate Method.
Define private controls and objects
//List of Students
ListViewlistStudents;
//DB Object
DBHandlerobjDB;
Now paste the following code in the OnCreate Method.
//initialization of DB Object
objDB=newDBHandler(this);
//Set Design of Activity
setContentView(R.layout.student_list);
//Controls to be populated in List
int[] to = newint[]{R.id.text1};
//List of student which will be populated as a result of fetch
operation on DB
ListstdList=newArrayList<String>();
//List Population
stdList=objDB.getData();
//Get Reference of the ListView from the Design
listStudent=(ListView)findViewById(R.id.listStudent);
20. //Prepare a list of Key Value Pair Hash to populate the ListView
List<Map<String,Object>> list=newArrayList<
Map<String,Object>>(stdList.size());
//For loop to get each instance from student list and put it into
Hash list which will be used to populate ListView
for(int i=0; i<stdList.size(); i++){
Map<String,Object> map = newHashMap<String,Object>();
map.put("Name", stdList.get(i));
list.add(map);
}
//Set adapter to the ListView with control to be populated , Cell
Layout and list of data
listStudent.setAdapter(newSimpleAdapter(this,list,R.layout.student_row,
new String[] { "Name"}, to));
Now Add this Activity to your AndroidManifest.xml file.
Add Code to start this activity in the OnClick Method for Back Button in
Student Detail Activity.
Intent i=newIntent(this,StudentList.class);
startActivity(i);
Now Run your Application.