Android Sol 11
Android Sol 11
Long questions:
1. Prescribe the complete solution of creating
foreign key constraints in code?
For example, given an orders table and a customers table, if you create a
column orders.customer_id that references the customers.id primary key:
Referenced Columns
Referenced columns must contain only unique sets of values. This means
the REFERENCES clause must use exactly the same columns as
a UNIQUE or PRIMARY KEY constraint on the referenced table. For example,
the clause REFERENCES tbl (C, D) requires tbl to have either the
constraint UNIQUE (C, D) or PRIMARY KEY (C, D). New in v21.2: The order of the
columns in the foreign key definition does not need to match the order of
the columns in the corresponding UNIQUE or PRIMARY KEY constraint.
Null values
The write contains null values for all foreign key columns (if MATCH FULL is
specified).
The write contains null values for at least one foreign key column
(if MATCH SIMPLE is specified).
For more information about composite foreign keys, see the composite
foreign key matching section.
Note that allowing null values in either your foreign key or referenced
columns can degrade their referential integrity, since any key with a null
value is never checked against the referenced table. To avoid this, you
can use a NOT NULL constraint on foreign keys when creating your tables.
Note:
A NOT NULL constraint cannot be added to existing tables.
All composite key matches defined prior to version 19.1 use the MATCH
SIMPLE comparison method. If you had a composite foreign key constraint
and have just upgraded to version 19.1, then please check that MATCH
SIMPLE works for your schema and consider replacing that foreign key
constraint with a MATCH FULL one.
How it works
Valid: Keys that can be used for matching foreign key relationships.
Invalid: Keys that will not be used for matching (including for any
cascading operations).
Unacceptable: Keys that cannot be inserted at all (an error is
signalled).
Note:
CockroachDB does not support MATCH PARTIAL . For more information, see
issue
When you set a foreign key constraint, you can control what happens to
the constrained column when the column it's referencing (the foreign key)
is deleted or updated.
Parameter Description
Default action. If there are any existing references to the key being deleted, the
transaction will fail at the end of the statement. The key can be updated,
ON DELETE NO ACTION depending on the ON UPDATE action.
Default action. If there are any existing references to the key being updated, the
transaction will fail at the end of the statement. The key can be deleted,
ON UPDATE NO ACTION depending on the ON DELETE action.
ON DELETE RESTRICT and NO ACTION are currently equivalent until options for deferring
RESTRICT / ON UPDATE constraint checking are added. To set an existing foreign key action
RESTRICT to RESTRICT, the foreign key constraint must be dropped and recreated.
When a referenced foreign key is deleted or updated, all rows referencing that
key are deleted or updated, respectively. If there are other alterations to the
ON DELETE
row, such as a SET NULL or SET DEFAULT, the delete will take precedence.
CASCADE / ON UPDATE
CASCADE
Note that CASCADE does not list objects it drops or updates, so it should be used
cautiously.
ON DELETE SET When a referenced foreign key is deleted or updated, respectively, the columns
NULL / ON UPDATE SET of all rows referencing that key will be set to NULL. The column must
NULL allow NULL or this update will fail.
Parameter Description
When a referenced foreign key is deleted or updated, the columns of all rows
referencing that key are set to the default value for that column.
ON DELETE SET
DEFAULT / ON UPDATE If the default value for the column is null, or if no default value is provided and
SET DEFAULT the column does not have a NOT NULL constraint, this will have the same effect
as ON DELETE SET NULL or ON UPDATE SET NULL. The default value must still
conform with all other constraints, such as UNIQUE.
This functionality is available within dbForge Studio for SQL Server, a mighty tool
that comprises a pack of features to boost your SQL coding and tune performance.
Among them is a Query Builder feature. Its purpose is to eliminate any difficulties
that occur in the process of SQL query making and make query management as fast
and simple as possible.
Query Builder helps you view the structure of a query and allows you to design even
the most complex queries via a simple drag-and-drop and a few mouse clicks. With
its help, you can perform multiple joins and combine several queries to a sub-query
without much effort.
Just as you start making a subquery or open it for editing, you are sent to a subquery
tab of the query document. By means of these tabs, you can move across different
subqueries very easily. You can create a subquery by right-clicking the diagram body
and selecting Create Subquery command from the shortcut menu.
If you place a table with a foreign key and a table it references into the diagram area
of the query builder, joins are performed automatically. However, if you want to add a
join, you need to go to the Joins tab of the tabbed editor and click Add in the upper
area of the tree node. You will see a new join where you can insert a new condition.
You need to click the Enter table name field and indicate the tables. After that, you
can choose the join type. To do that, click the red-colored text link and select the
appropriate item from the shortcut menu. On the same menu, you can click to
remove a join.
The tool provides an intuitive interface allowing you to easily construct WHERE and
HAVING clauses. Just navigate to the corresponding tabs of dbForge Studio for SQL
Server and introduce the appropriate modifications.
In dbForge Studio, you can create these types of clauses in practically no time. Move
to the corresponding tabs of the program and select the columns for sorting or
grouping.
Step 7. View and execute the query
As soon as you finished introducing the required modifications, you can switch to the
Text view to check the final SQL code of your query. If you feel content with the
result, you can run the script by clicking Execute on the main toolbar of the tool.
Besides, you can manipulate the result-set depending on your needs within a handy
Data Editor functionality.
Advantages of Serialization
1. To save/persist state of an object.
2. To travel an object across a network.
// Default constructor
public Demo(int a, String b)
{
this.a = a;
this.b = b;
}
class Test
{
public static void main(String[] args)
{
Demo object = new Demo(1, "geeksforgeeks");
String filename = "file.ser";
// Serialization
try
{
//Saving of object in a file
FileOutputStream file = new FileOutputStream(filename);
ObjectOutputStream out = new ObjectOutputStream(file);
out.close();
file.close();
catch(IOException ex)
{
System.out.println("IOException is caught");
}
Demo object1 = null;
// Deserialization
try
{
// Reading the object from a file
FileInputStream file = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(file);
in.close();
file.close();
catch(IOException ex)
{
System.out.println("IOException is caught");
}
catch(ClassNotFoundException ex)
{
System.out.println("ClassNotFoundException is caught");
}
}
}
Output :
Object has been serialized
Object has been deserialized
a = 1
b = geeksforgeeks
4. Write the complete working code for the
following interface?
Small Businesses are just as at risk from cyber security threats
as large enterprises. A common misconception for small
businesses is an idea of security through obscurity, that your
business is too small to be a target, but unfortunately, this is not
the case.
As attackers increasingly automate attacks, it’s easy for them to
target hundreds, if not thousands of small businesses at once.
Small businesses often have less stringent technological
defences, less awareness of threats and less time and resource
to put into cybersecurity. This makes them an easier target for
hackers than bigger organizations.
But, at the same time, they are no less lucrative targets. Even
the very smallest businesses can deal with large sums of
money, or have access to huge amounts of customer data,
which, under regulations such as GDPR, they are obligated to
protect. Small businesses also often work with larger
companies, and so they can be used by hackers as a way to
target those companies.
Small businesses also arguably have the most to lose from
being hit with a damaging cyber-attack. A recent report revealed
that businesses with less than 500 employees lose on average
$2.5 million per attack. Losing this amount of money in a cyber
breach is devastating to small businesses, and that’s not to
mention the reputational damage that comes from being hit by a
cyber-attack.
For these reasons, small businesses need to be aware of the
threats and how to stop them. This article will cover the top 5
security threats facing businesses, and how organizations can
protect themselves against them.
1) Phishing Attacks
The biggest, most damaging and most widespread threat facing
small businesses are phishing attacks. Phishing accounts
for 90% of all breaches that organizations face, they’ve grown
65% over the last year, and they account for over $12 billion in
business losses. Phishing attacks occur when an attacker
pretends to be a trusted contact, and entices a user to click a
malicious link, download a malicious file, or give them access to
sensitive information, account details or credentials.
Phishing attacks have grown much more sophisticated in recent
years, with attackers becoming more convincing in pretending to
be legitimate business contacts. There has also been a rise in
Business Email Compromise, which involves bad actors using
phishing campagins to steal business email account passwords
from high level executives, and then using these accounts to
fraudulently request payments from employees.
Part of what makes phishing attacks so damaging is that they’re
very difficult to combat. They use social engineering to target
humans within a business, rather than targeting technological
weaknesses. However, there are technological defences against
phishing attacks.
Having a strong Email Security Gateway like Proofpoint
Essentials, or Mimecast, in place can prevent phishing emails
from reaching your employees inboxes. Post-Delivery
Protection such as IRONSCALES are also crucial to secure your
business from phishing attacks. These solutions allow users to
report phishing emails, and then allow admins to delete them
from all user inboxes.
The final layer of security to protect emails from phishing attacks
is Security Awareness Training. These solutions allow you to
protect your employees by testing and training them to spot
phishing attacks and report them.
You can read verified user reviews of the top Email Security
Gateways, Post-Delivery Protection Solutions and Security
Awareness Training Platforms at Expert Insights.
2) Malware Attacks
Malware is the second big threat facing small businesses. It
encompasses a variety of cyber threats such as trojans and
viruses. Malware is a varied term for malicious code that
hackers create to gain access to networks, steal data, or destroy
data on computers. Malware usually comes from malicious
website downloads, spam emails or from connecting to other
infected machines or devices.
These attacks are particularly damaging for small businesses
because they can cripple devices, which requires expensive
repairs or replacements to fix. They can also give attackers a
back door to access data, which can put customers and
employees at risk. Small businesses are more likely to employ
people who use their own devices for work, as it helps to save
time and cost. This, however, increases their likelihood of
suffering from a malware attack, as personal devices are much
more likely to be at risk from malicious downloads.
Business can prevent malware attacks by having strong
technological defences in place. Endpoint Protection solutions
protect devices from malware downloads and give admins a
central control panel to manage devices and ensure all users’
security is up to date. Web Security is also important, stopping
users from visiting malicious webpages and downloading
malicious software.
You can read verified user reviews of the top Endpoint
Protection and Web Security vendors at Expert Insights.
3) Ransomware
Ransomware is one of the most common cyber-attacks, hitting
thousands of businesses every year. They’ve grown more
common recently, as they are one of the most lucrative forms of
attacks. Ransomware involves encrypting company data so that
it cannot be used or accessed, and then forcing the company to
pay a ransom to unlock the data. This leaves businesses with a
tough choice – to pay the ransom and potentially lose huge
sums of money, or cripple their services with a loss of data.
Small businesses are especially at risk from these types of
attack. In 2021, 71% of ransomware attacks targeted small
businesses, with an average ransom demand of $116,000.
Attackers know that smaller businesses are much more likely to
pay a ransom, as their data is often not backed-up and they
need to be up and running as soon as possible. The healthcare
sector is particularly badly hit by this type of attack, as locking
patient medical records and appointment times can damage a
business to a point where it has no choice but to close, unless a
ransom has been paid.
To prevent these attacks, businesses need to have
strong Endpoint Protection in place across all business devices.
These will help to stop ransomware attacks from being able to
effectively encrypt data. Endpoint protection solution
SentinelOne even provides a ‘ransomware rollback’ feature,
which allows organizations to very quickly detect and mitigate
against ransomware attacks.
Businesses should also consider having an effective cloud back-
up solution in place. These solutions back up company data
securely in the cloud, helping to mitigate against data loss.
There are various methods of data back-up available to
organizations, so it’s important to research the method that will
work best for your organization.
The benefit of implementing data back-up and recovery is that in
the event of a ransomware attack organizations can quickly
recover their data without having to pay any ransoms, or lose
productivity. This is an important step towards improved cyber-
reselience.
4) Weak Passwords
Another big threat facing small businesses is employees using
weak or easily guessed passwords. Many small businesses use
multiple cloud based services, that require different accounts.
These services often can contain sensitive data and financial
information. Using easily guessed passwords, or using the same
passwords for multiple accounts, can cause this data to become
compromised.
Small businesses are often at risk from compromises that come
from employees using weak passwords, due to an overall lack of
awareness about the damage they can cause. An average of
19% of enterprise professionals use easily guessed passwords
or share passwords across accounts according to a
recent report.
To ensure that employees are using strong passwords, users
should consider Business Password Management technologies.
These platforms help employees to manage passwords for all
their accounts, suggesting strong passwords that cannot be
easily cracked. Businesses should also consider implementing
Multi-Factor Authentication technologies. These ensure that
users need more than just a password to have access to
business accounts. This includes having multiple verification
steps, such as a passcode sent to a mobile device. These
security controls help to prevent attackers from accessing
business accounts, even if they do correctly guess a password.
You can read verified user reviews of the top Business
Password Management and the top Multi-Factor
Authentication solutions at Expert Insights.
5) Insider Threats
The final major threat facing small businesses is the insider
threat. An insider threat is a risk to an organization that is
caused by the actions of employees, former employees,
business contractors or associates. These actors can access
critical data about your company, and they can case harmful
effects through greed or malice, or simply through ignorance and
carelessness. Verizon recently found that 25% of data
breaches were caused by insider threats.
This is a growing problem and can put employees and
customers at risk, or cause the company financial damage.
Within small businesses, insider threats are growing as more
employees have access to multiple accounts, that hold more
data. Research has found that 62% of employees have reported
having access to accounts that they probably didn’t need to.
To block insider threats, small businesses need to ensure that
they have a strong culture of security awareness within their
organization. This will help to stop insider threats caused by
ignorance, and help employees to spot early on when an
attacker has compromised, or is attempting to compromise
company data.
You can read verified user reviews of all of the top Security
Awareness Training solutions at Expert Insights.
Summary
There are a range of threats facing small businesses at the
moment. The best way for businesses to protect against these
threats is to have a comprehensive set of security tools in place,
and to utilize Security Awareness Training to ensure that users
are aware of security threats and how to prevent them.
Expert Insights is a leading resource to help organizations find
the right security software and services. You can read verified
user reviews of all of the top security solutions and discover the
top features of each service. Get started by
visiting www.expertinsights.com/services
1. What difference between the .NET framework 2.0 and .NET compact
framework 2.0?
In general, the .NET Compact Framework is a subset of the full .NET
Framework. The .NET Compact Framework supports about 30 percent of
the namespaces and classes of the full .NET Framework, and is about 8
percent of its size. To keep the size small, only the most important classes
and members are supported. The .NET Compact Framework also contains
some features and classes that are specific to mobile and embedded
development.
2. What is DotNet framework?
The .NET Framework is a software framework developed by Microsoft that runs
primarily on Microsoft Windows. It includes a large class library called
Framework Class Library and provides language interoperability across several
programming languages
3. What is role of CLR?
The main function of Common Language Runtime (CLR) is to convert the
Managed Code into native code and then execute the Program. ... In addition
to executing code, CLR provides services such as memory management, thread
management, security management, code verification, compilation, and other
system services.
4. Which database is used for Microsoft mobiles?
Most of the time in Android uses the SQLite as a mobile database technology.
SQLite is a relational database that is used in various embedded on iOS and android
platforms.
5. What is the role of to string() method?
The to String () method returns the String representation of the object. If you
print any object, Java compiler internally invokes the to String() method on the
object. So overriding the to String () method, returns the desired output, it can be
the state of an object etc.
6. What is the purpose of data set class?
Dataset class contains records of multiple tables, and also represents an in-
memory collection of data retrieved from a data source. The data in the Dataset
can be edited programmatically. Dataset objects allow the users to access rows
using the index of the table collection.
7. What is the purpose of sqlCecommand?
A SqlCommand object allows you to query and send commands to a
database. It has methods that are specialized for different commands. The
Execute Reader method returns a SqlDataReader object for viewing the results
of a select query. For insert, update, and delete SQL commands, you use the
ExecuteNonQuery method.
8. What is serialization?
Serialization is the process of converting an object into a stream of bytes to store
the object or transmit it to memory, a database, or a file.
9. What is socket programming?
Socket programming is a means of communicating data between two
computers across a network. Connections can be made using either a
connection-oriented protocol or a connectionless protocol. ... Client and server
communicate by writing to and reading from the socket connection.
10. What are types of assemblies in DotNet?
In .Net 3 types of Assemblies are available:
Private Assemblies: Private Assemblies are designed to be used
by one
Application and...
Shared Assemblies: Microsoft offers the shared assembly for
those
Components that must. ...
Satellite Assembly: A satellite Assembly is defined as an
assembly with Resources only, no.
Internet Information Services (IIS) is a flexible, general-purpose web server from Microsoft
that runs on Windows systems to serve requested HTML pages or files.
An IIS web server accepts requests from remote client computers and returns the appropriate
response. This basic functionality allows web servers to share and deliver information across
local area networks (LAN), such as corporate intranets, and wide area networks (WAN), such
as the Internet.
1. import java.security.NoSuchAlgorithmException;
2. import java.security.MessageDigest;
3.
4. public class PassEncTech1
5. {
6. /* Driver Code */
7. public static void main(String[] args)
8. {
9. /* Plain-text password initialization. */
10. String password = "myPassword";
11. String encryptedpassword = null;
12. try
13. {
14. /* MessageDigest instance for MD5. */
15. MessageDigest m = MessageDigest.getInstance("MD5");
16.
17. /* Add plain-text password bytes to digest using MD5 update
() method. */
18. m.update(password.getBytes());
19.
20. /* Convert the hash value into bytes */
21. byte[] bytes = m.digest();
22.
23. /* The bytes array has bytes in decimal form. Converting it in
to hexadecimal format. */
24. StringBuilder s = new StringBuilder();
25. for(int i=0; i< bytes.length ;i++)
26. {
27. s.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).s
ubstring(1));
28. }
29.
30. /* Complete hashed password in hexadecimal format */
31. encryptedpassword = s.toString();
32. }
33. catch (NoSuchAlgorithmException e)
34. {
35. e.printStackTrace();
36. }
37.
38. /* Display the unencrypted and encrypted passwords. */
39. System.out.println("Plain-text password: " + password);
40. System.out.println("Encrypted password using MD5: " + encryp
tedpassword);
41. }
42. }
Output:
public Task(String s)
{
name = s;
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
public class Test
{
// Maximum number of threads in thread pool
static final int MAX_T = 3;
Long question:
1. Write java code that display a dialog
window using an activity?
y.
Add a button in activity_main.xml file,
1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
2. xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
3. android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_mar
gin"
4. android:paddingRight="@dimen/activity_horizontal_margin"
5. android:paddingTop="@dimen/activity_vertical_margin"
6. android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
7.
8. <Button
9. android:id="@+id/btnDialog"
10. android:layout_width="fill_parent"
11. android:layout_height="wrap_content"
12. android:text="click to display a dialog"
13. android:onClick="onClick"
14. />
15.
16. </LinearLayout>
In MainActivity.java class, add an array,
1. CharSequence[] items={"Wipro", "IBM", "TCS"};
2. boolean[] itemChecked = new boolean [items.length];
To create a dialog window, override the onCreateDialog() protected method
which is defined in the
Activity base class.
1. protected Dialog onCreateDialog(int id){
2. switch(id) {
3. case 0:
4. return new AlertDialog.Builder(this)
5. .setIcon(R.drawable.i1)
6. .setTitle("This is a simple dialog!")
7. .setPositiveButton("OK",
8. new DialogInterface.OnClickListener() {
9. @Override
10. public void onClick(DialogInterface dialogInterface, int i) {
11. Toast.makeText(getBaseContext(), "OK clicked!", Toast.LENGTH_SHORT).sh
ow();
12. }
13. }
14. )
15. .setNegativeButton("Cancel",
16. new DialogInterface.OnClickListener() {
17. @Override
18. public void onClick(DialogInterface dialogInterface, int i) {
19. Toast.makeText(getBaseContext(), "Cancel clicked!", Toast.LENGTH_SHORT)
.show();
20. }
21. }
22. )
23. .setMultiChoiceItems(items, itemChecked,
24. new DialogInterface.OnMultiChoiceClickListener() {
25. @Override
26. public void onClick(DialogInterface dialogInterface, int i, boolean b) {
27. Toast.makeText(getBaseContext(),items[i]+ (b?" is checked":" is unchecked"
),Toast.LENGTH_SHORT).show();
28. }
29. }
30.
31. ).create();
32. }
33. return null;
34. }
Below method is called when you call the showDialog() method.
1. public void onClick(View v)
2. {
3. showDialog(0);
4. }
The onCreateDialog () method is a call back for creating dialogs that are managed
by the activity. When show Dialog () method is called, this call back
onCreateDialog () method is invoked. The show Dialog () method accepts an
integer as an argument to display a particular dialog. We have used a switch
statement to identify the different types of dialogs to create. To create a dialog,
Alert Dialog class, Builder constructor is used.
In the above code, OK and Cancel are sets using the setPositionButton () and
setNegativeButton (). A user has the option to select multiple options by using
the setMultipleChioceItems () method. When an option is checked or unchecked
by the user, he/she gets the message that the selected option is checked or
unchecked
Service:
Being a background process the service can run for a long
time.
The local and remote are the two types of services. Within
the application, the local service is
accessed. While from other applications running on the
same device the remote service can be
accessed remotely.
Content Provider:
To share the data between the applications, the Content
Providers are used.
Fragment:
Being a part of an activity, one or more fragments can be
displayed on the screen at the same
time by the activity.
AndroidManifest.xml:
Information about activities, content providers, permissions,
etc is in the AndroidManifest.xml
which is like the web.xml file in Java EE.
Android Virtual Device (AVD):
To test an android application without using a mobile or a
tablet, the Android Virtual Device or
AVD is used. To emulate different types of real devices, an
AVD can be created in different configurations.
Multi-touch
Android has native support for multi-
7 touch which was initially made
available in handsets
such as the HTC Hero.
8 Multi-tasking
User can jump from one task to
another and same time various
application can run
simultaneously.
Resizable widgets
Widgets are resizable, so users can
9 expand them to show more content
or shrink them to save
space.
Multi-Language
10 Supports single direction and bi-
directional text.
GCM
Google Cloud Messaging (GCM) is a
service that lets developers send
11 short message data to
their users on Android devices,
without needing a proprietary sync
solution.
Wi-Fi Direct
A technology that lets apps discover
12 and pair directly, over a high-
bandwidth peer-to-peer
connection.
Android Beam
A popular NFC-based technology that
13 lets users instantly share, just by
touching two NFC
enabled phones together.
You can include this information in two different ways: Specify a KeyStore
file using the --ks option. Specify the private key file and certificate file
separately using the --key and --cert options, respectively. The private key
file must use the PKCS #8 format, and the certificate file must use the X.
16. What is android?
Android is a mobile/desktop operating system based on a modified version of the Linux
kernel and other open source software, designed primarily for touchscreen mobile devices
such as smartphones and tablets.
Long questions:
1. Discuss components of screen and
adapting to display orientation?
UNDERSTANDING THE COMPONENTS OF A SCREEN
An activity displays the user interface of your application, which may contain
widgets such as buttons,
labels, textboxes, and so on. Typically, you define your UI using an XML fi le (e.g.,
the main.xml
file located in the res/layout folder of your project), which looks similar to the
following:
<?xml version=”1.0” encoding=”utf-8”?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
Views and ViewGroups
An activity contains views and ViewGroups. A view is a widget that has an
appearance on screen.
Examples of views are buttons, labels, and textboxes. A view derives from the
base class android
.view.View.
android:orientation=”vertical” >
<TextView
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”@string/hello” />
</LinearLayout>
During runtime, you load the XML UI in the onCreate() method handler in your
Activity class,
using the setContentView() method of the Activity class:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
During compilation, each element in the XML file is compiled into its equivalent
Android GUI class,
with attributes represented by methods. The Android system then creates the UI
of the activity when
it is loaded.
you can order the appearance and sequence of views.
Examples of ViewGroups include LinearLayout and FrameLayout. A ViewGroup
derives from the
base class android.view.ViewGroup.
Android supports the following ViewGroups:
➤ LinearLayout
➤ AbsoluteLayout
➤ TableLayout
➤ RelativeLayout
➤ FrameLayout
➤ ScrollView
The following sections describe each of these ViewGroups in more detail. Note
that in practice it is
common to combine different types of layouts to create the UI you want.
LinearLayout
The LinearLayout arranges views in a single column or a single row. Child views can
be arranged
either vertically or horizontally. To see how LinearLayout works, consider the
following elements
typically contained in the main.xml file:
<?xml version=”1.0” encoding=”utf-8”?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:orientation=”vertical” >
<TextView
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”@string/hello” />
</LinearLayout>
In the main.xml file, observe that the root element is <LinearLayout> and it has a
<TextView>
element contained within it. The <LinearLayout> element controls the order in
which the views
contained within it appear.
Android defines and recognizes four screen densities:
➤ Low density (ldpi) — 120 dpi
➤ Medium density (mdpi) — 160 dpi
➤ High density (hdpi) — 240 dpi
➤ Extra High density (xhdpi) — 320 dpi
AbsoluteLayout
The AbsoluteLayout enables you to specify the exact location of its children.
TableLayout
The TableLayout groups views into rows and columns. You use the <TableRow>
element to designate
a row in the table. Each row can contain one or more views. Each view you place
within a row forms
a cell. The width of each column is determined by the largest width of each cell in
that column.
RelativeLayout
The RelativeLayout enables you to specify how child views are positioned relative
to each other.
FrameLayout
The FrameLayout is a placeholder on screen that you can use to display a single
view. Views that you add to a FrameLayout are always anchored to the top left of
the layout.
ScrollView
A ScrollView is a special type of FrameLayout in that it enables users to scroll
through a list of
views that occupy more space than the physical display. The ScrollView can
contain only one child
view or ViewGroup, which normally is a LinearLayout.