0% found this document useful (0 votes)
3 views49 pages

Android Sol 11

The document covers various concepts related to programming and database management, including tab control, docking and anchoring properties, error code enumerations, and foreign key constraints. It also discusses the creation of complex SQL queries, the phenomenon of multithreading, and the processes of serialization and deserialization of objects. Additionally, it outlines the stages of SOAP message processing and the components involved in SQL server replication.

Uploaded by

Ashi Ali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views49 pages

Android Sol 11

The document covers various concepts related to programming and database management, including tab control, docking and anchoring properties, error code enumerations, and foreign key constraints. It also discusses the creation of complex SQL queries, the phenomenon of multithreading, and the processes of serialization and deserialization of objects. Additionally, it outlines the stages of SOAP message processing and the components involved in SQL server replication.

Uploaded by

Ashi Ali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 49

BS 8th TERM 2017(CS)

1. What is the purpose of tab control?


Windows Tab Control is a useful control that allows you display multiple dialogs tabs on a
single form by switching between the tabs. A tab acts as another Form that can host other
controls. For example a Tab Control in Visual Studio. NET, which allows you to switch
among multiple files using the tabs.
2. What do you mean by docking and anchoring properties?
Anchor refers to the position a control has relative to the edges of the form. A textbox, for
example, that is anchored to the left edge of a form will stay in the same position as the form
is resized. Docking refers to how much space you want the control to take up on the form.
3. Which symbolic name is used to provide an enumeration for all the error codes?
Enumerations offer an easy way to work with sets of related constants. An enumeration,
or Enum, is a symbolic name for a set of values. Enumerations are treated as data types, and
you can use them to create sets of constants for use with variables and properties.
4. Discuss the major problem of typed sqlCeresultset that has been generated by the
tools?
The drawback if you don't close the result set yourself is that the resources won't be freed
until the garbage collector gets around to it. A lot of garbage collectors are lazy, so who
knows when that will be.
5. Specify the usage of binding source control?
The Binding Source component acts as both a conduit and a data source for other controls to
bind to. It provides an abstraction of your form's data connection while passing through
commands to the underlying list of data.
6. Suggest the meaning of signing of your code?
Code signing is a technology for verifying the authenticity of the publisher of a download to
avoid a computer virus or malware. Software signed with a digital signature is considered
safe to download.
7. Briefly address the web services?
RESTful Web Services. SOAP Web Services.
8. Pen down the four different stages of message processing in soap message?
Envelope − Defines the start and the end of the message. It is a mandatory element.
Header − Contains any optional attributes of the message used in processing the message,
either at an intermediary point or at the ultimate end-point. It is an optional element.
Body − Contains the XML data comprising the message being sent. It is a mandatory
element.
Fault − an optional Fault element that provides information about errors that occur while
processing the message.
9. Enlist the involved database in all sorts of SQL server replication?
 Publisher
 Publication database
 Publication
 Articles
 Distributor
 Distribution database
 Subscriber
 Subscriber database

10. Which namespace contains the socket class?


System.Net. Sockets Namespace
11. State the phenomenon of multithreading?
Multithreading is the ability of a program or an operating system process to manage its use
by more than one user at a time and to even manage multiple requests by the same
user without having to have multiple copies of the programming running in the computer.

Long questions:
1. Prescribe the complete solution of creating
foreign key constraints in code?

Foreign Key ConstrainT


A foreign key is a column (or combination of columns) in a table whose
values must match values of a column in some other table. FOREIGN
KEY constraints enforce referential integrity, which essentially says that if
column value A refers to column value B, then column value B must exist.

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:

 Each value inserted or updated in orders.customer_id must exactly match a


value in customers.id, or be NULL.

 Values in customers.id that are referenced by orders.customer_id cannot be


deleted or updated, unless you have cascading actions. However, values
of customers.id that are not present in orders.customer_id can be deleted or
updated.
Rules for creating foreign keys

Foreign Key Columns

 Foreign key columns must use their referenced column's type.

 A foreign key column cannot be a computed column.

 A single column can have multiple foreign key constraints. For an


example, see Add multiple foreign key constraints to a single column.

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.

 In the REFERENCES clause, if you specify a table but no columns,


CockroachDB references the table's primary key. In these cases,
the FOREIGN KEY constraint and the referenced table's primary key must
contain the same number of columns.

 By default, referenced columns must be in the same database as the


referencing foreign key column. To enable cross-database foreign key
references, set the sql.cross_db_fks.enabled cluster setting to true.

Null values

Single-column foreign keys accept null values.

Multiple-column (composite) foreign keys only accept null values in the


following scenarios:

 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.

Composite foreign key matching

By default, composite foreign keys are matched using the MATCH


SIMPLE algorithm (which is the same default as Postgres). MATCH FULL is
available if specified. You can specify both MATCH FULL and MATCH SIMPLE.

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

For matching purposes, composite foreign keys can be in one of three


states:

 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).

MATCH SIMPLE stipulates that:

 Valid keys may not contain any null values.


 Invalid keys contain one or more null values.
 Unacceptable keys do not exist from the point of view of MATCH
SIMPLE; all composite keys are acceptable.

MATCH FULL stipulates that:

 Valid keys may not contain any null values.


 Invalid keys must have all null values.
 Unacceptable keys have any combination of both null and non-null
values. In other words, MATCH FULL requires that if any column of a
composite key is NULL, then all columns of the key must be NULL.

For examples showing how these key matching algorithms work,


see Match composite foreign keys with MATCH SIMPLE and MATCH FULL.

Note:
CockroachDB does not support MATCH PARTIAL . For more information, see
issue

Foreign key actions

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.

Alias: ON DELETE RESTRICT

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.

Alias: ON UPDATE RESTRICT

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.

2. State the procedure of creating a project data


source that makes a complex query?
How do you create a complex query?
How to build complex queries using dbForge Studio for SQL Server
1. Add tables to the query. Next, you can start adding tables and views to the query. ...
2. Create a subquery. ...
3. Create JOINs between the tables. ...
4. Build WHERE or HAVING clause. ...
5. Create GROUP BY or ORDER BY clause. ...
6. View and execute the query. ...
7. Analyze the result.

How to Write Complex


Queries in SQL Server
May 13th, 2021
One of the regular jobs performed by a database administrator and developer is
creating and executing queries of higher complexity to resolve complicated tasks.
This requires extra caution and seriousness because any inaccuracies in the code
can result in undesirable bugs and application downtime.

What is a complex SQL query?


As the name suggests, a complex query has a complex syntax and can comprise
multiple parts. A purpose of such a query is to search data based on several
parameters. For instance, a complex query can include several joins across tables or
have subqueries (a query nested within another query). Besides, you can encounter
frequent use of AND and OR clauses within this type of query.
You can apply complex queries whenever it is necessary to fetch complex data from
several tables. Apart from that, they can be used for the purposes of reporting,
joining multiple tables, nesting queries, and transaction locking.

Complex SQL Server queries with several SELECT


statements
To understand data and analyze it correctly, now and then, you may need to retrieve
data from a collection of tables to generate a single result table. Hence, most
frequently, database admins and developers need to create complex SQL queries
that contain several SELECT statements. Via combining multiple results from the
SELECT statements, you are able to select what exactly you want to include in the
output. This is the main reason why they are used so often.

How to build complex queries using dbForge


Studio for SQL Server
However, writing complex queries on your own is both time-consuming and
complicated because, by the time you reach the end of your query, you will most
probably forget how it all started. So for performance reasons, it’s better to trust this
job to a reliable tool that will help you create complex queries without coding them
manually.

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.

Step 1. Open Query Builder


To start building queries visually, open dbForge Studio for SQL Server and go to the
Start page. Find Query Builder on the SQL Development tools list and click to start.

Step 2. Add tables to the query


Next, you can start adding tables and views to the query. To do that, click on the
necessary database node in Database Explorer, choose a required table (or multiple
tables), and, via a simple drag-and-drop, carry it to the query diagram area. There is
another way to do the same: right-click a table in Database Explorer and select Send
to, and then Query Builder.
Step 3. Create a subquery
dbForge Studio for SQL Server empowers you to create subqueries in any SELECT
statement clause. What’s more, within the program, every subquery can have
another subquery.

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.

Step 4. Create JOINs between the tables


Another option available within dbForge Studio for SQL Server is building several
kinds of JOINs between tables visually. These include inner, left outer, right outer,
and cross join. Besides, it is possible to set conditions of high complexity for any type
of join.

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.

Step 5. Build WHERE or HAVING clause


While building a query, you often intend to filter or exclude certain records from the
output. The easiest way to do that is by using WHERE and HAVING clauses.

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.

Step 6. Create GROUP BY or ORDER BY clause


The GROUP BY clause is usually found in a SELECT statement and is used to
group the records according to the specified parameters. The ORDER BY clause
helps to sort the records in the result-set in ascending or descending order.

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.

Step 8. Analyze the result


After you initiate the query execution, you are notified of whether the query was
executed successfully, or any errors occurred. In case the query was successful, you
can check and analyze the results.

Besides, you can manipulate the result-set depending on your needs within a handy
Data Editor functionality.

3. Explain the phenomenon of serializing and


deserializing object with the help of example?
What is serialization and deserialization of objects explain
with example?
Serialization is a mechanism of converting the state of an
object into a byte stream. Deserialization is the reverse
process where the byte stream is used to recreate the actual
Java object in memory. This mechanism is used to persist
the object. The byte stream created is platform independent.
Serialization and Deserialization in Java with Example
 Difficulty Level : Medium
 Last Updated : 07 Oct, 2021
Serialization is a mechanism of converting the state of an object into
a byte stream. Deserialization is the reverse process where the byte
stream is used to recreate the actual Java object in memory. This
mechanism is used to persist the object.
The byte stream created is platform independent. So, the object serialized on
one platform can be deserialized on a different platform.
To make a Java object serializable we implement
the java.io.Serializable interface.
The ObjectOutputStream class contains writeObject() method for serializing
an Object.

Advantages of Serialization
1. To save/persist state of an object.
2. To travel an object across a network.

Only the objects of those classes can be serialized


which are implementing java.io.Serializable interface.
Serializable is a marker interface (has no data
member and method). It is used to “mark” java classes
so that objects of these classes may get certain
capability. Other examples of marker interfaces are:-
Cloneable and Remote.
Example 1:
// Java code for serialization and deserialization
// of a Java object
import java.io.*;

class Demo implements java.io.Serializable


{
public int a;
public String b;

// 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);

// Method for serialization of object


out.writeObject(object);

out.close();
file.close();

System.out.println("Object has been serialized");

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);

// Method for deserialization of object


object1 = (Demo)in.readObject();

in.close();
file.close();

System.out.println("Object has been deserialized ");


System.out.println("a = " + object1.a);
System.out.println("b = " + object1.b);
}

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?

5. Illustrate the threats and solutions of storing


credentials and other securely?
What are the 5 threats to security?
This article will cover the top 5 security threats facing businesses, and how
organizations can protect themselves against them.
 1) Phishing Attacks. ...
 2) Malware Attacks. ...
 3) Ransomware. ...
 4) Weak Passwords. ...
 5) Insider Threats. ...


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

6. Indicate and demonstrate the synchronizing


thread activities and access to data in detail?

BS 7TH 2019 (CS)

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.

11. Which method is used to start a thread in DotNet?


You start a thread by supplying a delegate that represents the method the thread
is to execute in its class constructor. You then call the Start method to begin
execution.
12. What is IIS?
Internet Information Services is an extensible web server software created by
Microsoft for use with the Windows NT family. IIS supports HTTP, HTTP/2,
HTTPS, FTP, FTPS, SMTP and NNTP.
OR

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.

13. What is the purpose of .dll?


The use of DLLs helps promote modularization of code, code reuse, efficient
memory usage, and reduced disk space. So, the operating system and the
programs load faster, run faster, and take less disk space on the computer. When
a program uses a DLL, an issue that is called dependency may cause the
program not to run.
14. What is system namespace?
Contains fundamental classes and base classes that define commonly-used value
and reference data types, events and event handlers, interfaces, attributes, and
processing exceptions.
15. Why we need socket programming?
Socket programming shows how to use socket APIs to establish
communication links between remote and local processes. The processes
that use a socket can reside on the same system or different systems on different
networks. Sockets are useful for both stand-alone and network applications.
16. What is web service?
Web services are services spread over the web.
-Enables the communication between application over the web and provides
a standard protocol or format for communication.
-Using web services two different applications designed in different languages
Can talk to each other share information and exchange data
-Platform independent.
Long questions:
1. Write a note on DirectX 3D?
DirectX is a collection of application programming
interfaces (APIs) for handling tasks related
to multimedia, especially game programming and
video, on Microsoft platforms. Originally, the names of
these APIs all began with "Direct", such
as Direct3D, DirectDraw, DirectMusic, DirectPlay, Dire
ctSound, and so forth. The name DirectX was coined
as a shorthand term for all of these APIs
(the X standing in for the particular API names) and
soon became the name of the collection. When
Microsoft later set out to develop a gaming console,
the X was used as the basis of the name Xbox to
indicate that the console was based on DirectX
technology.[2] The X initial has been carried forward in
the naming of APIs designed for the Xbox such
as XInput and the Cross-platform Audio Creation
Tool (XACT), while the DirectX pattern has been
continued for Windows APIs such
as Direct2D and DirectWrite. The DirectX software
development kit (SDK) consists of runtime libraries in
redistributable binary form, along with accompanying
documentation and headers for use in coding
Direct3D (the 3D graphics API within DirectX) is
widely used in the development of video
games for Microsoft Windows and the Xbox line of
consoles. Direct3D is also used by
other software applications for visualization and
graphics tasks such as CAD/CAM engineering. As
Direct3D is the most widely publicized component of
DirectX, it is common to see the names "DirectX" and
"Direct3D" used interchangeably. Direct3D contains
many commands for 3D computer graphics rendering;
however, since version 8, Direct3D has superseded
the DirectDraw framework and also taken
responsibility for the rendering of 2D graphics.
[7]
Microsoft strives to continually update Direct3D to
support the latest technology available on 3D graphics
cards. Direct3D offers full vertex
software emulation but no pixel software emulation for
features not available in hardware
Direct3D is a subset of DirectX. DirectX contains
Direct3D which is the primary graphics handling
portion of DirectX. ... A game developer, or any
graphics rendering programmer, can choose
whether to call into use the DirectX (Direct3D) or
OpenGL APIs.

2. Write a note on properties


in .net and show there use
with example?
A property is a member that provides a flexible
mechanism to read, write, or compute the value
of a private field. Properties can be used as if they
are public data members, but they are actually
special methods called accessors

3. What is cryptography? How


it is implemented in mobiles?
Write a code to encrypt the
user password?
Cryptography is the study of secure
communications techniques that allow only the
sender and intended recipient of a message to
view its contents. ... When transmitting electronic
data, the most common use of cryptography is to
encrypt and decrypt email and other plain-text
messages. Cryptography can be broken down into
three different types: Secret Key
Cryptography. Public Key Cryptography. Hash
Functions.

Android encryption forces the use of a full


alphanumeric passcode, and locks the setting
causing a full system wipe if too many incorrect
passwords are entered.
Android builds on the Java Cryptography
Architecture (JCA), that provides API for digital
signatures, certificates, encryption, keys
generation and management. ... SecretKey — a
secret (symmetric) key. The purpose of this
interface is to group (and provide type safety for) all
secret key interfaces (e.g., SecretKeySpec)

PasswordUtils Java class used to


encrypt and verify user
password.
package com.appsdeveloperblog.encryption;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.util.Arrays;
import java.util.Base64;
import java.util.Random;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
public class PasswordUtils {
private static final Random RANDOM = new SecureRandom();
private static final String ALPHABET =
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
private static final int ITERATIONS = 10000;
private static final int KEY_LENGTH = 256;
public static String getSalt(int length) {
StringBuilder returnValue = new StringBuilder(length);
for (int i = 0; i < length; i++) {
returnValue.append(ALPHABET.charAt(RANDOM.nextInt(ALPHABET.length())));
}
return new String(returnValue);
}
public static byte[] hash(char[] password, byte[] salt) {
PBEKeySpec spec = new PBEKeySpec(password, salt, ITERATIONS, KEY_LENGTH);
Arrays.fill(password, Character.MIN_VALUE);
try {
SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
return skf.generateSecret(spec).getEncoded();
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
throw new AssertionError("Error while hashing a password: " + e.getMessage(), e);
} finally {
spec.clearPassword();
}
}
public static String generateSecurePassword(String password, String salt) {
String returnValue = null;
byte[] securePassword = hash(password.toCharArray(), salt.getBytes());
returnValue = Base64.getEncoder().encodeToString(securePassword);
return returnValue;
}
public static boolean verifyUserPassword(String providedPassword,
String securedPassword, String salt)
{
boolean returnValue = false;
// Generate New secure password with the same salt
String newSecurePassword = generateSecurePassword(providedPassword, salt);
// Check if two passwords are equal
returnValue = newSecurePassword.equalsIgnoreCase(securedPassword);
return returnValue;
}

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:

Plain-text password: myPassword


Encrypted password using MD5: deb1536f480475f7d593219aa1afd74c

4. Write a note on thread pool


and threading also illustrate
it with code example?
Thread pool is a single FIFO task queue with a
group of worker threads. The producers (E.g. the
UI thread) sends tasks to the task queue.
Whenever any worker threads in the thread pool
become available, they remove the tasks from the
front of the queue and start running them. In the
case of a thread pool, a group of fixed-size threads
is created.After completion of the job, the thread is
contained in the thread pool again.
A thread is a thread of execution in a program.
The Java Virtual Machine allows an application to
have multiple threads of execution running
concurrently. Every thread has a priority. ... One is
to declare a class to be a subclass of Thread . This
subclass should override the run method of class
Thread .

The different thread classes available are:

AsyncTask: Helps get work on/off the UI thread

HandlerThread: Thread for callbacks

ThreadPoolExecutor: Running lots of parallel work

IntentService: Helps get intents off the UI thread

// Java program to illustrate


// ThreadPool
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

// Task class to be executed (Step 1)


class Task implements Runnable
{
private String name;

public Task(String s)
{
name = s;
}

// Prints task name and sleeps for 1s


// This Whole process is repeated 5 times
public void run()
{
try
{
for (int i = 0; i<=5; i++)
{
if (i==0)
{
Date d = new Date();
SimpleDateFormat ft = new
SimpleDateFormat("hh:mm:ss");
System.out.println("Initialization Time for"
+ " task name - "+ name +" = "
+ft.format(d));
//prints the initialization time for every task
}
else
{
Date d = new Date();
SimpleDateFormat ft = new
SimpleDateFormat("hh:mm:ss");
System.out.println("Executing Time for task name - "+
name +" = " +ft.format(d));
// prints the execution time for every task
}
Thread.sleep(1000);
}
System.out.println(name+" complete");
}

catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
public class Test
{
// Maximum number of threads in thread pool
static final int MAX_T = 3;

public static void main(String[] args)


{
// creates five tasks
Runnable r1 = new Task("task 1");
Runnable r2 = new Task("task 2");
Runnable r3 = new Task("task 3");
Runnable r4 = new Task("task 4");
Runnable r5 = new Task("task 5");

// creates a thread pool with MAX_T no. of


// threads as the fixed pool size(Step 2)
ExecutorService pool = Executors.newFixedThreadPool(MAX_T);

// passes the Task objects to the pool to execute (Step 3)


pool.execute(r1);
pool.execute(r2);
pool.execute(r3);
pool.execute(r4);
pool.execute(r5);

// pool shutdown ( Step 4)


pool.shutdown();
}
}
5. Write a note on graphic
programming also write code
for drawing a rectangle and a
line?
The graphical approach to programming allows a computer to process spatial
representations in two or more dimensions. In contrast to text-based
programming, which uses lines of code, graphical programming replaces text with
pictures or symbols of physical things. Graphical programming provides an
approach that's more intuitive and less cumbersome for some
programmers. It also can be a more effective way to introduce
computer programming to visual learners. For example, researchers
at the Lifelong Kindergarten Group have created a program called
Scratch, which uses graphical programming to help children learn
math and engage in creative thinking.

Graphical programming is often called visual programming or Visual


Programming Language (VPL). It's different from Microsoft's Visual
Basic, which defines pictures by using text-based language.

Graphical programming is most


frequently used in the stages of
engineering systems design. Engineers
and programmers might use graphical
programs to translate information about
physical events, such as vibrations that
occur during the testing of automotive
engines, into visual readouts.

Draw a line in Java Applet:


The line is the simplest shape that we can draw with the Graphics class.
The drawLine() method takes two pair of coordinates (x1, y1) and (y1, y2) as
arguments and draws a line between them. It has the following syntax:
 g.drawLine(x1, y2, x2, y2); // g is the Graphics object passed to paint()
method.
Example:
 import java.awt.*;
 import java.applet.*;
 public class Line extends Applet
 {
 public void paint(Graphics g)
 {
 g.drawLine(100,10,250, 150);
 g.drawLine(100,150,150,10);
 }
 }
 <html>
 <head>
 </head>
 <body>
 <applet code = "Line.class" width = "420" height = "320"></applet>
 </body>
 </html>
Output:

Draw a rectangle in Java Applet:


Example:
 import java.awt.*;
 import java.applet.*;
 public class Rectangle extends Applet
 {
 public void paint(Graphics g)
 {
 g.setColor(Color.black);
 g.drawRect(120, 50, 100, 100);
 }
 }
 <applet code = "Rectangle.class" width = "480" height =
"360"></applet>
Output:

6. Write a note on failure of


window phone and success
for android OS?
BSIT 7th (2017)
1. What is android?
Android is a mobile operating system developed by Google. It is used by
several smartphones and tablets. ... The Android operating system (OS) is
based on the Linux kernel. Unlike Apple's iOS, Android is open source,
meaning developers can modify and customize the OS for each phone.
2. What are the advantages of android?
 Open Ecosystem. ...
 Customizable UI. ...
 Open Source. ...
 Innovations Reach the Market Quicker. ...
 Customized ROMs. ...
 Affordable Development
 Affordable
3. Explain architecture of android using diagram?

4. What is implicit intent in android?


An implicit intent specifies an action that can invoke any app on the device able to
perform the action. Using an implicit intent is useful when your app cannot perform
the action, but other apps probably can and you'd like the user to pick which app to
use.
5. How to call another activity in android?
To start an activity, call startActivity() and pass it your Intent . The system
receives this call and starts an instance of the Activity specified by the Intent .
Now you need to create the DisplayMessageActivity class in order for this to
work.
6. What is intent?
An Intent in the Android operating system is a software mechanism that allows
users to coordinate the functions of different activities to achieve a task.
7. What is activity in android?
An Android activity is one screen of the Android app's user interface. ... An
Android app may contain one or more activities, meaning one or more
screens. The Android app starts by showing the main activity, and from there
the app may make it possible to open additional activities.
8. what is service in android?
Services in Android are a special component that facilitates an application
to run in the background in order to perform long-running operation
tasks. ... A service can run continuously in the background even if the
application is closed or the user switches to another application.
9. What is the name of database used in android?
SQLite Database is an open-source database provided in Android which is used
to store data inside the user's device in the form of a Text file.
10.What is AAPT in android?
AAPT2 (Android Asset Packaging Tool) is a build tool that Android Studio
and Android Gradle Plugin use to compile and package your app's resources.
AAPT2 parses, indexes, and compiles the resources into a binary format that
is optimized for the Android platform. Android Gradle Plugin 3.0.
11.What is view group in android?
A ViewGroup is a special view that can contain other views. The ViewGroup
is the base class for Layouts in android, like LinearLayout ,
RelativeLayout , FrameLayout etc. In other words, ViewGroup is generally
used to define the layout in which views(widgets) will be set/arranged/listed on
the android screen.
12.What is fragment in android?
A Fragment represents a reusable portion of your app's UI. A fragment
defines and manages its own layout, has its own lifecycle, and can handle its
own input events. Fragments cannot live on their own--they must be hosted by
an activity or another fragment.
13. What is ADB in android?
The Android Debug Bridge is a programming tool used for debugging Android-
based devices using a USB or TCP connection. It consists of a client and server
on the host PC, where the server connects to the daemon on the Android device.
Available since 2007, features include a shell and the possibility to make backups.
14. what is ndk in andoid?
The Native Development Kit (NDK) is a set of tools that allows you to use C and
C++ code with Android, and provides platform libraries you can use to manage
native activities and access physical device components, such as sensors and
touch input.
15. what is google android sdk?
The Android SDK (software development kit) is a set of development tools
used to develop applications for the Android platform that has become
Apple's biggest rival in the smartphone space. The Android SDK includes the
following: Required libraries. Debugger. An emulator.
16. does android support other language than java?
yes... recently google has introduced new language for android programing
which is simple and easy to understand. The name of that language is
KOTLIN.

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

2. What is the core building blocks of


android?
A piece of code with a well-defined life cycle e.g. Activity,
Receiver, Service, etc. is what an android component can
be simply understood as. Activities, views, intents, services,
content providers, fragments, and AndroidManifest.xml are
the core building blocks or fundamental
components of android.
Activity:
Being similar to a Frame in AWT, an activity as a class
represents a single screen. It is a core
building block, i.e., the fundamental component of android.
View:
The UI element including button, label, text field, etc, and
anything that one can see is a view.
Intent:
Along with invoking the components, the Intent is used for
many purposes including:
 Start the service
 Launch an activity
 Display a web page
 Display a list of contacts
 Broadcast a message
 Dial a phone call etc.
Example: To view the webpage:
Intent intent=new
Intent(Intent.ACTION_VIE
W);
intent.setData(Uri.parse("
http://www.test.com"));
startActivity(intent);

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.

3. Write down features of android


application?
Features of Android:
Android is a powerful operating system competing with
Apple 4GS and supports great features.
Few of them are listed below -
Sr.No. Feature & Description
Beautiful UI
Android OS basic screen provides a
1
beautiful and intuitive user
interface.
Connectivity
GSM/EDGE, IDEN, CDMA, EV-DO,
2
UMTS, Bluetooth, Wi-Fi, LTE, NFC
and WiMAX.
Storage
SQLite, a lightweight relational
3
database, is used for data storage
purposes.
Media support
H.263, H.264, MPEG-4 SP, AMR,
AMR-WB, AAC, HE-AAC, AAC 5.1,
4
MP3, MIDI, Ogg
Vorbis, WAV, JPEG, PNG, GIF, and
BMP.
Messaging
5
SMS and MMS
Web browser
Based on the open-source WebKit
layout engine, coupled with
6
Chrome's V8 JavaScript
engine supporting HTML5 and
CSS3.

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.

4. What is ACTIVITY and ACTIVITY


LIFECYCLE? Explain ACTIVITY
LIFECYCLE using flow chart?
What is an Activity in Android?
Human mind or conscious is responsible for what we feel,
what we think, makes us feel pain when we are hurt
(physically or emotionally), which often leads to a few tears,
laughing on seeing or hearing
something funny and a lot more. What happens to us in the
real world physically (getting hurt, seeing, hearing etc.) are
interpreted by our mind(conscious or soul) and we think or
operate as per.
So in a way, we can say that our body is just a physical
object while what controls us through every situation is our
mind (soul or conscious).
In case of Android → Views, Layouts and View Groups are
used to design the user interface, which is the physical
appearance of our App. But what is the mind or soul or
conscious of our App? Yes, it is the Activity.
Activity is nothing but a java class in Android which has
some pre-defined functions which are triggered at different
App states, which we can override to perform anything we
want.
Activity class provides us with empty functions allowing us
to be the controller of everything.
For example, if we have a function specified by our mind →
onSeeingSomethingFunny (),
although we know what happens inside this, but what if we
can override and provide our own
definition to this function.
@Override
onSeeingSomethingFunny()
{
start crying;
}
Copy
One thing that is different here in context to our example is,
that a human is created once at birth, and is destroyed
once at death, and for the time in between is controlled by
the mind/soul/conscious. But an Activity is responsible to
create and destroy an App infinite number of times. So
apart from controlling the app, Activity also controls
creation, destruction and other states of the App's lifecycle.
There can be multiple Activities in Android, but there can be
only one Main Activity. For example, In Java programming
(or programming languages like C or C++), the execution of
the program always begin with main() method. Similarly,
when the user presses the App icon, the Main Activity is
called and the execution starts from the onCreate() method
of the Activity class.
Activity Lifecycle methods:
Whenever we open Google Maps app, it fetches our location
through GPS. And if the GPS tracker is off, then android will
ask for your permission to switch it ON. So how the GPS
tracker or Android is able to decide whether an app needs
GPS tracker for functioning or not?
Yes, obviously, the App when started asks for the GPS
location which is only possible if the GPS tracker in switched
ON.
And how does the App knows this, because we coded it that
whenever a user starts it, it has to ask the user to switch
ON the GPS tracker, as it is required. Similarly, we can also
tell the app to perform a few things before exiting or
getting destroyed. This is the role of Activity Lifecycle.
There are six key lifecycle methods through which every
Activity goes depending upon its state. They are:
1. onCreate()
2. OnStart()
3. OnResume ()
4. on Pause()
5. on Stop()
6. on Destroy()

Method What does it do?


Whenever an Activity starts
running, the first method to
get executed is onCreate ().
This method is
executed only once during the
lifetime. If we have any
onCreate() instance variables in the
Activity, the
initialization of those variables
can be done in this method.
After onCreate() method,
the onStart() method is
executed.
During the execution of
onStart() method, the Activity
is not yet rendered on screen
but is about to
onStart()
become visible to the user. In
this method, we can perform
any operation related to UI
components.
When the Activity finally gets
rendered on the screen,
onResume () method is
onResume() invoked. At this
point, the Activity is in the
active state and is interacting
with the user.
If the activity loses its focus
and is only partially visible to
the user, it enters the paused
state.
During this transition, the
onPause() method is invoked.
onPause() In the onPause() method, we
may commit
database transactions or
perform light-weight
processing before the Activity
goes to the
background.
onStop() From the active state, if we hit
the Home key, the Activity
goes to the background and
the Home
Screen of the device is made
visible. During this event, the
Activity enters the stopped
state.
Both onPause() and onStop()
methods are executed.
When an activity is destroyed
onDestroy() by a user or Android system,
onDestroy() function is called.
When the Activity comes back to focus from the paused
state, onResume() is invoked.When we reopen any
app(after pressing Home key), Activity now transits from
stopped state to the active state. Thus, onStart() and
onResume() methods are invoked.
Note: onCreate() method is not called, as it is executed only once during the
Activity life-cycle.
To destroy the Activity on the screen, we can hit the Back
key. This moves the Activity into the destroyed state.
During this event, onPause(), onStop() and onDestroy()
methods are invoked.
Note: Whenever we change the orientation of the screen i.e from portrait to
landscape or viceversa, lifecycle methods start from the start i.e from onCreate()
method. This is because the
complete spacing and other visual appearance gets changed and adjusted.

5. What is CONTENTPROVIDER and what


is typically used for?
A content provider component supplies data from one application to others on
request. Such requests are handled by the methods of the ContentResolver class.
A content provider can use different ways to store its data and the data can be
stored in a database, in files, or even over a network.
A content provider coordinates access to the data storage layer in your
application for a number of different APIs and components as illustrated in figure
1, these include:
 Sharing access to your application data with other applications
 Sending data to a widget
 Returning custom search suggestions for your application through the search
framework
using SearchRecentSuggestionsProvider
 Synchronizing application data with your server using an implementation
of AbstractThreadedSyncAdapter
 Loading data in your UI using a Cursor Loader
Figure 1. Relationship between content provider and other
components.
Accessing a provider:
When you want to access data in a content provider, you
use the Content Resolver object in your application's
Context to communicate with the provider as a client. The
Content Resolver object communicates with the provider
object, an instance of a class that implements Content
Provider.
The provider object receives data requests from clients,
performs the requested action, and returns the results. This
object has methods that call identically-named methods in
the provider object, an instance of one of the concrete
subclasses of Content Provider.
The Content Resolver methods provide the basic "CRUD"
(create, retrieve, update, and delete) functions of persistent
storage.
A common pattern for accessing a Content Provider from
your UI uses Cursor Loader to run an asynchronous query in
the background. The Activity or Fragment in your UI call a
Cursor Loader to the query, which in turn gets the Content
Provider using the Content Resolver.
This allows the UI to continue to be available to the user
while the query is running. This pattern involves the
interaction of a number of different objects, as well as the
underlying storage mechanism, illustrated in fig2:

BSSE 7th (2018)


1. What is eclipse in android?
Eclipse is an integrated development environment (IDE) used
in computer programming. It contains a base workspace and an
extensible plug-in system for customizing the environment. ... The
Eclipse software development kit (SDK), which includes the Java
development tools, is meant for Java developers.
2. What is the purpose of threading?
Threads provide a way to improve application performance
through parallelism. Threads represent a software approach to
improving performance of operating system by reducing the
overhead thread is equivalent to a classical process. Each thread
belongs to exactly one process and no thread can exist outside a
process.
3. What is socket programming?
Socket programming is a way of connecting two nodes on a network to
communicate with each other. One socket (node) listens on a particular
port at an IP, while other socket reaches out to the other to form a
connection. Server forms the listener socket while client reaches out to
the server.
4. What are picker views in android?
Android provides controls for the user to pick a time or pick a date as
ready-to-use dialogs. Each picker provides controls for selecting each
part of the time (hour, minute, AM/PM) or date (month, day, year).
5. How to use the intent object to link activities in android?
To start an activity, use the method startActivity(intent) . This method
is defined on the Context object which Activity extends. The following
code demonstrates how you can start another activity via an intent. #
Start the activity connect to the # specified class Intent i = new
Intent(this, ActivityTwo.
6. Which company developed android?
Android began in 2003 as a project of the American technology
company Android Inc., to develop an operating system for digital cameras.
In 2004 the project changed to become an operating system for smartphones.
Android Inc., was bought by the American search engine company Google
Inc., in 2005.
7. How to listen foe UI notification in android?
Step 1: Tap the furthest left icon at the top bar of the app. Here you
can pick which applications you want to hear notifications for. ...
Step 2: Press on the next icon to the right, which opens the General
Settings area. ...
Step 3: Touch Start in the middle of the screen.
8. How to use the list view to display list of items?
Android ListView is a view which groups several items and display them
in vertical scrollable list. The list items are automatically inserted to the
list using an Adapter that pulls content from a source such as an array or
database
9. Briefly discuss how to send SMS messages
programmatically from within your application?
In Android, you can use SmsManager API or devices Built-in SMS
application to send SMS's

 //Getting intent and PendingIntent instance.


 Intent intent=new Intent(getApplicationContext(),MainActivity. ...
 PendingIntent pi=PendingIntent.getActivity(getApplicationContext(), 0, intent,0);
 //Get the SmsManager instance and call the sendTextMessage method to send
message.
10. How to write and read files in internal and external
storage android?
To create a file to internal storage, first you need to get directory. There are two types of
directories, temporary cache directory and directory for permanent files. Files stored in
temporary directory are removed by the system to free up storage space. To get internal
directory for your app, call getFilesDir().
Remaining…
11. Android is based on which kernel?
Android is based on a modified Linux 2.6 kernel. Google, as well as other members of the
Open Handset Alliance (OHA) collaborated on Android (design, development, distribution).
Currently, the Android Open Source Project (AOSP) is governing the Android maintenance
and development cycle
12. What is JSON exception in android?
org.json.JSONException. Thrown to indicate a problem with the JSON API. Such
problems include: Attempts to parse or construct malformed documents. Use of null
as a name.
13. How to display track on google map in android studio?
…………………..
14. What are different android devices in the market?
Top 10 Android Devices in the Market
 Introduction.
 Google Pixel C.
 Samsung Galaxy S6.
 Samsung Galaxy Note 5.
 Motorola Moto G.
 Google Nexus 6P.
 LG V10.
 Dell Venue 8 7000.
15. How to export your application as an APK file and
sign it with a new certificate?
1. Change the resource in the .apk. Open the .apk file with WinRAR (if
that doesn't work, rename the file extension .apk to .zip) ...
2. Sign the .apk. Android doesn't allow to install an application (apk) that
isn't signed. ...
3. Install the apk on the device.
SignanAPK:

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.

ADAPTING TO DISPLAY ORIENTATION


One of the key features of modern smartphones is their ability to switch screen
orientation, and
Android is no exception. Android supports two screen orientations: portrait and
landscape. By
default, when you change the display orientation of your Android device, the
current activity that is
displayed automatically redraws its content in the new orientation. This is
because the onCreate()
method of the activity is fired whenever there is a change in display orientation.
However, when the views are redrawn, they may be drawn in their original
locations (depending
on the layout selected)
in landscape mode, a lot of empty space on the right of the screen could be used.
Furthermore,
any additional views at the bottom of the screen would be hidden when the
screen orientation is set to
landscape.
In general, you can employ two techniques to handle changes in screen
orientation:
➤ Anchoring — The easiest way is to “anchor” your views to the four edges of
the screen. When
the screen orientation changes, the views can anchor neatly to the edges.
➤ Resizing and repositioning — Whereas anchoring and centralizing are simple
techniques to
ensure that views can handle changes in screen orientation, the ultimate
technique is resizing
each and every view according to the current screen orientation.

2. Discuss installing and configuring


the android SDK manager and anatomy
of an android application?
Configuring the Android SDK Manager
The Android SDK Manager manages the various versions of the Android SDK
currently installed
on your computer. When it is launched, you will see a list of items and whether or
not they are
currently installed on your computer.
Check the relevant tools, documentation, and platforms you need for your project.
Once you have
selected the items you want, click the Install button to download them. Because it
takes a while
to download from Google’s server, it is a good idea to download only what you
need immediately,
and download the rest when you have more time.
Each version of the Android OS is identified by an API level number. For example,
Android 2.3.3 is
level 10 (API 10), while Android 3.0 is level 11 (API 11), and so on. For each level,
two platforms are
available. For example, level 14 offers the following:
➤ SDK Platform
➤ Google APIs by Google Inc.
The key difference between the two is that the Google APIs platform contains
additional APIs
provided by Google (such as the Google Maps library). Therefore, if the
application you are writing
requires Google Maps, you need to create an AVD using the Google APIs platform.
You will be asked to choose the packages to install. Check the Accept All option
and click Install. The SDK Manager will proceed to download the packages that
you have selected. The installation takes some time, so be patient. When all the
packages are installed, you will be
asked to restart the ADB (Android Debug Bridge). Click Yes.

ANATOMY OF AN ANDROID APPLICATION


Now that you have created your first Hello World Android
application, it is time to dissect the innards of the Android
project and examine all the parts that make everything work.
First, note the various files that make up an Android project in
the Package Explorer in Eclipse.
The various folders and their files are as follows:
➤ src — Contains the .java source fi les for your project.
In this example, there is one fi le, HelloWorldActivity
.java. The HelloWorldActivity.java fi le is the
source fi le for your activity. You write the code for your
application in this fi le. The Java fi le is listed under the
package name for your project, which in this case is net
.learn2develop.HelloWorld.
➤ gen — contains the R.java fi le, a compiler-generated
fi le that references all the resources found in your project.
You should not modify this fi le. All the resources in your
project are automatically compiled into this class so that
you can refer to them using the class.
➤ Android 4.0 library — This item contains one fi le,
android.jar, which contains all the class libraries
needed for an Android application.
➤ Assets — This folder contains all the assets used by your
application, such as HTML, text fi les, databases, etc.
➤ bin — This folder contains the fi les built by the ADT during the build process. In particular,
it generates the .apk fi le (Android Package). An .apk fi le is the application binary of an
Android application. It contains everything needed to run an Android application.
➤ res — this folder contains all the resources used in your application. It also contains a few
other subfolders: drawable-<resolution>, layout, and values.
AndroidManifest.xml — This is the manifest fi le for your Android application.
Here you
specify the permissions needed by your application, as well as other
features (such as intent-filters,

3. Discuss components of mobile


application and workflow for its
application developments?
4. Discuss linking activities using
intents, fragments and displaying
notification?
5. Discuss android game development
and publishing android application in
details?

You might also like