Download as pdf or txt
Download as pdf or txt
You are on page 1of 31

I.

Definitions:

1. Android operating system:


• It is a powerful mobile operating system by Google and designed for
smartphones and tablets.
• It is continually updated, improved, and extended.

2. Layout file:
• It is an xml file that contains the xml used to create the objects and
controls that the user can interact with.
User Interface
3. RelativeLayout:
• It’s the default layout, which designs the UI components as relative to
one another rather than designing them as a fixed position.

4. “match_parent” value:
• It indicates that the layout should be the height and width of the device
screen. ‫يكون مناسب لحجم شاشة الجوال‬
• If a child element of RelativeLayout has this value for either
layout_height or layout_width, it will fill up as much of the
RelativeLayout as it can.

5. “wrap_content” value:
• It tells Android to size the View to the size of the text displayed in it.
‫على حسب الكلمة يتغير حجم االيقونه‬

6. “package” keyword:
• It identifies that this class belongs to a certain package for example
“com.example.helloworld”. \
• All source Java files in the same app will have this entry as the first code
in the file.

7. “import” keyword:
• It’s used to get the source code needed for your activity.
8. Bundle:
• It is an object for passing data between activities.
• In this way we can have an application that can perform some activity
based on what another activity has done or the data it has used.
• The Bundle also enables the activity to store its current state just before it
is destroyed (by rotation) and passes that data back to the activity when
it’s re-created (in the new orientation).

9. The “onCreate (..)” method:


• It is the first method executed by the Activity when it is started.
• It takes savedInstanceState of type Bundle as a parameter.
• The super.onCreate calls the super class’s onCreate method. Because
this method is overriding the Activity class’s inherited onCreate
method, it must call that method explicitly to use that functionality to
create the Activity.
• The setContentView(R.layout.activity_hello_world ) tells the
activity to use the activity_hello_world.xml file as the layout to be
displayed when the activity is running.

10. The onCreateOptionsMenu(Menu menu) method:


• This method is called when the user clicks the device’s Menu button.
• It returns a Boolean (true or false) value indicating whether the menu
was successfully created.
• The first line of code ( getMenuInflator() ) gets an object that can
create a menu from the running activity.
• It then tells it to inflate (create) a visual representation of the menu
based on the main.xml file in the menu resource folder and refer to it
with the name “menu”.

II. Main advantages of Android Studio:


• Instant Run:
o Shows the effects of code changes immediately without restarting the
app.

• Intelligent code editor:


o Advanced code completion, refactoring, and code analysis.

• Robust and flexible build system.


o Automated build and dependency management, and customized build
configurations.

• Designed for teams:


o Integrates with version control tools, such as GitHub.

• Optimized for all android devices


o Unified environment to develop apps for phones, TV, tablets…etc.

III. What are the components of the Package Explorer?


• Manifest folder:
o Configures all important information when the app is installed.

• Java folder:
o Contains all the java code files such as activities, classes ...etc.

• Resources folder (res folder): contains the following folders:


o Drawable folder:
Contains all image files of the app.

o Layout folder:
Contains all user interfaces of the app as .XML files.
o Mipmap folder: contains the icons of the app launcher (the icon of the
home screen which you click to open the app).

o Values folder:
Contains the xml files that limit the hard-coding throughout the
app.

1. Dimens.xml:
Values of the display size of items in layouts.

2. Color.xml:
Values of the colors used in the app.

3. String.xml:
Contains string values.

4. Array.xml:
Where the string arrays can be defined.

5. Ids.xml:
IDs that can’t be reused in layouts.

IV. What are the main elements of the Manifest file?

o The <manifest> component is the root element. The attributes associated


with this element define the application package, version code, and version
name & others.
• The Version Code:
It’s an integer value used to indicate there is a new version of
the app available.
Increasing value enables the Play Store to notify users of the
app that a new version is available.
It also controls the install of the upgrade so that no user data is
lost during an upgrade.

• The Version Name is the displayed version of your app.

• The java package of the application. It serves as a unique identifier for


the app.

o The <uses-sdk> element and its attributes define the minimum and target
SDKs for the app.

o The <application> element has both attributes and child elements that
configures how the app works. Application attributes in this manifest define
the app icon, theme, and label (name). Each activity in an app must have an
entry in the <application> element.

o The <activity> element tells the operating system that an activity has
permission to run in your application.

• All activities used in an app must be defined in the manifest.


• The Java source file for the activity and the activity’s title are
identified.

o The <intent-filter> element, a child element of the <activity> element.

• It defines what the Android OS should do with this activity.


• It needs to be added in the first activity to launch when a user opens
the app.
• The <action> tag identifies the activity as the main or first activity to
run.

o The <category> tag tells the OS to use the app launcher to start this activity.
I. Definitions:
1. Activity class:
• A class designed to handle a single task that the user can perform.
• The Activity class is not directly instantiated in an Android app.
Rather, each activity we create is a sub-class (inherited) of it.
• This way developers can inherit all the functionality of the Activity
class in addition to adding their own unique functionality through Java
code.
• One of the most important inherited functions of the Activity class is
the capability to respond to life cycle events such as onCreate() and
onPause().
• The Activity subclasses developed by the user are stored as .java files
in the app project’s java folder.

2. Layout:
• A layout is the visual component of a user interface in Android.
• The layout is an xml file that is used to tell the operating system what
visual objects are to be displayed, how they are configured, and where
they should be displayed.
• Layouts can also be defined at runtime by instantiating the widgets
that make up an interface and configuring them as needed.

3. Widget:
• The objects that make up an Android interface.
• Widgets are subclasses of the View class.
• Android widgets include:
o Widgets to define where other widgets are displayed (for
example, RelativeLayout)
o Widgets to directly interact with the user (for example,
RadioButton)
o Widgets to provide some type of navigation within the
interfaces (for example, ScrollView).
4. Intent:
• An Intent is a class that is used to describe an operation to be
performed.
• An intent is essentially a message that defines an action to be taken
and the data that the action is to be performed on.
• Intents are the primary way in which the developer starts new
activities within the app.
• Intents can also be used to communicate between activities.
• Intents can be used to start activities or broadcast both within and
outside the app to provide instructions and data to other activities.

II. Mention two of the subclasses of the Activity class.


1. FragmentActivity subclass :
• Fragments allow the developer to include multiple tasks or panes
within a single activity.
• This class is also used to make an app backward compatible to OS
versions earlier than 11.

2. ListActivity subclass:
• Designed to specifically support the development of a list
interface.

III. Write a piece of code that does the transaction between Activity1 to
Actrivity2.

Intent i = new Intent ( Activity1.this, Activity2.class );


startActivity ( i );

IV. Write a piece of code to link a button in the layout that has an id of (
btnSave ) to java code.

Button button = ( Button ) findViewById ( R.id.btnSave );

V. Write a piece of code of a button b1 that when is clicked, it switches the


current activity MainActivity to another activity called MainActivity2.
Button b1 = ( Button ) findViewById ( R.id.b1 );
b1.setOnClickListener (new View.OnClickListener ( ) {
public void onClick (View v ){
Intent i = new Intent ( MainActivity.this,
MainActivity2.class );
startActivity ( i );
}
});
I. Definitions:
1. Shared preferences:
• Preferences are implemented through use of the
SharedPreferences class.

• A SharedPreferences object can be used to store primitive data


(for example, integers and strings) in a key/value pair.

• Each value has its own key for storage and retrieval of that data.

• SharedPreferences are stored in memory private to the app and


will persist as long as the app remains installed on the device.

• App upgrades will not impact the values stored with


SharedPreferences.

• Used for a limited set of data that represent user choices about
app configuration or other data that needs to persist across life
cycle changes.

2. Files:
• Written and read as a stream of bytes.

• Files written to internal storage are private to the app.

• Files written to external storage (such as an SD card) can be


accessed and modified by other apps or the users of any
connected devices (such as a computer).

• Can be written and read from storage using the


FileOutputStream and FileInputStream.

• useful for backing up data and transmitting to other users

• To the Android system, a file is one thing as it does not have


parts, such as different objects, within it.
• Advantage:
o The system stores the data efficiently and does not have to
worry about what data is stored within the stream.

o Many kinds of data can be stored in a file.

• Disadvantage:
o The developer will have to code the reading and writing
of the file so that the data can be used appropriately when
it is needed.

o For example, embedding XML in the stream to identify


the different types of data, or embedding commas in the
file to distinguish different pieces of data (in either case,
the user of that file must know its structure to use it
correctly).

3. Database:
• Android supports the use of SQLite databases.

• SQLite is a fully functional relational database management


system (RDBMS) that can integrate into any host application.

• A relational database system allows the developer to give


meaning to the data stored within it by separating the data into
tables.

• SQLite also provides capabilities for retrieval and manipulation


of the stored data through the use of queries written in
Structured Query Language (SQL).

• Almost any type of data can be stored and manipulated using a


SQLite database, although some data types have more limited
support than other RDBMSs.
• SQLite does not require an independent server process to
execute.

• Data stored in a SQLite database is private to the app and will


persist as long as the app is installed on the device.

• An app may create and use multiple databases, and each


database can have many tables, making data storage via SQLite
both extensive and flexible.

4. Cursor:
• A cursor is an object that is used to hold and move through the
results of a query.

II. What are the main modes for accessing SharedPreferences?

• getSharedPreferences ("String preference name", integer mode):


o This mode is used when you want to have more than one set of
preferences for an app, or you want the preferences available to
any Activity in the app.

o Each set is given a name that is used as the key to access that
particular set of preferences.

• getPreferences(integer mode):
o This is used if you need a set of preferences only for a single
activity.

Note that: with each of these methods you need to set an access mode.
Using 0 (zero) makes the preferences private to the app or set a mode
that makes them readable or writeable from outside the app (opens
potential security holes).
III. Android and ios are not very different in terms of data persistence.
(Discuss).

• Android and ios offer essentially the same three types of data
persistence mechanisms.

• Although the concept is the same, but the coding and the name of the
persistence mechanisms may differ due to the different platforms.

Android ios
SharedPreferences. NSUserDefaults.
File input and output. File input and output.
SQLite database. SQLite database + Core Data
(object oriented database) built on
top of SQLite.

IV. What is the recommended practice to using SQLite in an Android app?

• The best practice is to create the following two classes:


o A DatabaseHelper class (inherited from the SQLiteOpenHelper
class) whose only function is to provide for the creation,
modification, and deletion of tables in the database as well as
for the upgrade of the database version.

o A DataSource class used for providing methods to open and


close the database and the queries used to store, access, and
manipulate the data in the tables.

V. When do the onCreate( ) and the onUpgrade( ) methods get executed in a


DatabaseHelper class?

• The onCreate method:


o Is called the first time the database is opened.
o If the database name variable does not exist, this method is
executed.

• The onUpgrade method:


o Every time the database is accessed, the existing database
version is compared to the one declared in the code.
o When the database is opened and the current version number in
the code is higher than the version number of the current
database the onUpgrade method is executed.

VI. What are the methods being auto-generated when we call a textWatcher
object to addTextChangedListener of editText?

• The afterTextChanged method:


o It’s a required method for the TextWatch object.
o It is called after the user completes editing the data and leaves
the EditText.
o This is the event used to capture the entered data once the user
ends editing.

• The beforeTextChanged method:


o It’s a required TextWatcher method. This method is executed
when the user presses down on a key to enter it into an EditText
but before the value in the EditText is actually changed.

• The onTextChanged method:


o It is also a required TextWatcher method.
o The method is executed after each and every character change
in an EditText.
VII. Write a method that adds a user (name, password) to a database.
public boolean addUser(String username, String password) {
boolean didSucceed = false ;
ContentValues values= new ContentValues();

values.put("name", username);
values.put("pass", password);

didSucceed = getWritableDatabase()
.insert ("users", null, values) > 0;

return didSucceed;
}
How to Code
1-Extend SQLiteOpenHelper
2-Name
private static final String
DATABASE_NAME = "mycontacts.db" ;
3-Version
private static final int
DATABASE_VERSION = 1; //3
4-Constructor
super (context, DATABASE_NAME , null ,
DATABASE_VERSION );
5-OnCreate
public void onCreate(SQLiteDatabase
database) {
database.execSQL(
CREATE_TABLE_CONTACT );
Create Databse }
6-OnUpgrade
public void onUpgrade(SQLiteDatabase
db, int oldVersion, int newVersion) {

Log.w(ContactDBHelper.class.getName(),
"Upgrading database from
version " + oldVersion + " to "
+ newVersion + ",
which will destroy all old data" );

db.execSQL( "DROP TABLE IF EXISTS


contact" );
onCreate(db);
}
I. Definitions:

1. Lists in android:
• There are two components required for any list implementation in
Android:
o ListView widget:
An object that can display a vertical list of items that can
be scrolled through.
It’s the visible component of a list which is implemented
in an xml layout file.
It has attributes that allow the user to configure some
aspects of the display.
If given the special ID of @id/android:list and a special
subclass of Activity (ListActivity), many of the tasks of
list implementation are easier because the developer can
take advantage of many built-in features of the SDK.

o Adapter:
Provides access to the underlying data source for the list.
An AdapterView is the super class that binds all the
views to the data source (such as database, arrays…etc.).

2. The BaseAdapter class:


• It’s an abstract class which is the super class of all adapters. It has
three subclasses:
o The ArrayAdapter
Used to bind an Array or ArrayList to a view.
An ArrayAdapter is always parameterized, which means
it must be told what kind of data it is going to bind to a
view (such as String, or more complex).

o The CursorAdapter
An abstract class that binds data from a database cursor
to a view.
It has a subclass named as SimpleCursorAdapter that is
used to map a row layout to fields in a cursor.
o The SimpleAdapter
Used to bind static data to a view.

II. What does method putExtra(key, value) in the Intent class do?
• The method putExtra(key, value) is used to put primitive data types in
the Intent so that they are accessible by the activity receiving the
intent.
• In other words, it’s used to transfer data between activities.
Week 2 questions:

1) Which of the following is NOT an advantage for small businesses in adopting


mobile technology compared to traditional computing platforms?
a) Less costly
b) Less complex
c) Easily available to all employees
d) Able to reduce the number of employees

2) When the user rotates the device


a) The app layout automatically reorganizes for that orientation.
b) The horizontal and vertical state remain the same because the device size
does not change.
c) The app remains in the running state.
d) The user experience is enhanced by more accessible screen elements.

3) The proper life cycle method to save app status is _____ in Android and _____
in iOS.
a) onPause, viewWillDisappear:
b) onResume, viewWillAppear:
c) onStopped, viewDidUnload:
d) onDestroy, applicationDidEnterBackground

4) Which of the following is NOT an important design consideration for the app
developer?
a) The app life cycle
b) Screen size
c) Connectivity problems
d) Programming language limitations
5) Draw Android Life Cycle

6) Draw ios view lifecycle.


7) True or false:

a) Mobile devices can increase customer loyalty and brand awareness (true).
b) Battery use is not a concern for all app developers (false).
Week 3 questions:
1. What’s an AVD?
a) component of the Android package used to configure the user’s device
b) A simulated device configuration for use with the emulator
c) A manager used to emulate alternative designs
d) A component of the Eclipse IDE used to update the Android SDK

2. Which of the following best describes an Activity?


a. An element of the app’s UI
b. An alternative name for a method in a Java class, used specifically by Android
c. A class that has the code to provide the functionality associated with a screen in an app
d. Any action taken by an Android app in response to a user selection

3. Which of the following is the correct attribute value to set the widget's width to match the
size of the widget or the data it contains?
a. match_content
b. wrap_content
c. fill_to_content
d. match_size

The manifest file configures the app and informs when the device is installed
(true).
What is the Three Main Files in Android App
a) Manifest
• The configurations file for an android app.
• One file AndroidManifest.xml.
• Contain (app name - app icon - interface side - backup - theme - main
activity - actions)
b) java
• All code of java write here in main java class (MainActivtiy)
c) res
• Contained all these files:
1) Drawable:
o Put it all images and graphic here you can create separate files.
2) layout
o A file that define the user interface for an activity.
o One file only (activity_main.xml)
3) mipmap
o Contain (ic_launcher.png - ic_launcher_round.png)
o Put here icon image for app we can put multiple size for deferent
screen.
Values:
1) Contain (color.xml - string.xml - styles.xml - dimens.xml)
o color.xml = Define every color we need in own app here.
<color name="colorAccent">#FF4081</color> // Only
change the name + color
o string.xml = Define name app here.
<string name="app_name">My Application</string> // just
change (My Application).
o styles.xml = Put here some style we use in deferent screen.
<item name="colorAccent">@color/colorAccent</item> //
just change color name in color.xml and put it here
o dimens.xml = Put it here multiple screen size.
Two File same name (dimen.xml) For Phone and Tablet
<dimen name="activity_vertical_margin">16dp</dimen>
<dimen name="activity_horzontal_margin">16dp</dimen>
// change size only.
<intent-filter> —> defined what the android OS should do to with activity.
<user-sdk> —> element for minimum and target SDK
Week 4 and 5 and 6 questions:
The different between Intent (Explicit/Implicit)?
Intent explicit —> use object class intent to make explicit call to activity inside our
application.
Intent implicit —>use object intent to make implicit call to activity outside our
application.

Which of the following best describes an Activity?


a) An element of the app’s UI
b) An alternative name for a method in a Java class, used specifically by
Android
c) A class that has the code to provide the functionality associated with a
screen in an app
d) Any action taken by an Android app in response to a user selection

Which of the following objects is used to start an Activity?


a) Task
b) Bundle
c) Intent
d) Launcher

Which of the following objects would be used to read a flat file in an Android app?
a) CharacterInputReader
b) ByteInputReader
c) InputStreamReader
d) FileInputStream

Which of the following best describes the function of the Database helper class?
a) To read and write data to a SQLite database
b) To provide methods to access the data in a SQLite database
c) To create and upgrade a SQLite database
d) To open and close a SQLite database

Which of the following is the correct code to advance the cursor one record in the
dataset?
a) cursor.move();
b) cursor.moveToNext() ;
c) cursor.step() ;
d) cursor.move(1);

The object used to make primitive bits of data persist across changes in the app life
cycle is the _____ object.
a) DatabaseHelper
b) SharedPreferences
c) OutputStream
d) Persistent

Write the code to declare ContactDBHelper and make it a subclass of


SQLiteOpenHelper.

public class ContactDBHelper extendsnSQLiteOpenHelper

Write the code to edit (save) a shared preferences as key value pair
(“Midterm_ID”, 123) .

getSharedPreferences("MyPref",MODE_PRIVATE ).edit().putString( " Midterm_ID "


, 123 ).commit();

SharedPreferences mypref;
mypref=getSharedPreferences("mypref",MODE_PRIVATE);
mypref.edit().putString("Midterm_ID",123).commit();
What is the difference between the getPreferences and getSharedPreference.
get preference can be used only in one activity
get shared preference can be used around the project activities

Write the code to send key value pair (“studentid”, 123456) from one activity to
another inside your app.
Intent intent = new Intent(Activity1.this, Activity2.class);
intent.putExtra("studentid", 123456);
startActivity(intent);

Which of the following best describes the function of database helper class?
a) To read and write data to SQLite database.
b) To provide methods to access the data in a SQLite database.
c) To create and upgrade a SQLite database.
d) To open and close a SQLite database

The database version number of SQLite database has no functional


implementations (false).
Which of the following IDs allows the developer to take advantage of built-in
features of the SDK for displaying data in a vertically scrollable form?
a) @id/android:list
b) @id/android:scrollableList
c) @+id/autoList
d) @+id/listView1

Which of the following is a subclass of BaseAdapter?


a) DatabaseAdapter
b) CursorAdapter
c) DataAdapter
d) DataListAdapter

What are the two components which are required for any list implementation in
Android? Provide brief explanation?
The two required components are: a ListView widget and an adapter.
• The ListView widget is an object that can display a vertical list of items that can
be scrolled through. An Adapter is dynamically associated with the ListView.
• The adapter provides access to the underlying data source for the list.

What are the main subclasses for the class BaseAdapter? Write names and brief
description of each.
• ArrayAdapter is used to bind an Array or ArrayList to a view.
• CursorAdapter is an abstract class that binds data from a database cursor to
a view.
• The SimpleAdapter class is used to bind static data to a view.

The BaseAdapter class has three subclasses, ArrayAdapter,


CursorAdapter, and SimpleAdapter.
android:id="@id/android:list"
setContentView(R.layout.activity_main);
ArrayList<String> arr = new ArrayList<String>();
arr.add(“a1234”);
arr.add(“b1234”);
arr.add(“c1234”);
arr.add(“d1234”);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, arr));

list view—> an xml layout to display list of an item on screen, recommend name
for listView is
AndroidList to support all functionally that build in SDK
adapter —> to link between source file and ListView. The super class for all
BaseAdapter.

Fill in blanks:
private void initDisplayButton()
{
Button displayButton = (Button) ……(1)…….(R. (2) .buttonDisplay);
displayButton.setOnClickListener(new OnClickListener ()
{
@ Override public void ….(3)….(View arg0)
{
EditText editName = (……..(4)......) ……(1)…… (R.id.editTextName);
TextView textDisplay = (TextView) …(1)… (R.id.textViewDisplay);
String nameToDisplay = editName.getText()……(5)……..;
}
});
}
Answers:

1 findViewbyid
2 id
3 onClick
4 EditText
5 toString()

You have two activities, as follows:

Activity 1 Activity 2

You will enter you name in the first activity. When you click on the send button,
the second activity will open showing your name. Complete the following methods
for both activities.
Solution:
public class activity1 extends AppCompatActivity {
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Button button1 = (Button) findViewById(R.id.button1);


button1.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
EditText edittext1 = (EditText) findViewById(R.id.editText1);
String x = edittext1.getText().toString();
Intent intent = new Intent(activity1.This,activity2.class);
intent.putExtra("username",x);
startActivity(intent);
} }); } }

public class activty2 extends AppCompatActivity {


@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textview2 = (TextView) findViewById(R.id.textview2);
Bundle extra = getIntent().getExtras();
String x = extra.getString("username");
textview2.setText(x); } }

Imagie the user wants to store the addition result in a shared preference object for
future use. Write the suitable code for storing the sum value in SharedPreferece.
Assume the preference set name is: “Results” and preference key is: “summation”.
Solution:
getSharedPreferences(“Results”,
MODE_PRIVATE).edit().putInt(“summation”, 12).commit();

You might also like