Android Tutorial
Android Tutorial
Android Tutorial
Manjunath.R
*Website: http://www.myw3schools.com/
Educational institutions are teaching it
Pupils need it
The Android (a mobile operating system based on a modified version of the Linux kernel) which was
developed by the Open Handset Alliance, led by Google, and other companies – and has now garnered
the interest of a million smartphone users. This book is for all android developers, whether you are a
noviceor an experienced pro. The beginner will find its carefully paced discussions and many
examplesespecially helpful. Of course those who have already familiar with android programming are
likely toderive more benefits from this book. After completing this book you will find yourself at a
moderate levelof expertise in Android programming from where you can take yourself to next levels.
Contents
Java Programming 1
Android 109
"Remember that code is really the language in which we ultimately express the requirements. We may
create languages that are closer to the requirements. We may create tools that help us parse and assemble
those requirements into formal structures. But we will never eliminate necessary precision—so there will
always be code."
― Robert C. Martin
Java Programming Language
Website oracle.com/java/
Influenced by
CLU, Simula67, LISP, SmallTalk, Ada 83, C++, C#, Eiffel, Mesa, Modula-3, Oberon, Objective-
C, UCSD Pascal, Object Pascal
Influenced
Ada
2005, BeanShell, C#, Chapel, Clojure, ECMAScript, Fantom, Gambas, Groovy, Hack, Haxe, J#, Kotli
n, PHP, Python, Scala, Seed7, Vala
Java is one of the most used programming languages used in the development of virus-free
systems [because:
469
1
No explicit pointer
Java Programs run inside a virtual machine sandbox
] and a open-source and free high level programming language and a computing platform for
application development conceived by James Gosling, Patrick Naughton, Chris Warth, Ed
Frank, and Mike Sheridan at Sun Microsystems, Inc. in 1991 to create programs to control
consumer electronics (which is now a subsidiary of Oracle Corporation) and released in 1995,
runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX,
used in internet programming, mobile devices, games, e-business solutions etc., because of its
reliability, high performance, simplicity and easy to use and quick to learn and rigid versus
extensibility. Since Java has a runtime environment (JRE) and API, it is called a platform. As a
language that has the Object-Oriented feature, Java supports:
Polymorphism
Inheritance
Encapsulation
Abstraction
Classes
Objects
Instance
Method
Message Passing
Advantages:
Object Oriented
Platform Independent
Simple
470
2
Dynamic
Secure
Multi-threaded
Architecture-neutral
Portable
Robust
Standalone Application
Web Application
Enterprise Application
Mobile Application
471
3
text file named HelloWorld.java
name
main()method
public class HelloWorld {
public static void main(String [] args) {
System.out.println("Hello, World!"); statement
}
}
Now Type the System.out.println("Hello, World!"); which displays the text Hello World.
A Java program:
472
4
is written using Text Editor , such as [ Notepad++, Notepad ] and saved with [.java] Extension.
File Saved with [.java] extension is called Source Program or Source Code.
// HelloWorld.java
/* Because the class name is HelloWorld the source file should be named as
HelloWorld.java */
and sent to the java compiler (i.e., javac compiler) where the source program is compiled i.e.,
the program is entirely read and translated into Java byte codes (but not into machine language).
If the javac compiler finds any error during compilation, it provides information about the error
to the programmer. The programmer has to review code and check for the solution. And if there
are no errors the translated program (i.e., java byte codes − a highly optimized set of
instructions) is stored in computers main memory as HelloWorld.class and since the java byte
codes cannot be trusted to be correct. Therefore before execution they are verified and converted
to machine level language i.e., machine code sequence of 0s and 1s by Java run-time system,
which is called the Java Virtual Machine (JVM) and is executed by a Java interpreter and
Hello, World!
/* Comment on one or
473
5
More lines */
JVM (Java Virtual Machine) resides under RAM (Random Access Memory – the stuff
that boosts up your computer to run faster and allows your computer to perform many tasks at
the same time) and JVM comprises:
In the statement:
The word "HelloWorld" implies: name of the class is HelloWorld and this class is public.
public means that the class HelloWorld can be accessed by any other class in any package.
In the program:
474
6
}
imply the body of the class HelloWorld (Here: the curly brace '{' imply the beginning of the
class and the curly brace '}' imply the end of the class) within which the main method
is written. All method names should start with a Lower Case letter. For all class names the first
letter should be in Upper Case.
and
475
7
{
imply the beginning of the main method and the curly brace
imply the end of the main method) within which the statement:
System.out.println("Hello, World!");
main method in java functions like main function main() in C and C++.
If the statement:
Then the error will be displayed on the console screen because the program written in notepad is
saved as HelloWorld.java not as sample.java. Name of the program file should exactly match
the class name. When saving the file, you should save it using the class name and append '.java'
to the end of the name.
476
8
Like C and C++, Java is also a case sensitive language i.e., capital letters (or upper case letters)
must be avoided to prevent the display of error on the screen. For example: If the statement:
Each code statement must end with a semicolon. If we forget to end each program statement
within the body of main method with a semicolon (";") − Error will be displayed on the screen.
the main method − the entry point of the program execution i.e., the point from where the
execution of Java program begins.
In the statement:
System.out.println();
System → name of a standard class that contains variables and methods for supporting
simple keyboard and character output to the display.
out → represents the standard output stream
477
9
println() → output method of the Java language which makes provision to print the
output in the next line:
Hello,world!
on the screen.
The text Hello,world! should be enclosed by the double quotation marks (" ") and should be
written within the println method and this println method should be ended with the semicolon
i.e.,
System.out.println("Hello,world!");
Hello, World!
Hello, World!
478
10
}
}
In the statement:
public → implies: this method can accessed from anywhere outside the class HelloWorld
private
or
protected
Then compilation error will be flagged on the screen because if the method is declared private or
protected then this method does not make itself available to JVM for execution.
479
11
Why static?
Because the program execution begins from the main method and if the main method is not
declared static then the execution of the program does not take place.
void → implies the main method does not return any value i.e., main method return
nothing when it completes execution.
String args[]→ While running the program if we want to pass something to the
main method, then this parameter is used as the way of taking input from the user − so we
can pass some strings while running the program if we want.
If the word args in the statement: public static void main(String [] args) is replaced by
another word say jamesgosling or java
i.e.,
480
12
System.out.println("Hello, World!");
}
}
Hello,world!
If the statement:
is replaced by the statement public static void main(String []) − Then the error is
displayed on the screen.
Most Java programmers prefer args and argv i.e., the statements:
are preferred.
If the space is left between the words Hello and World i.e., if the statement:
481
13
is written instead of the statement:
Java Modifiers
Java Variables
Local Variables
Class Variables (Static Variables)
Instance Variables (Non-static Variables)
index (position)
482
14
codePointCount() Returns the Unicode in the specified int
string
sequence of characters
specified character(s)
considerations
arguments
array of chars
483
15
string
specified index
string
matches
substrings
specified characters
484
16
a subsequence of this sequence
character
array
string
object
485
17
sign of the second floating point y
cos(x) Returns the cosine of x (x is in radians) double
486
18
value
toDegrees(x) Converts an angle measured in radians to an double
approx. equivalent angle measured in
degrees
toRadians(x) Converts an angle measured in degrees to an double
approx. angle measured in radians
ulp(x) Returns the size of the unit of least double|float
precision (ulp) of x
487
19
Program 1.1
Program 1.2
Java program to print the word " ****hello silicon city**** " on screen
Program 1.3
488
20
*
*****
*****
*****
*****
on screen
*****
*****
*****
*****
If new line \n is not included in the above program then the output on the screen is:
*********************
489
21
(a)
****
**java**
****
(b)
****************
* *
* Hello World! *
* *
****************
(c)
java is done mostly in lowercase. Like C & C++ it's also a case-sensitive language
Answers:
490
22
a)
b)
c)
491
23
System.out.println("\n Must have a main method!");
System.out.println("\n java is done mostly in lowercase. Like C & C++ it's also a case-
sensitive language");
}
}
Program 1.4
492
24
cout<<"The area of the circle = "<< area;
In the statement:
493
25
producing a String statement:
Even though if we write ARGS instead of args i.e., even though if we express args in capital
letter, No error will be displayed on the screen.
public static void main(String [] ARGS) → no error will be displayed on the console
screen
494
26
Program 1.5
a)
495
27
Answer:
b)
Answer:
Program 1.6
496
28
F = 9*C/5 +32;
System.out.println("temperature in Fahrenheit= " +F);
}
}
Program 1.7
If you want to supply the values for a and b through the key board, then we have to rewrite the
program as follows:
497
29
import java.util.Scanner;
public class HelloWorld
{
public static void main(String [] args) {
int a, b, sum;
Scanner scan = new Scanner(System.in);
System.out.print("Enter any two Numbers: ");
a = scan.nextInt();
b = scan.nextInt();
sum = a + b;
System.out.println("the sum of a and b = " + sum);
}
}
Scanner is a class found in java.util package. So to use Scanner class, we first need
to include:
java.util package
in our program.
The statement:
498
30
implies: declaring an object of the Scanner class "scan" to read the values entered for a and b
through the key board. And the statements:
a = scan.nextInt();
b = scan.nextInt();
imply: scan is an object of Scanner class and nextInt() is a method of the object "scan" that
allows the object "scan" to read only integer values from the keyboard.
nextInt() that allows the object "scan" to read only integer values from the keyboard,
methods that allows the object "scan" to read other data types from the keyboard are
listed below:
Methods Datatype
nextInt() Integer
nextFloat() Float
nextDouble() Double
nextLong() Long
nextShort() Short
nextBoolean() Boolean
Program 1.8
499
31
i)
If you want to supply the value for x through the key board, then the above program should take
the form:
import java.util.Scanner;
public class HelloWorld {
public static void main(String [] args) {
int x;
Scanner scan = new Scanner(System.in);
System.out.print("Enter any Number: ");
x = scan.nextFloat();
System.out.println(" square root of a number = " + Math.sqrt(x));
}
}
500
32
square root of a number = 15.264337522
ii)
If you want to supply the value for x through the key board, then the above program should take
the form:
import java.util.Scanner;
public class HelloWorld {
public static void main(String [] args) {
double x;
Scanner scan = new Scanner(System.in);
System.out.print("Enter any Number: ");
x = scan.nextDouble();
System.out.println(" square root of a number = " + Math.sqrt(x));
}
}
501
33
The output on the screen:
Program 1.9
ch=A
If you want to supply the value for c through the key board, then the above program should take
the form:
502
34
c = (char)System.in.read();
System.out.println("ch= " + c);
}
}
Enter a character:
ch= K
Note: Exception is a problem that arises during the execution of a program. When an
exception occurs, program abnormally terminates and disrupts − throws Exception should
be written after the statement public static void main(String[] args) so that the
exceptions are thrown to the operating system to handle and the program will be
successfully executed and the output will be displayed on the screen.
Program 2.0
import java.util.Scanner;
public class HelloWorld {
public static void main(String [] args) {
String m;
Scanner in = new Scanner(System.in);
System.out.print("Enter the word: ");
m = in.nextLine();
System.out.println(" the word you entered = " + m);
}
}
503
35
The output on the screen:
If the statement:
m = scan.nextLine();
is written instead of
m = in.nextLine();
by the statement:
504
36
}
}
Answer:
The statement:
Program 2.1
505
37
The output on the screen:
If you want to supply the values for a and b through the key board, then we have to rewrite the
above program as follows:
import java.util.Scanner;
public class HelloWorld {
public static void main(String [] args) {
int a, b, product;
Scanner scan = new Scanner(System.in);
System.out.print("Enter any two Numbers: ");
a = scan.nextInt();
b = scan.nextInt();
product = a * b;
System.out.println("the product of a and b = " + product);
}
}
If you want to assign the floating point values for a and b, then the above program should take
the form:
import java.util.Scanner;
public class HelloWorld {
public static void main(String [] args) {
float a, b, product;
Scanner scan = new Scanner(System.in);
506
38
System.out.print("Enter any two Numbers: ");
a = scan.nextFloat();
b = scan.nextFloat();
product = a * b;
System.out.println("the product of a and b = " + product);
}
}
If the statement:
507
39
Note: The word public in the statement:
implies: that the program or the data within the program (such as methods, variables etc.) can be
accessed directly by an external java program.
is written instead of
then the program or the data within the program (such as methods, variables etc.) cannot be
accessed directly by an external program.
a=1000000000
int a, b, product;
i.e.,
508
40
public static void main(String [] args){
long int a, b, product;
a=1000000000;
b=2000000000;
product = a * b;
System.out.println("the product of a and b = " + product);
}
}
Answer:
square of a number = 4
Program 2.2
509
41
a=2;
b = a * a;
System.out.println("the square of a = " + b);
}
}
the square of a = 4
If you want to supply the value for a through the key board, then we have to rewrite the above
program as follows:
import java.util.Scanner;
public class HelloWorld{
public static void main(String [] args) {
int a, b;
Scanner scan = new Scanner(System.in);
System.out.println("Enter any Number: ");
a = scan.nextInt();
b = a * a;
System.out.println("the square of a = " + b);
}
}
Note:
510
42
If scan.nextint() is written instead of scan.nextInt()
public static void main(string [] args); is written instead of
public static void main(String [] args)
Program 2.3
Java program to find the greatest of two numbers using if - else statement
else
511
43
{
System.out.println("a is greater than b");
}
else
{
System.out.println("b is greater than a");
}
}
}
b is greater than a
{
System.out.println("a is greater than b");
}
a is greater than b
{
System.out.println("b is greater than a");
}
b is greater than a
512
44
If you want to supply the values for a and b through the key board, then the above program
should be rewritten as:
import java.util.Scanner;
public class HelloWorld{
public static void main(String [] args){
int a, b;
Scanner scan = new Scanner(System.in);
System.out.println("Enter any two Numbers: ");
a = scan.nextInt();
b = scan.nextInt();
if(a>b)
{
System.out.println("a is greater than b");
}
else
{
System.out.println("b is greater than a");
}
}
}
b is greater than a
Note:
513
45
System.out.println ("b is greater than a");
i.e.,
import java.util.Scanner;
public class HelloWorld{
public static void main(String [] args){
int a, b;
Scanner scan = new Scanner(System.in);
System.out.println("Enter any two Numbers: ");
a = scan.nextInt();
b = scan.nextInt();
if(a>b)
System.out.println("a is greater than b");
if(b>a)
System.out.println("b is greater than a");
}
}
There will no display of compilation error on the screen or there will be no change in the
output displayed on the screen (i.e., b is greater than a will be outputted on the screen).
Program 2.4
Java program to find the greatest of three numbers using else if statement
514
46
print this statement using the method System.out.println( );
else
515
47
c is greater than b and a
If the statements:
if(a>b&&a>c)
{
System.out.println("a is greater than b and c");
}
else if(b>a&&b>c)
{
System.out.println("b is greater than a and c");
}
else
{
System.out.println("c is greater than b and a");
}
if(a>b&&a>c)
{
System.out.println(a + "is greater than" + b + "and" + c);
}
else if(b>a&&b>c)
{
System.out.println(b + "is greater than" + a + "and" + c);
}
else
{
System.out.println(c + "is greater than" + b + "and" + a);
}
516
48
4 is greater than 3 and 2
Program 2.5
import java.util.Scanner;
public class HelloWorld{
public static void main(String [] args) {
int N1, N2, N3, N4, N5, N6, N7, N8, N9, N10, X;
Scanner scan = new Scanner(System.in);
System.out.println("Enter any ten Numbers: ");
N1 = scan.nextInt();
N2 = scan.nextInt();
N3 = scan.nextInt();
N4 = scan.nextInt();
N5 = scan.nextInt();
N6 = scan.nextInt();
N7 = scan.nextInt();
N8 = scan.nextInt();
N9 = scan.nextInt();
N10 = scan.nextInt();
X = (N1 + N2 + N3 + N4 + N5 + N6 + N7 + N8 + N9 + N10) /10;
System.out.println("the average of 10 numbers = " + X);
}
}
517
49
Note: The average of 10 numbers is 5.5, the output on the screen is 5 because int is used
instead of float.
Program 2.6
If you want to supply the values for P, T and R through the key board, then the above program
should take the form:
import java.util.Scanner;
public class HelloWorld {
public static void main(String [] args) {
int P,T, R, SI;
Scanner scan = new Scanner(System.in);
System.out.println("Enter principal amount:");
P = scan.nextInt();
System.out.println("Enter time:");
T = scan.nextInt();
System.out.println("Enter rate of interest:");
R = scan.nextInt();
518
50
SI = P*T*R/100;
System.out.println("the simple interest = " + SI);
}
}
Enter time:
Program 2.7
519
51
}
If you want to supply the value for age through the key board, then the above program should be
rewritten as:
import java.util.Scanner;
public class HelloWorld{
public static void main(String [] args){
int age;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the age: ");
age = scan.nextInt();
if(age> = 60)
{
System.out.println("senior citizen");
}
else
{
System.out.println("not a senior citizen");
}
}
}
520
52
senior citizen
Program 2.8
Java program to get marks for 3 subjects and declare the result:
If the marks >= 35 in all the subjects the student passes else fails.
candidate is passed
521
53
If you want to supply the values for marks M1, M2 and M3 through the key board, then the
above program should be rewritten as:
import java.util.Scanner;
public class HelloWorld{
public static void main(String [] args) {
int age;
Scanner scan = new Scanner(System.in);
System.out.println("Enter any three Numbers: ");
M1= scan.nextInt();
M2 = scan.nextInt();
M3 = scan.nextInt();
if(M1>= 35 && M2>= 35 && M3>= 35)
{
System.out.println("candidate is passed");
}
else
{
System.out.println("candidate is failed");
}
}
}
Program 2.9
522
54
import java.util.Scanner;
public class HelloWorld{
public static void main(String [] args) {
int CP, SP, loss, profit;
Scanner scan = new Scanner(System.in);
System.out.println("Enter cost price: ");
CP = scan.nextInt();
System.out.println("Enter selling price: ");
SP = scan.nextInt();
if(SP>CP)
{
System.out.println("profit= " + (SP-CP));
}
else
{
System.out.println("loss =" +(CP-SP));
}
}
}
profit = 1
Program 3.0
Java program to find the incremented and decremented values of two numbers
523
55
public class HelloWorld{
public static void main(String [] args){
int a, b, c, d, e, f;
a = 10;
b=12;
c=a+1;
d=b+1;
e=a-1;
f=b-1;
If the statements:
524
56
System.out.print("\n the incremented value of a = " + c);
System.out.print("\n the incremented value of b = " + d);
System.out.print("\n the decremented value of a = " + e);
System.out.print("\n the decremented value of b = " + f);
i.e., \n make provision for the another result to print in the new line. If you want to supply the
values for a and b through the key board, then the above program should take the form:
import java.util.Scanner;
public class HelloWorld{
public static void main(String [] args){
int a, b, c, d, e, f;
Scanner scan = new Scanner(System.in);
System.out.println("Enter any Number: ");
a = scan.nextInt();
System.out.println("Enter any Number: ");
b = scan.nextInt();
c=a+1;
d=b+1;
e=a-1;
f=b-1;
System.out.print("\n the incremented value of a = " + c);
System.out.print("\n the incremented value of b = " + d);
System.out.print("\n the decremented value of a = " + e);
System.out.print("\n the decremented value of b = " + f);
}
525
57
}
A)
import java.util.Scanner;
public class temperature{
public static void main(String [] args) {
float T1, T2, A;
Scanner scan = new Scanner(System.in);
System.out.println("Enter any Number: ");
T1 = scan.nextFloat();
System.out.println("Enter any Number: ");
T2 = scan.nextFloat();
A = (T1 + T2) / 2;
System.out.println("the average temperature of the day = " + A);
526
58
}
}
Answer:
B)
import java.util.Scanner;
public class HelloWorld{
public static void main(String [] args) {
int P;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the percentage: ");
P = scan.nextInt();
if(P >= 60)
{
System.out.println("first class");
}
else if(P>=50&&P <60)
{
System.out.println("second class");
}
else
{
System.out.println("pass class");
}
if(P<40)
527
59
{
System.out.println("fail");
}
}
}
Answer:
first class
Program 3.1
Java program to calculate the discounted price and the total price after discount
Given:
discounted price
import java.util.Scanner;
public class HelloWorld{
public static void main(String [] args) {
int PV, dis;
Scanner scan = new Scanner(System.in);
System.out.println("Enter purchased value: ");
PV = scan.nextInt();
if(PV<1000)
{
528
60
System.out.println("dis = " + PV* 0.1);
}
else if(PV>5000)
{
System.out.println("dis = " + PV* 0.2);
}
else
{
System.out.println("dis= " + PV* 0.3);
}
}
}
dis = 1300
total price
import java.util.Scanner;
public class HelloWorld{
public static void main(String [] args) {
int PV, total;
Scanner scan = new Scanner(System.in);
System.out.println("Enter purchased value: ");
PV = scan.nextInt();
if(PV<1000)
{
System.out.println("total= " + PV - PV* 0.1);
}
else if(PV>5000)
{
529
61
System.out.println("total = " + PV- PV* 0.2);
}
else
{
System.out.println("total= " + PV- PV* 0.3);
}
}
}
total = 585
import java.util.Scanner;
public class HelloWorld{
public static void main(String [] args){
int PV, dis, total;
Scanner scan = new Scanner(System.in);
System.out.println("Enter purchased value: ");
PV = scan.nextInt();
if(PV<1000)
{
System.out.println("dis = " + PV* 0.1);
System.out.println("total= " + total - dis);
}
else if(PV>5000)
{
System.out.println("dis = " + PV* 0.2);
System.out.println("total= " + total - dis);
530
62
}
else
{
System.out.println("dis = " + PV* 0.3);
System.out.println("total= " + total - dis);
}
}
}
Program 3.2
Java program to print the first ten natural numbers using for loop statement
531
63
If the statement:
value of i = 1
value of i = 2
value of i = 3
value of i = 4
value of i = 5
value of i = 6
value of i = 7
value of i = 8
value of i = 9
value of i = 10
532
64
If the for loop statement:
is written instead of the statement: for (i=1; i<10; i++), then the output on the screen
is:
Note: the condition i<=10 tells to print till value of i =10 but the condition i<10 tells to
print till value of i=9
If the statement:
is written instead of the statement: for (i=1; i<=10; i++), then the output on the screen is:
continues ....
If the statement:
533
65
System.out.println("\n " + i);
10
Answer:
There is no mistake in the above program. Addition of the statement throws Exception does not
make any change in the output displayed on the screen or give rise to any compilation error on
the screen.
534
66
Program 3.3
Answer:
Java program to print the first ten natural numbers using while loop statement
535
67
while (i<=10)
{
System.out.println("\n " + i++);
}
}
}
10
If the statement:
int i = 1;
is replaced by
int i = 0;
536
68
0
10
int i = 7;
10
do
537
69
}
i=1
i=2
i=3
i=4
i=5
i=6
i=7
i=8
i=9
i=10
The statement:
538
70
is executed and then condition (i<=10) is checked. If condition (i<=10) is true then
The statement:
is executed again. This process repeats until the given condition (i<=10) becomes false.
Program 3.4
Java program to print the characters from A to Z using for loop, do while loop and while
loop statement.
Java program to print the characters from A to Z using for loop statement:
539
71
D
Java program to print the characters from A to Z using while loop statement:
540
72
while (a<='Z')
{
System.out.println("\n " + a++);
}
}
}
Program 3.5
import java.util.Scanner;
public class HelloWorld{
public static void main(String [] args) {
int a;
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number: ");
a = scan.nextInt();
541
73
if(a%2 = = 0)
{
System.out.println("the number is even");
}
else
{
System.out.println("the number is odd");
}
}
}
Enter a number:
Program 3.6
import java.util.Scanner;
public class HelloWorld{
public static void main(String [] args) {
int a, b, c;
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number: ");
a = scan.nextInt();
System.out.println("Enter a number: ");
b = scan.nextInt();
c = a%b;
System.out.println("the remainder of a and b = " + c);
}
542
74
}
Enter a number:
If you enter the number 3
Enter a number:
If you enter the number 2
Since (a =3 and b =2). Therefore: 3 divided by 2 (i.e., a divided by b) yields the remainder equal
to 1.
Program 3.7
import java.util.Scanner;
public class HelloWorld{
public static void main(String [] args) {
int x, y;
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number: ");
x = scan.nextInt();
System.out.println("Enter a number: ");
y = scan.nextInt();
if(x-y==0)
{
System.out.println("the two numbers are equivalent");
}
else
543
75
{
System.out.println("the numbers are not equivalent");
}
}
Enter a number:
If you enter the number 2
Enter a number:
If you enter the number 2
Program 3.8
544
76
}
}
leap year
Answer:
value of a = 2
If the statement:
545
77
(where :: denote scope resolution operator)
i.e.,
Then the compilation error will be displayed on the screen because [like C++] JAVA does not
hold or support the resolution operator.
Program 3.9
546
78
The output on the screen:
The statement
{
System.out.println("number is negative");
}
Program 4.0
Java program to print the sum of the first 10 digits using for loop statement:
547
79
sum of the first 10 digits = 55
The statement:
on the screen.
If the statement:
int i, sum = 0;
is replaced by
int i, sum = 1;
What will be the output if the for loop statement for(i =1; i<=10; i++) is replaced by
the statement for(i =2; i<10; i++)?
548
80
If the statement
Then the compilation error message will be displayed on the screen (stating that sum is twice
declared).
Program 4.1
Java program to print the average of the first 10 numbers using for loop statement
549
81
If the data type float is used i.e.,
Program 4.2
Java program to print the product of the first 10 digits using for loop statement
550
82
The statement:
Program 4.3
Java Program to print the table of a number using the for loop statement
import java.util.Scanner;
public class HelloWorld{
public static void main(String [] args){
int n, i;
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number: ");
n = scan.nextInt();
for( i=1; i<=5; i++)
System.out.println ( \n n + " * " + i + " = " + n * i);
551
83
}
}
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8
2 * 5 = 10
i.e.,
import java.util.Scanner;
public class HelloWorld{
public static void main(String [] args){
int n, i;
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number: ");
n = scan.nextInt();
for( i=1; i<=5; i++)
System.out.println ( \n n + " + " + i + " = " + n + i);
}
}
552
84
Enter any number:
If you enter the number 2 (i.e., n=2)
2 + 1 = 3
2 + 2 = 4
2 + 3 = 5
2 + 4 = 6
2 + 5 = 7
Program 4.4
Java program to print the first 10 numbers starting from one together with their squares
If the statement:
553
85
System.out.println(" number = " + i + " its square = " + i*i);
i.e.,
If the statement:
554
86
System.out.println(" \n number = " + i + " its square = " + i*i);
i.e.,
555
87
If the statement:
i.e.,
number = 1
its square=1
number = 2
its square=4
number = 3
its square=9
number = 4
its square=16
number = 5
its square=25
number = 6
its square=36
number = 7
its square=49
number = 8
its square=64
number = 9
556
88
its square=81
number= 10
its square=100
Write a program to print the first 10 numbers starting from one together with their
squares and cubes:
Answer:
Program 4.5
557
89
return (a+b) ;
}
}
} imply the body of the main method with in which the program statements:
int a, b, c;
a = 11;
b = 6;
c = add (a, b);
System.out.println(" sum of two numbers = " + c);
are written.
Like in C ++ (the function declaration is not made) and unlike in C [(the function
declaration is made) − there is no need for method declaration in Java (i.e., without the
558
90
method declaration the program will be successfully executed and the result will be
outputted on the screen]
public static int add (int a, int b) imply: the method to add two integers x and y
and
return (a+b) ;
imply the body of the method public static int add (int a, int b)
main method:
The statement
int a, b, c;
559
91
The statements:
a = 11;
b = 6;
c = add (a, b);
The statement:
imply method call (i.e., we are calling the method public static int add (int a, int b) to add the
values (i.e., 11 and 6) and return the result (i.e., 17) to the statement
to make provision to display the output of the sum of two entered numbers as 17 on the screen.
560
92
}
import java.util.Scanner;
public class HelloWorld{
public static void main(String[] args) {
int a, b;
Scanner scan = new Scanner(System.in);
System.out.println("Enter any two numbers: ");
a = scan.nextInt();
b = scan.nextInt();
System.out.println(" largest of two numbers = " + max (a, b) );
}
public static int max (int a, int b) {
if(a>b)
return a;
else
return b;
}
}
561
93
will be outputted on the screen.
import java.util.Scanner;
public class HelloWorld{
public static void main(String[] args) {
int a, b, c;
Scanner scan = new Scanner(System.in);
System.out.println("Enter any three numbers: ");
a = scan.nextInt();
b = scan.nextInt();
c= scan.nextInt();
System.out.println(" largest of two numbers = " + max (a, b, c) );
}
public static int max (int a, int b, int c) {
if(a>b && a>c)
return a;
else if (b>c && b>a)
return b;
else
return c;
}
}
562
94
Java program to print the square of the number using method
import java.util.Scanner;
public class HelloWorld{
public static void main(String[] args) {
int x;
Scanner scan = new Scanner(System.in);
System.out.println("Enter any number: ");
x = scan.nextInt();
System.out.println("square of the number = " + square (x));
}
public static int square (int x){
return x*x;
}
}
Program 4.6
Switch (case) allows to make decision from the number of choices i.e., from the number
of cases
For example:
563
95
public static void main(String[] args)throws Exception{
char ch;
System.out.print("Enter a character:");
ch = (char)System.in.read();
switch(ch)
{
case 'R':
System.out.print("Red");
break;
case 'W':
System.out.print("White");
break;
case 'Y':
System.out.print("Yellow");
break;
case 'G':
System.out.print("Green");
break;
default:
System.out.print("Error");
break;
}
}
}
Enter a character:
If you enter a character R
Red
Program 4.7
564
96
Java program to print the output
Element [0] = 16
Element [1] = 18
Element [2] = 20
Element [3] = 25
Element [4] = 36
using arrays:
Element [0] = 16
Element [1] = 18
Element [2] = 20
Element [3] = 25
Element [4] = 36
Array declaration in C:
int num [5] = {16, 18, 20, 25, 36};
565
97
or
int num [] = {16, 18, 20, 25, 36};
566
98
public class HelloWorld{
public static void main(String[] args){
int i, avg, sum = 0;
int [] num = {16, 18, 20, 25, 36};
for(i=0; i<5; i++)
sum = sum + num[i];
avg = sum/5;
System.out.println("Sum of the Elements in the array = " + sum);
System.out.println("average of the Elements in the array = " + avg);
}
}
Einstein [0] = E
Einstein [1] = I
Einstein [2] = N
Einstein [3] = S
Einstein [4] = T
Einstein [5] = E
Einstein [6] = I
Einstein [7] = N
using arrays
567
99
Answer:
i)
Answer:
Einstein [0] = 69
Einstein [1] = 73
Einstein [2] = 78
Einstein [3] = 83
Einstein [4] = 84
Einstein [5] = 69
100
568
Einstein [6] = 73
Einstein [7] = 78
ii)
Answer:
body [b] = b
body [o] = o
body [d] = d
body [y] = y
import java.util.Scanner;
public class HelloWorld {
public static void main(String [] args) {
int x, y;
Scanner scan = new Scanner(System.in);
System.out.print("Enter any Number: ");
x = scan.nextFloat();
System.out.print("Enter any Number: ");
y = scan.nextInt();
System.out.println(" square root of x = " + Math.sqrt(x));
System.out.println(" square root of y = " + Math.sqrt(y));
}
}
101
569
The output on the screen:
square root of x = 3
square root of y = 2
If
/*
*/
is introduced i.e.,
import java.util.Scanner;
public class HelloWorld {
public static void main(String [] args) {
int x, y;
Scanner scan = new Scanner(System.in);
System.out.print("Enter any Number: ");
x = scan.nextInt();
/*
System.out.print("Enter any Number: ");
y = scan.nextInt();
*/
102
570
System.out.println(" square root of x = " + Math.sqrt(x));
/*
System.out.println(" square root of y = " + Math.sqrt(y));
*/
}
}
square root of x = 3
Answer:
long float x; should not be used − only float x should be used because Java do not support the
data type such as long int, long float etc.
103
571
Program 4.8
A)
System.out.println("" + i);
}
}
}
B)
104
572
}
System.out.println("" + i);
}
}
}
1356
In the statement:
105
573
"1 + 2"
"1" and "2" imply the operands and the plus symbol imply the operator.
Polymorphism
Suppose if you are in class room that time you behave like a student, when you are in shopping
mall at that time you behave like a customer, when you at your home at that time you behave
like a son or daughter. Your ability to present in different-different behaviors is known as
polymorphism.
In the example:
sum = a+b;
106
574
System.out.println("the sum of a and b = " + sum);
The ability of plus symbol to behave both as arithmetic operator and concatenation operator is
known as polymorphism.
Inheritance
Here public class player extends game implies: class player is public and it is the sub class of the
class game. Since class player is the subclass of class game − class player automatically takes on
all the behavior and attributes of its parent class "game" i.e., methods or fields within the class
game will be automatically be included in the class player.
The statements:
implies: that class player is not only a subclass of class game but also it is a subclass of class
ball.
107
575
Encapsulation
Encapsulation is the technique of bringing the data variables and methods in single frame and
declaring data variable private (so it cannot be accessed by anyone outside the class, thereby
hiding or encapsulating the data variable (String name) within the public class Student) and
providing indirect access to the data variable via public methods.
"I think that it’s extraordinarily important that we in computer science keep fun in computing. When it started out it was
an awful lot of fun. Of course the paying customers got shafted every now and then and after a while we began to take their
complaints seriously. We began to feel as if we really were responsible for the successful error-free perfect use of these
machines. I don’t think we are. I think we’re responsible for stretching them setting them off in new directions and
keeping fun in the house. I hope the field of computer science never loses its sense of fun. Above all I hope we don’t
become missionaries. Don’t feel as if you’re Bible sales-men. The world has too many of those already. What you know
about computing other people will learn. Don’t feel as if the key to successful computing is only in your hands. What’s in
your hands I think and hope is intelligence: the ability to see the machine as more than when you were first led up to it
― Alan J. Perlis
108
ANDROID
Linux based operating system currently developed by Google, based on the Linux kernel and designed
primarily for touchscreen mobile devices such as smartphones and tablets -- which empowers millions of
mobile devices such as smartphones and tablet computers across the world ‒ first developed by Android
Inc. (a Palo Alto-based startup company, founded in 2003) and later subsequently acquired by and further
advanced by a coalition of hardware, software and telecommunications companies i.e., open hand set
alliance (a group of 84 technology and mobile companies including Dell, Motorola, Samsung Electronics,
Sony, Intel, LG Electronics, Qualcomm, Broadcom, HTC, Sprint, Texas Instruments and Japanese
wireless carriers KDDI and NTT DoCoMo etc.) ‒ led by Google Inc. and was initially released in
September 23, 2008 under the Apache v2 open source license.
Android Architecture
LINUS KERNEL
Core part / heart of the android operating system ‒ developed by Linus Torvalds in 1991 ‒ which consists
of drivers (i.e., a well-defined set of instructions ‒ what we call programs or software written in C
language that is installed into mobile phones and stored in the form of files in the phone) ‒ that tells your
mobile phone how to communicate with its hardware components such as camera, display etc. ‒ without
which keypad, Bluetooth, Audio, Wi-Fi, Camera won’t work properly and it is responsible for Inter
Process Communication (IPC: a mechanism which allows applications running in different processes to
share data and communicate with each other i.e., a mechanism which allows an application running in a
process to send requests and receive responses from an application running in another process), Power
management (conserves power in the expense of performance and holds the device not to get to sleep
state) and Memory management (make the best or most effective use of memory).
109
Send request
Receive response
LIBRARIES
A collection of prewritten non-volatile data (written in C/ C++ language) and precompiled programming
codes ‒ which support the well-functioning of android operating system.
Libraries include:
Surface Manager/ Screen manager (support the display screen)
OpenGL (Open Graphics Library) ‒ support 3Dimemsional graphics
SGL (Scalable Graphics Library) ‒ support 2Dimensional graphics
Media Framework ‒ support recording and playback of audio and video and image formats
(MP3, JPG, JPEG, PNG, GIF etc.)
Free Type ‒ responsible for font support (i.e., font size, color etc.)
SSL (Secured Sockets layer) / TLS (Transport Layer Security) ‒ responsible for internet security
and support network applications
WebKit ‒ support the display of web pages (i.e., support inbuilt browser)
SQLite ‒ responsible for storage of user data
110
Bionic ‒ standard C library WHICH supports embedded Linux based devices in mobile phones
Core Libraries
+
DVM
This includes Java core libraries (consists of Java packages) and DVM (Dalvik Virtual Machine) ‒
which is responsible to run android application.
Java source code is compiled into Java bytecode which is stored within .class file and the Java bytecode is
read, verified and executed by Java Virtual Machine (JVM). But in the case of Google’s Android
operating system, DVM (Dalvik Virtual Machine) is used instead of JVM because JVM is designed for
desktops and it is too heavy for mobile devices and moreover JVM takes more memory, runs and loads
slower compared to DVM.
111
A software frame work (written in Java language) that supports the features of android applications
Application Frame Work includes:
Content Provider
Notifications Manager
Activity Manager
Window Manager
Location Manager
View manager
Package manager
Telephony manager
XMPP (Extensible Messaging and Presence Protocol)
Resource manager:
Content Provider
Content Provider
Database
(Electronic book)
Data of applications (App 1, App 2 and App 3) are stored in database (which may be SQLite or Files
etc.). If application App 1 requests content provider for the data of the application App 2, then the content
provider fetches the data of the application App 2 and sends to App 1. Thus the data of App 2 is shared by
App 1 THROUGH Content provider.
112
Notifications Manager
Notifications Manager – display alerts and notifications (like low battery, you have got 2 messages, you
have 2 missed calls etc.) to the user.
Activity Manager
Will be opened
Button
If you click on it
If you open your mailbox application, you see number of activities such as inbox, sent, draft etc.
If you click on inbox, then another activity showing the list of inbox mails is opened.
And if you click on one of the inbox mail, then another activity showing the content of inbox mail is
opened.
The activity manager manages and keeps the record of these activities.
Window Manager
Display screen
for video player
Video Player
113
The display screen for the video player application organized by Window Manager
Location Manager
Location Manager provides the periodic updates of the geographical location of the mobile device using
GPS (Global Positioning System which is a satellite-based navigation system) or cell tower.
View manager
User interface
Package manager provide information about the list of installed apps in Android mobile device.
Telephony manager
Telephony manager provide information about the Telephony services (such as phone network, SIM
serial number, IMEI number etc.).
XMPP
XMPP (Extensible Messaging and Presence Protocol) supports online chat application (like yahoo
messenger etc.).
114
Android Chat Application
Y Yahoo!
Resource manager
Where you can store all the non-code resources like images, graphics, videos, audios, animations, pictures
that your application might use as backgrounds etc. ‒ and you can upload these resources to your app.
Applications
Instagram
Facebook
115
Android - Application Components
Activities
If you open your phone application, you see number of activities such as received calls, dialed calls,
missed calls etc.
If you click on received calls, then another activity (i.e., screen showing the list of received calls) is
opened.
And if you click on one of the received call, then another activity showing the information about the
received call (such as the phone number of received call, the time at which it was received etc.) is opened.
And if you want to make a call, another activity showing the number keypad is opened.
Services
If you want the music to play in the background or if you want some video to be downloaded while you
are browsing over the internet ‒ services provide feasibility for the music to play in the background or
video to be downloaded while you are browsing over internet.
Broadcast Receivers
pop up notifications such as low battery, charging, Power got connected to the mobile device, Power got
disconnected from the mobile device, A headset was plugged in, A headset was plugged out.
116
Popup
notification by
broadcast
receiver
Content Providers
If you type a request for the meaning of a word in the search engine of user dictionary application
User dictionary application sends the request to content resolver and the content resolver sends the
request to the content provider and the content provider fetches the information from the database and
directs it to the content provider and then from content provider to content resolver and finally from
content resolver to user application.
Intent
Activity 1 Activity 2
View Photo
When you press view photo, intent (message) is sent to the android operating
system to open another activity (i.e., activity 2) which display the photo
117
Android Virtual Device (AVD) & Emulator
Different android mobile devices possess different configurations. After running and testing your android
application on emulator (the component that allows the testing of android application without the
necessity to install the application on a physical Android based mobile device) you need Android Virtual
Device (AVD) to test whether the application is compatible with a particular android mobile device
configuration before installation of the app into that mobile device.
There is one major step for getting started with Android operation:
You need to download java development kit i.e., JDK (jdk-8u91-windows-x64.exe) from the website
Oracle
http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html
http://developer.android.com/sdk/index.html
And after downloading and installing it into your computer, if you try to open the studio – you will
observe a popup message stating that your JDK does not point to valid installation and your studio will be
forcibly closed. For that you need to follow the following steps:
Open control panel → then open System and Security→ then open System → then open Advanced
system settings → click on Environment variables then a window
118
And if you click on New button—then a window
And restart the system → now open your studio → and follow the option
File → New → New project
And Create New Project window is opened and in create new project window you will see a list of things:
Application name:
Company domain:
Package name:
Project location:
119
Application name: name of the application you are going to create
Because you are going to create Hello Android application,
Application name is Hello Android
Company domain: domain name which you prefer to be associated with your app to preserve its unique
identity in Google play store —without which you cannot generate a package name and without the
package name you cannot distribute your app in the official app store for Android smartphones and tablets
or in the online android market like Google play store.
In this case we just name the
Company domain as manju.example.com
Package name:
Since Company domain is manju.example.com and application name is Hello Android
Package name is:
com. example.manju.Helloandroid (which is autogenerated)
Project location: a file or folder on your hard drive where the newly created application will be stored.
In this case the above project will be stored in the C drive and the path of the project will be as follows:
C:\Users\Manju\AndroidStudioProjects\HelloAndroid
120
Company domain: manju.example.com
Once you have set the application name, company domain and project location, click on the "Next" button
in the lower right corner of the Create New Project window.
Because normally apps are installed into phones and smart phone tablets we select Phones and Tablets
(instead of TV, Glass , Android Auto and Wear). And under Phones and Tablets – we select minimum
SDK (SDK means software development kit): API 10: Android 2.3.3 (GingerBread) because we wish
our app to run on approximately 100.00% of the devices that are active on the Android market. Selection
of minimum SDK is very important because
If you select minimum SDK:
121
Then your app will run on only approximately 96.2% of the mobile devices that are active on the Google
play store.
Then your app will run on approximately 94.8% of the mobile devices that are active on the Google play
store.
After selecting the minimum SDK --click on the "Next" button in the lower right corner of the Target
Android devices window.
And you need to select an activity and click on the "Next" button in the lower right corner of the Add an
activity to mobile window.
122
In this case, we select blank activity
And then a window
Customize the activity
Will be opened
If you click on finish button -- a new window displaying .java and xml file will be opened displaying the
text Hello Android!
123
activity_main.xml
(Layout file)
Design Text
You see
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello Android!" />
124
If you add the statement
android: textAppearance ="?android:attr/textAppearanceSmall"
after the statement
android:text="Hello Android!"
i.e.,
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello Android!"
android: textAppearance ="?android:attr/textAppearanceSmall"
/>
activity_main.xml
(Layout file)
Design Text
by the statement
125
Then the font size of Hello Android! will be medium.
by the statement
android:textStyle="bold"
i.e.,
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello Android!"
android:textStyle="bold"
/>
126
activity_main.xml
(Layout file)
Design Text
127
android:textStyle="bold"
i.e.,
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello Android!"
android: textAppearance ="?android:attr/textAppearanceSmall"
android:textStyle="bold"
android:textColor="#33b5e5"/>
If you replace
#33b5e5
by #33b565
128
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello Android!"
android: textAppearance ="?android:attr/textAppearanceSmall"
android:textStyle="bold"
android:textColor="#33b5e5"
android:textSize="50sp"/>
Horizontal
Hello Android!
Vertical
android:layout_centerHorizontal="true"
i.e.,
<TextView
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="Hello Android!"
129
android: textAppearance ="?android:attr/textAppearanceSmall"
android:textStyle="bold"
android:textColor="#33b5e5"
android:textSize="50sp"/>
Hello Android!
Horizontal center
Hello Android!
Vertical center
130
Hello Android!
Hello Android! 69 dp
Hello Android! 80 dp
Hello Android! 100 dp
131
What will be the output on the screen if:
<TextView
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp”
android:text="Hello Android!"
android: textAppearance ="?android:attr/textAppearanceSmall"
android:textStyle="bold"
android:textColor="#33b5e5"
android:textSize="50sp"
/>
<TextView
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="60dp”
android:text="Hello!"
android: textAppearance ="?android:attr/textAppearanceLarge"
android:textStyle="bold|italic"
android:textColor="#33b575"
android:textSize="90sp"/>
Answer:
Hello Android!
Hello!
132
SQL (Structured Query Language) — a standard interactive and programming language for
getting information from a database
SQLite – database
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft ="true"
android:layout_marginTop="30dp"
android:text="Hello Android!"
android:textAppearance ="?android:attr/textAppearanceSmall"
android:textStyle="bold"
android:textColor="#33b5e5"
android:textSize="25sp"/>
is written instead of
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:text="Hello Android!"
android:textAppearance ="?android:attr/textAppearanceSmall"
android:textStyle="bold"
android:textColor="#33b5e5"
android:textSize="25sp"/>
133
Hello Android!
Left
android:layout_centerHorizontal="true"
by the statement
android:layout_alignParentRight ="true"
Hello Android!
Right
134
If you replace the statement
android:layout_centerHorizontal="true"
by the statement
android:layout_alignParentBottom ="true"
android:layout_alignParentBottom ="true"
by the statement
android:layout_alignParentTop ="true"
Then the text Hello Android! will become visible on the screen.
First you need to create a raw folder and for that you need to follow the following steps:
Open Android studio and you will see the following screen:
135
If you select packages then you will see
If you select new and click on it and select Android resource directory and click on it – a new resource
directory window will be opened
After clicking on ok button, a new folder named raw will be created and you can see it as shown in the
figure below:
136
Now you copy the image (i.e., image_name.jpg) from the desktop and paste in the newly created folder
(i.e., in raw folder) and open .xml file and paste the following code:
<ImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:src="@raw/image_name" />
image_name.jpg
If you want to drag the image downwards, then you have to add the statement
android:layout_marginTop="100dp"
137
after the statement
android:layout_height="wrap_content"
i.e.,
<ImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:src="@raw/image_name" />
android:layout_marginTop="100dp"
by the statement
android:layout_marginTop="200dp"
Position of image
corresponding to
Position of image
100dp
corresponding to
200dp
Suppose if you have copied the image (i.e., image_name.jpg) from the desktop and pasted it in the
drawable folder, then you need to replace the statement
android:src="@raw/image_name"
by the statement
138
android:src="@drawable/image_name"
otherwise no image will be displayed on the screen (because you have saved the image in drawable folder
not in the raw folder).
Note:
Suppose if you copy the image from the desktop and paste it in the layout folder, then you have to replace
the statement
android:src="@raw/image_name"
by the statement
android:src="@layout/image_name"
image will be displayed on the screen but when you try to build / generate the .apk file (i.e., .Android
application package file), error will be displayed on the screen stating that
Build failed
i.e.,
139
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginTop="100dp"
android:src="@raw/image_name" />
To drag the image to the center you need to add the following code:
android:layout_centerHorizontal="true"
i.e.,
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp"
android:src="@raw/image_name" />
First you need to copy the video (i.e., video.mp4) from the desktop and paste it in the raw folder and then
you have to replace the existing codes in activity_main.xml file by the following codes:
140
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.manju.Helloandroid.MainActivity">
<VideoView
android:id="@+id/videoView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:background="@android:color/transparent" />
</RelativeLayout>
and after replacing the above codes in activity_main .xml file, you need to replace the existing codes
below package name (i.e., com.example.manju.Helloandroid) in MainActivity.java by the following
codes:
import android.graphics.PixelFormat;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.MediaController;
import android.widget.VideoView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonPlayVideo2 = (Button) findViewById(R.id.button1);
141
getWindow().setFormat(PixelFormat.UNKNOWN);
//displays a video file
VideoView mVideoView2 = (VideoView) findViewById(R.id.videoView1);
String uriPath2 = "android.resource://com.example.manju.Helloandroid/" +
R.raw.bvideo;
Uri uri2 = Uri.parse(uriPath2);
mVideoView2.setVideoURI(uri2);
mVideoView2.requestFocus();
mVideoView2.start();
buttonPlayVideo2.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
VideoView mVideoView2 = (VideoView) findViewById(R.id.videoView1);
// VideoView mVideoView = new VideoView(this);
String uriPath = "android.resource://com.example.manju.Helloandroid/"
+ R.raw.video;
Uri uri2 = Uri.parse(uriPath);
mVideoView2.setVideoURI(uri2);
mVideoView2.requestFocus();
mVideoView2.start();
}
});
}
}
Then if you run the application − video will be played on the emulator as shown in the figure below.
Video
playing on
the emulator
142
If you replace the statements
android:layout_width="wrap_content"
android:layout_height="wrap_content"
by the statements
android:layout_width="500px"
android:layout_height="500px"
Video screen is
reduced because
of the code:
Note:
If you replace the file video.mp4 in the raw folder by the file music.mp3, then you should rewrite the
above codes after the package name in .java file as follows:
import android.graphics.PixelFormat;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.MediaController;
import android.widget.VideoView;
143
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonPlayVideo2 = (Button) findViewById(R.id.button1);
getWindow().setFormat(PixelFormat.UNKNOWN);
//displays a video file
VideoView mVideoView2 = (VideoView) findViewById(R.id.videoView1);
String uriPath2 = "android.resource://com.example.manju.helloandroid/" +
R.raw.music;
Uri uri2 = Uri.parse(uriPath2);
mVideoView2.setVideoURI(uri2);
mVideoView2.requestFocus();
mVideoView2.start();
buttonPlayVideo2.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
VideoView mVideoView2 = (VideoView) findViewById(R.id.videoView1);
// VideoView mVideoView = new VideoView(this);
String uriPath = "android.resource://com.example.manju.helloandroid/"
+ R.raw.music;
Uri uri2 = Uri.parse(uriPath);
mVideoView2.setVideoURI(uri2);
mVideoView2.requestFocus();
mVideoView2.start();
}
});
}
}
Then the output on the screen is:
144
Note:
If you add the following code in .xml file:
<ImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:src="@raw/image_name" />
Button1
First Activity:
145
First you need to replace the existing codes after the package name in Mainactivity.java file by the
following codes:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.content.Intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
{
Intent i = new Intent(MainActivity.this, Display.class);
startActivity(i);
}
}
}
And you need to replace the existing codes in activity_main. xml by the following codes:
<Button
146
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button1"
android:id="@+id/Bdisplay"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="177dp"
android:onClick="onButtonClick" />
</RelativeLayout>
Second Activity:
And Go to packages and under packages select Main activity → right click on it → select New → and
select Java class
Then
And go to Layout and under layout select activity_main. xml and right click on it → select New → and
select → XmL → and select Layout xml file.
Will be opened
Creates a new xml layout file
147
And you should place the following codes in Display.java file:
/**
* Created by Manju on 3/17/2016.
*/
public class Display extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display);
}
}
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Our new activity has started"
android:id="@+id/textView" />
</LinearLayout>
And you should add the following code in android manifest.xml file:
<application
android:allowBackup="true"
148
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
button 1 button 2
First Activity:
First you need to replace the existing codes after the package name in Mainactivity.java file by the
following codes:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.content.Intent;
149
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
{
Intent i = new Intent(MainActivity.this, Display.class);
startActivity(i);
}
}
}
And you need to replace the existing codes in activity_main. xml by the following codes:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button1"
android:id="@+id/Bdisplay"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="177dp"
android:onClick="onButtonClick" />
</RelativeLayout>
150
Second Activity:
Go to packages and under packages select Mainactivity.java → right click on it → select New → and
select Java class
Then
And Go to packages and under packages select Main activity → right click on it → select New → and
select Java class
Then
And go to Layout and under layout select activity_main. xml and right click on it → select New → and
select → XmL → and select Layout xml file.
Will be opened
Creates a new xml layout file
And you should open the Display.java file and rewrite the existing codes by the following codes:
151
import android. app. Activity;
import android.os.Bundle;
import android.view.View;
import android.content.Intent;
/**
* Created by Manju on 3/17/2016.
*/
public class Display extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display);
{
Intent i = new Intent(Display.this, File.class);
startActivity(i);
}
And you should open the display.xml file and rewrite the existing codes by the following codes:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button2"
android:id="@+id/Bfile"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
152
android:layout_marginBottom="177dp"
android:onClick="onButtonClick" />
</LinearLayout>
Third Activity:
And Go to packages and under packages select Display.java → right click on it → select New → and
select Java class
Then
And go to Layout and under layout select display. xml and right click on it → select New → and select →
XmL → and select Layout xml file.
Will be opened
Creates a new xml layout file
import android.app.Activity;
import android.os.Bundle;
153
/**
* Created by Manju on 3/21/2016.
*/
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Our new activity is running"
android:id="@+id/textView" />
</LinearLayout>
And you should add the following codes in android manifest.xml file:
i.e.,
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
154
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.content.Intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
155
setContentView(R.layout.activity_main);
}
{
Intent i = new Intent(MainActivity.this, Display.class);
startActivity(i);
}
if (v.getId() == R.id.Bmanju)
{
Intent i = new Intent(MainActivity.this, Manju.class);
startActivity(i);
}
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="button 1"
android:id="@+id/Bdisplay"
android:onClick="onButtonClick"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<Button
156
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="button 2"
android:id="@+id/Bmanju"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="177dp"
android:onClick="onButtonClick" />
</RelativeLayout>
And go to Mainactivity.java → right click on it → select New → and select Java class
Then
And again go to Mainactivity.java → right click on it → select New → and select Java class
Then
157
And go to Layout and under layout select main_activity. xml and right click on it → select New → and
select → XmL → and select Layout xml file.
Will be opened
Creates a new xml layout file
And again go to Layout and under layout select main_activity. xml and right click on it → select New →
and select → XmL → and select Layout xml file.
Will be opened
Creates a new xml layout file
/**
* Created by Manju on 3/17/2016.
158
*/
public class Display extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display);
}
}
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Our new activity has started"
android:id="@+id/textView" />
</LinearLayout>
import android.os.Bundle;
import android. app. Activity;
/**
* Created by Manju on 3/28/2016.
*/
public class Manju extends Activity{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.manju);
}
}
159
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Our new activity has ended"
android:id="@+id/textView" />
</LinearLayout>
And in android manifest file you have to add the following codes:
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</application>
Note:
If the program:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
160
import android.view.View;
import android.content.Intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
{
Intent i = new Intent(MainActivity.this, Display.class);
startActivity(i);
}
if (v.getId() == R.id.Bmanju)
{
Intent i = new Intent(MainActivity.this, Manju.class);
startActivity(i);
}
is rewritten as:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.content.Intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
161
public void onButtonClick(View v) {
if (v.getId() == R.id.Bdisplay)
{
Intent i = new Intent(MainActivity.this, Display.class);
startActivity(i);
}
}
{
Intent i = new Intent(MainActivity.this, Manju.class);
startActivity(i);
}
}
}
Then execution error will be displayed on the Emulator or force shut down will result because method
is declared twice.
Go to build → then select build apk → Gradle build starts → apk files are generated in few minutes →
install and run it on your android mobile set.
Note:
In order to sell your app on Google play -- you need to generate signed apk file for that:
162
Then go to build → select generate signed apk→ then you will see
Then you see New key store window → then fill the details – for example
163
Note: always select Validity (years) > 25 years because in order to publish your app in Google play you
need to select minimum years of 25.
After filling the details you press OK → then you will see GENERATE SIGNED APK window will be
opened → press next → then you need to fill the master password (note: you need to remember master
password because it is only the evidence the Google play will verify whether you are going to publish
your app or not) → after filling the master password , then click on finish → after few minutes of Gradle
building → you see the apk file in show folder.
button 1
First you need to open the manifest file and add the statement
and you need to replace the existing codes in .xml file by the following codes:
<Button
android:layout_width="wrap_content"
164
android:layout_height="wrap_content"
android:text="Browser"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="177dp"
android:onClick="browser1" />
</LinearLayout>
And you should modify the codes below the package name in MainActivity.java as follows:
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void browser1(View view){
Intent browserIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse("http://google.com.kh"));
startActivity(browserIntent);
}
}
Suppose you want to add two buttons (i.e., if you click on button 1, Google website should be opened and
if you click on button 2, facebook website should be opened)
165
Then
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void browser1(View view){
Intent browserIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse("http://google.com.kh"));
startActivity(browserIntent);
166
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Browser"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="177dp"
android:onClick="browser1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Browser2"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="130dp"
android:onClick="browser2" />
</LinearLayout>
First you NEED to open the manifest file and add the statement
and you need to replace the existing codes in activity_main. xml file by the following codes:
<Button
android:id="@+id/buttonCall"
android:layout_width="wrap_content"
167
android:layout_height="wrap_content"
android:text="Call1"
android:layout_alignParentBottom="true"
android:layout_marginBottom="200dp"
android:onClick="call" />
<Button
android:id="@+id/buttonCall1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Call2"
android:layout_alignParentBottom="true"
android:layout_marginBottom="150dp"
android:onClick="call" />
</LinearLayout>
And you should modify the codes below the package name in MainActivity.java file as follows:
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android. view. View.OnClickListener;
168
button = (Button) findViewById(R.id.buttonCall1);
button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" +
"020000000"));
startActivity(callIntent);
}
});
First you need to open the manifest file and add the statement
<Button
android:id="@+id/buttonSMS"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="sms"
android:layout_alignParentBottom="true"
169
android:layout_marginBottom="200dp"
android:onClick="SMS" />
And you should modify the codes below the package name in MainActivity.java file as follows:
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android. view. View.OnClickListener;
}
}
Suppose you want to add two buttons (i.e., if you click on button 1, sms should be sent to one number and
if you click on button 2, sms should be sent to another number)
Then
170
Your .java file should take the form:
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android. view. View.OnClickListener;
171
<Button
android:id="@+id/buttonSMS"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="sms"
android:layout_alignParentBottom="true"
android:layout_marginBottom="200dp"
android:onClick="SMS" />
<Button
android:id="@+id/buttonSMS1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="sms1"
android:layout_alignParentBottom="true"
android:layout_marginBottom="150dp"
android:onClick="SMS" />
Calculator
172
<EditText
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginLeft="5pt"
android:id="@+id/etNum2"
android:layout_width="match_parent"
android:inputType="numberDecimal">
</EditText>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/linearLayout2"
android:layout_marginTop="3pt"
android:layout_marginLeft="5pt"
android:layout_marginRight="5pt">
<Button
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_weight="1"
android:text="+"
android:textSize="8pt"
android:id="@+id/btnAdd">
</Button>
<Button
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_weight="1"
android:text="-"
android:textSize="8pt"
android:id="@+id/btnSub">
</Button>
<Button
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_weight="1"
android:text="*"
android:textSize="8pt"
android:id="@+id/btnMult">
</Button>
<Button
173
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_weight="1"
android:text="/"
android:textSize="8pt"
android:id="@+id/btnDiv">
</Button>
</LinearLayout>
<TextView
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_marginLeft="5pt"
android:layout_marginRight="5pt"
android:textSize="12pt"
android:layout_marginTop="3pt"
android:id="@+id/tvResult"
android:gravity="center_horizontal">
</TextView>
</LinearLayout>
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Bundle;
import android.app.Activity;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
EditText etNum1;
EditText etNum2;
Button btnAdd;
Button btnSub;
174
Button btnMult;
Button btnDiv;
TextView tvResult;
// set a listener
btnAdd.setOnClickListener((OnClickListener) this);
btnSub.setOnClickListener(this);
btnMult.setOnClickListener(this);
btnDiv.setOnClickListener(this);
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
float num1 = 0;
float num2 = 0;
float result = 0;
175
// read EditText and fill variables with numbers
num1 = Float.parseFloat(etNum1.getText().toString());
num2 = Float.parseFloat(etNum2.getText().toString());
// defines the button that has been clicked and performs the corresponding
operation
// write operation into oper, we will use it later for output
switch (v.getId()) {
case R.id.btnAdd:
oper = "+";
result = num1 + num2;
break;
case R.id.btnSub:
oper = "-";
result = num1 - num2;
break;
case R.id.btnMult:
oper = "*";
result = num1 * num2;
break;
case R.id.btnDiv:
oper = "/";
result = num1 / num2;
break;
default:
break;
}
How to get location (latitude and longitude values) and city name?
import android.os.Bundle;
import android.app.Activity;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
176
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
177
pb = (ProgressBar) findViewById(R.id.progressBar1);
pb.setVisibility(View.INVISIBLE);
locationMangaer = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
@Override
public void onClick(View v) {
flag = displayGpsStatus();
if (flag) {
Log.v(TAG, "onClick");
pb.setVisibility(View.VISIBLE);
locationListener = new MyLocationListener();
locationMangaer.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
5000, 10,locationListener);
} else {
alertbox("Gps Status!!", "Your NETWORK is: OFF");
}
178
return true;
} else {
return false;
}
}
editLocation.setText("");
pb.setVisibility(View.INVISIBLE);
Toast.makeText(getBaseContext(),"Location changed : Lat: " +
loc.getLatitude()+ " Lng: " + loc.getLongitude(),
179
Toast.LENGTH_SHORT).show();
String longitude = "Longitude: " +loc.getLongitude();
Log.v(TAG, longitude);
String latitude = "Latitude: " +loc.getLatitude();
Log.v(TAG, latitude);
String s = longitude+"\n"+latitude +
"\n\nCity name is: "+cityName;
editLocation.setText(s);
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider,
int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}
180
Code that you need to add in the manifest file:
181
<LinearLayout
android:id="@+id/layloadingH"
android:layout_height="wrap_content"
android:layout_weight="0.20"
android:layout_width="fill_parent"
android:gravity="center">
<ProgressBar
android:layout_width="wrap_content"
android:id="@+id/progressBar1"
android:layout_height="wrap_content"></ProgressBar>
</LinearLayout>
</LinearLayout>
Note:
Suppose if you want to add the clock and text time to your app then your .xml file should take the form:
<TextClock
android:layout_width="82dp"
android:layout_height="43dp"
android:id="@+id/textClock"
android:layout_gravity="center_horizontal" />
<AnalogClock
android:layout_width="100dp"
android:layout_height="100dp"
android:id="@+id/analogClock"
182
android:layout_gravity="center_horizontal"
android:layout_weight="0.20" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.33"
android:id="@+id/editTextLocation"
android:editable="false">
<requestFocus></requestFocus>
</EditText>
<LinearLayout
android:id="@+id/layButtonH"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:gravity="center"
android:layout_weight="0.15">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Location"
android:id="@+id/btnLocation"></Button>
</LinearLayout>
<LinearLayout
android:id="@+id/layloadingH"
android:layout_height="wrap_content"
android:layout_weight="0.20"
android:layout_width="fill_parent"
android:gravity="center">
<ProgressBar
android:layout_width="wrap_content"
android:id="@+id/progressBar1"
android:layout_height="wrap_content"></ProgressBar>
</LinearLayout>
</LinearLayout>
How to get location and address line, country name, postal code etc.?
import android.os.Bundle;
import android.app.Activity;
183
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
184
//if you want to lock screen for always Portrait mode
setRequestedOrientation(ActivityInfo
.SCREEN_ORIENTATION_PORTRAIT);
pb = (ProgressBar) findViewById(R.id.progressBar1);
pb.setVisibility(View.INVISIBLE);
locationMangaer = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
@Override
public void onClick(View v) {
flag = displayGpsStatus();
if (flag) {
Log.v(TAG, "onClick");
pb.setVisibility(View.VISIBLE);
locationListener = new MyLocationListener();
locationMangaer.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
5000, 10,locationListener);
} else {
alertbox("Gps Status!!", "Your NETWORK is: OFF");
}
185
boolean gpsStatus = Settings.Secure
.isLocationProviderEnabled(contentResolver,
LocationManager.NETWORK_PROVIDER);
if (gpsStatus) {
return true;
} else {
return false;
}
}
186
editLocation.setText("");
pb.setVisibility(View.INVISIBLE);
Toast.makeText(getBaseContext(),"Location changed : Lat: " +
loc.getLatitude()+ " Lng: " + loc.getLongitude(),
Toast.LENGTH_SHORT).show();
String longitude = "Longitude: " +loc.getLongitude();
Log.v(TAG, longitude);
String latitude = "Latitude: " +loc.getLatitude();
Log.v(TAG, latitude);
String s = longitude+"\n"+latitude +
"\n\n "+ L + "\n\n " + M + "\n\n " + N +"\n\n " + O + "\n\n
"+ P + "\n\n " + Q + "\n\n "+ A;
editLocation.setText(s);
}
187
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider,
int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}
import java.util.Calendar;
import java.util.Date;
import android.app.Activity;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
Button btnCTime;
TextView txtCTime;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
188
btnCTime=(Button)findViewById(R.id.btnGenCurTime);
txtCTime=(TextView)findViewById(R.id.txtShowCurTime);
txtCTime.setInputType(InputType.TYPE_NULL);
btnCTime.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View vw) {
txtCTime.setText(new Date().toString());
}
});
}
}
<TextView
android:id="@+id/txtShowCurTime"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<requestFocus />
</TextView>
<Button
android:id="@+id/btnGenCurTime"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="date" />
</LinearLayout>
import android.content.Intent;
import android.os.Bundle;
189
import android.support.v7.app.AppCompatActivity;
import android.view.View;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="whatsapp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="177dp"
android:onClick="browser1" />
Note: you have to download whatsapp application from the website: www.whatsapp.com and install it
into your phone – then the output on the screen is:
190
How to set image in background?
First you need to copy the image file (say image_name.jpg) and paste into drawable folder
android:weightSum="1">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="whatsapp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="177dp"
android:onClick="browser1" />
</LinearLayout>
Scientific CALCULATOR
191
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Bundle;
import android.app.Activity;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
EditText etNum1;
Button btnsqrt;
Button btncbrt;
Button btnln;
Button btnlog;
Button btnexp;
Button btnsin;
Button btncos;
Button btntan;
Button btnreci;
Button btncosec;
Button btnsec;
Button btncot;
Button btnsquare;
Button btncube;
Button btnfacto;
TextView tvResult;
192
etNum1 = (EditText) findViewById(R.id.etNum1);
// set a listener
btnsqrt.setOnClickListener((OnClickListener) this);
btncbrt.setOnClickListener(this);
btnln.setOnClickListener(this);
btnlog.setOnClickListener(this);
btnexp.setOnClickListener(this);
btnsin.setOnClickListener(this);
btncos.setOnClickListener(this);
btntan.setOnClickListener(this);
btnreci.setOnClickListener(this);
btncosec.setOnClickListener(this);
btnsec.setOnClickListener(this);
btncot.setOnClickListener(this);
btnsquare.setOnClickListener(this);
btncube.setOnClickListener(this);
btnfacto.setOnClickListener(this);
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
193
double num1 = 0;
double result = 0;
// defines the button that has been clicked and performs the corresponding
operation
// write operation into oper, we will use it later for output
switch (v.getId()) {
case R.id.btnsqrt:
oper = "sqrt";
result = Math.sqrt(num1) ;
break;
case R.id.btncbrt:
oper = "cbrt";
result = Math.cbrt(num1);
break;
case R.id.btnln:
oper = "ln";
result = Math.log(num1);
break;
case R.id.btnlog:
oper = "log";
result = Math.log10(num1);
break;
case R.id.btnexp:
oper = "exp";
result = Math.exp(num1);
break;
case R.id.btnsin:
oper = "sin";
result = Math.sin(num1);
break;
case R.id.btncos:
oper = "cos";
result = Math.cos(num1);
break;
194
case R.id.btntan:
oper = "tan";
result = Math.tan(num1);
break;
case R.id.btnreci:
oper = "1/x";
result = 1/num1;
break;
case R.id.btncosec:
oper = "cosec";
result = 1/Math.sin(num1);
break;
case R.id.btnsec:
oper = "sec";
result = 1/ Math.cos(num1);
break;
case R.id.btncot:
oper = "cot";
result = 1/Math.tan(num1);
break;
case R.id.btnsquare:
oper = "square";
result = num1 * num1;
break;
case R.id.btncube:
oper = "cube";
result = num1 * num1 * num1;
break;
case R.id.btnfacto:
oper = "fact";
int i, fact =1;
for(i=1;i<=num1;i++)
fact = fact *i;
result = fact;
break;
default:
break;
}
195
code in activity_main.xml file
<Button
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_weight="1"
android:text="sqrt"
android:textSize="8pt"
android:id="@+id/btnsqrt">
</Button>
<Button
196
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_weight="1"
android:text="cbrt"
android:textSize="8pt"
android:id="@+id/btncbrt">
</Button>
<Button
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_weight="1"
android:text="ln"
android:textSize="8pt"
android:id="@+id/btnln">
</Button>
<Button
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_weight="1"
android:text="log"
android:textSize="8pt"
android:id="@+id/btnlog">
</Button>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/linearLayout2"
android:layout_marginTop="3pt"
android:layout_marginLeft="5pt"
android:layout_marginRight="5pt">
<Button
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_weight="1"
android:text="exp"
android:textSize="8pt"
android:id="@+id/btnexp">
197
</Button>
<Button
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_weight="1"
android:text="sin"
android:textSize="8pt"
android:id="@+id/btnsin">
</Button>
<Button
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_weight="1"
android:text="cos"
android:textSize="8pt"
android:id="@+id/btncos">
</Button>
<Button
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_weight="1"
android:text="tan"
android:textSize="8pt"
android:id="@+id/btntan">
</Button>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/linearLayout2"
android:layout_marginTop="3pt"
android:layout_marginLeft="5pt"
android:layout_marginRight="5pt">
<Button
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_weight="1"
android:text="1/x"
android:textSize="8pt"
198
android:id="@+id/btnreci">
</Button>
<Button
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_weight="1"
android:text="cosec"
android:textSize="8pt"
android:id="@+id/btncosec">
</Button>
<Button
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_weight="1"
android:text="sec"
android:textSize="8pt"
android:id="@+id/btnsec">
</Button>
<Button
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_weight="1"
android:text="cot"
android:textSize="8pt"
android:id="@+id/btncot">
</Button>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/linearLayout2"
android:layout_marginTop="3pt"
android:layout_marginLeft="5pt"
android:layout_marginRight="5pt">
<Button
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_weight="1"
199
android:text="square"
android:textSize="8pt"
android:id="@+id/btnsquare">
</Button>
<Button
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_weight="1"
android:text="cube"
android:textSize="8pt"
android:id="@+id/btncube">
</Button>
<Button
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_weight="1"
android:text="factorial"
android:textSize="8pt"
android:id="@+id/btnfacto">
</Button>
</LinearLayout>
Get Information about model number, API level, android version etc.
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.widget.TextView;
TextView text;
200
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ModelNumber = android.os.Build.MODEL;
Board = android.os.Build.BOARD;
Brand = android.os.Build.BRAND;
Display = android.os.Build.DISPLAY;
FingerPrint = android.os.Build.FINGERPRINT;
ID = android.os.Build.ID;
TAGS = android.os.Build.TAGS;
Type = android.os.Build.TYPE;
AndroidVersion = android.os.Build.VERSION.RELEASE;
APILevel = android.os.Build.VERSION.SDK;
CodeName = android.os.Build.VERSION.CODENAME;
INCREMENTAL = android.os.Build.VERSION.INCREMENTAL;
text.setText(Html.fromHtml("Phone Type" +
"<br/><br/><font color = 'red';>Model Number : </font></font>" +
ModelNumber
+ "<br/><font color = 'red';>Board : </font>" + Board
+ "<br/><font color = 'red';>Brand : </font>" + Brand
+ "<br/><font color = 'red';>Display : </font>" + Display
+ "<br/><font color = 'red';>FingerPrint : </font>" + FingerPrint
+ "<br/><font color = 'red';>ID : </font>" + ID
+ "<br/><font color = 'red';>TAGS : </font>" + TAGS
+ "<br/><font color = 'red';>Type : </font>" + Type
+ "<br/>"
201
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/textView2"
android:textColor="#4169E1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10sp"
android:layout_marginTop="20sp" />
</RelativeLayout>
How to take a photo and save it in gallery / SD card / image file in android?
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
202
setContentView(R.layout.activity_main);
imgView = (ImageView) findViewById(R.id.imageView1);
btnCamera = (Button) findViewById(R.id.btn_camera);
btnCamera.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
// ******** code for take image
intent.putExtra(MediaStore.EXTRA_OUTPUT,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI.toString());
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, CAMERA_REQUEST);
} catch (ActivityNotFoundException e) {
// Do nothing for now
}
}
});
}
203
<?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" >
<Button
android:id="@+id/btn_camera"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Take image" />
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
</LinearLayout>
IEMI number
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.telephony.TelephonyManager;
import android.widget.TextView;
TelephonyManager tel;
TextView imei;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
204
imei = (TextView) findViewById(R.id.textView2);
imei.setText(tel.getDeviceId().toString());
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:textColor="#4169E1"
android:textSize="18sp"
android:text="IMEI Number" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textSize="15sp"
android:text="IMEI" />
</RelativeLayout>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
Gallery Creation
205
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher.ViewFactory;
int imgs[] =
{
R.drawable.image_name,
R.drawable.image_name1,
};
ImageSwitcher imgSwitcher;
gallery.setOnItemClickListener(new OnItemClickListener() {
206
public void onItemClick(AdapterView<?> arg0, View arg1, int
arg2,
long arg3) {
imgSwitcher.setImageResource(imgs[arg2]);
}
});
}
public ImageAdapter(Context c) {
ctx = c;
}
return imgs.length;
}
return arg0;
}
return arg0;
}
207
iView.setLayoutParams(new ImageSwitcher.LayoutParams
(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
iView.setBackgroundColor(0xFF000000);
return iView;
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Gallery
android:id="@+id/gallery1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true" />
<ImageSwitcher
android:id="@+id/imageSwitcher1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="@+id/gallery1"
android:layout_centerHorizontal="true"
android:layout_marginTop="5dp" >
</ImageSwitcher>
</RelativeLayout>
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.widget.TextView;
208
TextView cityField, detailsField, currentTemperatureField, humidity_field,
pressure_field, weatherIcon, updatedField;
Typeface weatherFont;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_main);
weatherFont = Typeface.createFromAsset(getApplicationContext().getAssets(),
"fonts/weathericons-regular-webfont.ttf");
cityField = (TextView)findViewById(R.id.city_field);
updatedField = (TextView)findViewById(R.id.updated_field);
detailsField = (TextView)findViewById(R.id.details_field);
currentTemperatureField =
(TextView)findViewById(R.id.current_temperature_field);
humidity_field = (TextView)findViewById(R.id.humidity_field);
pressure_field = (TextView)findViewById(R.id.pressure_field);
weatherIcon = (TextView)findViewById(R.id.weather_icon);
weatherIcon.setTypeface(weatherFont);
cityField.setText(weather_city);
updatedField.setText(weather_updatedOn);
detailsField.setText(weather_description);
currentTemperatureField.setText(weather_temperature);
humidity_field.setText("Humidity: "+weather_humidity);
pressure_field.setText("Pressure: "+weather_pressure);
weatherIcon.setText(Html.fromHtml(weather_iconText));
}
});
asyncTask.execute(
209
"25.223666 ", "-12.3669858"); // asyncTask.execute("Latitude", "Longitude")
}
}
import android.app.Activity;
import android.os.AsyncTask;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
"http://api.openweathermap.org/data/2.5/weather?lat=%s&lon=%s&units=metric";
210
case 2 : icon = "";
break;
case 3 : icon = "";
break;
case 7 : icon = "";
break;
case 8 : icon = "";
break;
case 6 : icon = "";
break;
case 5 : icon = "";
break;
}
}
return icon;
}
@Override
protected JSONObject doInBackground(String... params) {
211
return jsonWeather;
}
@Override
protected void onPostExecute(JSONObject json) {
try {
if(json != null){
JSONObject details =
json.getJSONArray("weather").getJSONObject(0);
JSONObject main = json.getJSONObject("main");
DateFormat df = DateFormat.getDateTimeInstance();
String city = json.getString("name").toUpperCase(Locale.US) + ", "
+ json.getJSONObject("sys").getString("country");
String description =
details.getString("description").toUpperCase(Locale.US);
String temperature = String.format("%.2f",
main.getDouble("temp"))+ "°";
String humidity = main.getString("humidity") + "%";
String pressure = main.getString("pressure") + " hPa";
String updatedOn = df.format(new Date(json.getLong("dt")*1000));
String iconText = setWeatherIcon(details.getInt("id"),
json.getJSONObject("sys").getLong("sunrise") * 1000,
json.getJSONObject("sys").getLong("sunset") * 1000);
}
} catch (JSONException e) {
//Log.e(LOG_TAG, "Cannot process JSON results", e);
}
}
}
212
HttpURLConnection connection =
(HttpURLConnection)url.openConnection();
connection.addRequestProperty("x-api-key", OPEN_WEATHER_MAP_API);
return data;
}catch(Exception e){
return null;
}
}
<?xml version="1.0"?>
<RelativeLayout
android:padding="20dp"
android:background="#3F51B5"
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView android:layout_height="wrap_content"
213
android:layout_width="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FFFFFF"
android:layout_centerHorizontal="true"
android:layout_alignParentTop="true"
android:id="@+id/city_field"/>
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF"
android:layout_centerHorizontal="true"
android:id="@+id/updated_field"
android:textSize="13sp"
android:layout_below="@+id/city_field"/>
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FFFFFF"
android:layout_centerHorizontal="true"
android:id="@+id/weather_icon"
android:textSize="90sp"
android:layout_centerVertical="true"/>
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FFFFFF"
android:layout_centerHorizontal="true"
android:id="@+id/current_temperature_field"
android:textSize="50sp"
android:layout_alignParentBottom="true"/>
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF"
android:layout_centerHorizontal="true"
android:id="@+id/details_field"
214
android:layout_below="@+id/weather_icon"/>
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF"
android:layout_centerHorizontal="true"
android:id="@+id/humidity_field"
android:layout_below="@+id/details_field"/>
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF"
android:layout_centerHorizontal="true"
android:id="@+id/pressure_field"
android:layout_below="@+id/humidity_field"/>
</RelativeLayout>
<uses-permission android:name="android.permission.INTERNET"/>
MainActivity.java:
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
215
Button b1,b2;
EditText ed1,ed2;
TextView tx1;
int counter = 3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.button);
ed1=(EditText)findViewById(R.id.editText);
ed2=(EditText)findViewById(R.id.editText2);
b2=(Button)findViewById(R.id.button2);
tx1=(TextView)findViewById(R.id.textView3);
tx1.setVisibility(View.GONE);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(ed1.getText().toString().equals("admin") &&
ed2.getText().toString().equals("admin")) {
Toast.makeText(getApplicationContext(),
"Redirecting...",Toast.LENGTH_SHORT).show();
else{
Toast.makeText(getApplicationContext(), "Wrong
Credentials",Toast.LENGTH_SHORT).show();
tx1.setVisibility(View.VISIBLE);
tx1.setBackgroundColor(Color.RED);
counter--;
tx1.setText(Integer.toString(counter));
if (counter == 0) {
216
b1.setEnabled(false);
}
}
}
});
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
Display.java:
217
public class Display extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display);
}
}
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point"
android:id="@+id/textView"
android:layout_below="@+id/textview"
android:layout_centerHorizontal="true"
android:textColor="#ff7aff24"
android:textSize="35dp" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:hint="Enter Name"
android:focusable="true"
android:textColorHighlight="#ff7eff15"
218
android:textColorHint="#ffff25e6"
android:layout_marginTop="46dp"
android:layout_below="@+id/imageView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/ic_launcher"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:id="@+id/editText2"
android:layout_below="@+id/editText"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignRight="@+id/editText"
android:layout_alignEnd="@+id/editText"
android:textColorHint="#ffff299f"
android:hint="Password" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Attempts Left:"
android:id="@+id/textView2"
android:layout_below="@+id/editText2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textSize="25dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
219
android:id="@+id/textView3"
android:layout_alignTop="@+id/textView2"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignBottom="@+id/textView2"
android:layout_toEndOf="@+id/textview"
android:textSize="25dp"
android:layout_toRightOf="@+id/textview" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="login"
android:id="@+id/button"
android:layout_alignParentBottom="true"
android:layout_toLeftOf="@+id/textview"
android:layout_toStartOf="@+id/textview"
android:onClick="onClick"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cancel"
android:id="@+id/button2"
android:layout_alignParentBottom="true"
android:layout_toRightOf="@+id/textview"
android:layout_toEndOf="@+id/textview" />
</RelativeLayout>
display.xml:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
220
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Our new activity has started"
android:id="@+id/textView" />
</LinearLayout>
String.xml file:
<resources>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
</resources>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
221
How to create LOGOUT and EXIT IN Android
Display.java:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display);
}
public void logout(View view){
Intent i = new Intent(Display.this, MainActivity.class);
startActivity(i);
}
display.xml:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".Display" >
222
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="146dp"
android:onClick="logout"
android:text="logout" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button1"
android:layout_alignParentTop="true"
android:layout_marginTop="64dp"
android:text="welcome"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button1"
android:layout_centerHorizontal="true"
android:layout_marginTop="43dp"
android:onClick="exit"
android:text="exit" />
</RelativeLayout>
MainActivity.java:
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
223
public class MainActivity extends AppCompatActivity implements
WeatherDownloader.WeatherDataDownloadListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setTitle("Current Weather");
cityNameSearch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
cityNameProgress.setVisibility(View.VISIBLE);
String cityNameQuery = cityName.getText().toString();
if(cityNameQuery.length() > 0) {
WeatherDownloader downloader = new
224
WeatherDownloader(MainActivity.this, WeatherDownloader.Mode.CITYNAME);
downloader.getCurrentWeatherData(getResources().getString(R.string.weather_api_key),
cityNameQuery);
}
}
});
cityIdSearch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
cityIdProgress.setVisibility(View.VISIBLE);
String cityIdQuery = cityId.getText().toString();
if(cityIdQuery.length() > 0) {
WeatherDownloader downloader = new
WeatherDownloader(MainActivity.this, WeatherDownloader.Mode.CITYID);
downloader.getCurrentWeatherData(getResources().getString(R.string.weather_api_key),
cityIdQuery);
}
}
});
coordinatesSearch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
coordinatesProgress.setVisibility(View.VISIBLE);
String coordinatesQuery = coordinates.getText().toString();
if(coordinatesQuery.length() > 0) {
WeatherDownloader downloader = new
WeatherDownloader(MainActivity.this, WeatherDownloader.Mode.COORDINATES);
downloader.getCurrentWeatherData(getResources().getString(R.string.weather_api_key),
coordinatesQuery);
}
}
});
zipCodeSearch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
zipCodeProgress.setVisibility(View.VISIBLE);
String zipCodeQuery = zipCode.getText().toString();
if(zipCodeQuery.length() > 0) {
225
WeatherDownloader downloader = new
WeatherDownloader(MainActivity.this, WeatherDownloader.Mode.ZIPCODE);
downloader.getCurrentWeatherData(getResources().getString(R.string.weather_api_key),
zipCodeQuery);
}
}
});
@Override
public void onWeatherDownloadComplete(WeatherData data, WeatherDownloader.Mode
mode) {
if (mode == WeatherDownloader.Mode.CITYNAME) {
cityNameProgress.setVisibility(View.GONE);
cityNameResult.setText(String.format("%.2f",
WeatherUnits.convertToCelsius(data.getMain().getTemp())));
} else if (mode == WeatherDownloader.Mode.CITYID) {
cityIdProgress.setVisibility(View.GONE);
cityIdResult.setText(String.format("%.2f",
WeatherUnits.convertToFahrenheit(data.getMain().getTemp())));
} else if (mode == WeatherDownloader.Mode.COORDINATES) {
coordinatesProgress.setVisibility(View.GONE);
coordinatesResult.setText(data.getMain().getTemp());
} else if (mode == WeatherDownloader.Mode.ZIPCODE) {
zipCodeProgress.setVisibility(View.GONE);
zipCodeResult.setText(String.format("%.2f",
WeatherUnits.convertToFahrenheit(data.getMain().getTemp())));
}
}
@Override
public void onWeatherDownloadFailed(Exception e) {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
Clouds.java:
226
public String getAll () {
return all;
}
@Override
public String toString() {
return "Clouds[all = "+all+"]";
}
}
Coord.java:
@Override
public String toString() {
return "Coord [lon = "+lon+", lat = "+lat+"]";
227
}
}
JsonUtil.java:
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
228
{
JSONObject jsonObject = new JSONObject(json);
JSONArray weatherJsonArray = jsonObject.getJSONArray("weather");
if(weatherJsonArray != null) {
Weather[] weatherArray = new Weather[weatherJsonArray.length()];
for (int i = 0; i < weatherJsonArray.length(); i++) {
Weather weather = new Weather();
JSONObject weatherJsonObject = weatherJsonArray.getJSONObject(i);
weather.setId(weatherJsonObject.getString("id"));
weather.setDescription(weatherJsonObject.getString("description"));
weather.setIcon(weatherJsonObject.getString("icon"));
weather.setMain(weatherJsonObject.getString("main"));
weatherArray[i] = weather;
}
return weatherArray;
} else {
return null;
}
}
229
} else {
return null;
}
}
Main.java:
230
public void setPressure (String pressure) {
this.pressure = pressure;
}
@Override
public String toString() {
return "Main [humidity = "+humidity+", pressure = "+pressure+", temp_max =
"+temp_max+", temp_min = "+temp_min+", temp = "+temp+"]";
}
}
Rain.java:
Sys.java:
231
public class Sys {
private String message;
232
this.sunrise = sunrise;
}
@Override
public String toString() {
return "Sys [message = "+message+", id = "+id+", sunset = "+sunset+", sunrise
= "+sunrise+", type = "+type+", country = "+country+"]";
}
}
Weather.java:
233
this.id = id;
}
@Override
public String toString() {
return "Weather [id = "+id+", icon = "+icon+", description = "+description+",
main = "+main+"]";
}
}
WeatherData.java:
import java.util.Arrays;
234
private Clouds clouds;
235
this.clouds = clouds;
}
236
return name;
}
@Override
public String toString() {
return "WeatherData [id = "+id+", dt = "+dt+", clouds = "+clouds+", coord =
"+coord+", wind = "+wind+", cod = "+cod+", visibility = "+visibility+", sys = "+sys+",
name = "+name+", base = "+base+", weather = "+ Arrays.toString(weather) +", main =
237
"+main+"]";
}
}
WeatherDataBuilder.java:
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
238
Main mainData = null;
try {
mainData = JsonUtil.getMainObjectFromJson(response);
weatherData.setMain(mainData);
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage());
weatherData.setMain(mainData);
}
try {
weatherData.setBase(jsonObject.getString("base"));
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage());
239
weatherData.setBase(null);
}
try {
weatherData.setVisibility(jsonObject.getString("visibility"));
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage());
weatherData.setVisibility(null);
}
try {
weatherData.setDt(jsonObject.getString("dt"));
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage());
weatherData.setDt(null);
}
try {
weatherData.setId(jsonObject.getString("id"));
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage());
weatherData.setId(null);
}
try {
weatherData.setName(jsonObject.getString("name"));
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage());
weatherData.setName(null);
}
try {
weatherData.setCod(jsonObject.getString("cod"));
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage());
weatherData.setCod(null);
}
return weatherData;
}
}
WeatherDownloader.java:
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
240
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
241
.appendPath(DATA_PATH)
.appendPath(VERSION_PATH)
.appendPath(WEATHER_PATH)
.appendQueryParameter("appid", apiKey);
switch (mode) {
case CITYNAME:
builder.appendQueryParameter("q", query);
return builder.build().toString();
case ZIPCODE:
builder.appendQueryParameter("zip", query);
return builder.build().toString();
case COORDINATES:
String[] coord = query.split(":");
builder.appendQueryParameter("lat", coord[0]);
builder.appendQueryParameter("lon", coord[1]);
return builder.build().toString();
case CITYID:
builder.appendQueryParameter("id", query);
return builder.build().toString();
default:
break;
}
return null;
}
242
} catch (IOException e) {
Log.e(LOG_TAG, e.getMessage());
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
} catch (IOException e) {
Log.e(LOG_TAG, e.getMessage());
}
}
return null;
}
@Override
protected void onPostExecute(String response) {
if(response == null){
Log.e(LOG_TAG, "Response is null");
downloadListener.onWeatherDownloadComplete(null, mode);
} else {
try {
downloadListener.onWeatherDownloadComplete(WeatherDataBuilder.buildWeatherData(respons
e), mode);
} catch (Exception e) {
Log.e(LOG_TAG, "Invalid data");
downloadListener.onWeatherDownloadFailed(e);
}
}
}
243
return result;
}
}
WeatherUnits.java:
Wind.java:
244
private String deg;
@Override
public String toString() {
return "Wind [speed = "+speed+", deg = "+deg+"]";
}
}
activity_main.xml:
<LinearLayout tools:context=".MainActivity"
android:orientation="vertical"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout android:orientation="horizontal"
android:layout_height="wrap_content"
android:layout_width="match_parent">
245
<TextView android:layout_height="wrap_content"
android:layout_width="0dp"
android:text="Search by name"
android:layout_weight="1"/>
<EditText android:layout_height="wrap_content"
android:layout_width="0dp"
android:layout_weight="1"
android:inputType="textAutoCorrect"
android:hint="city name"
android:id="@+id/city_name"/>
</LinearLayout>
<LinearLayout android:orientation="horizontal"
android:layout_height="wrap_content"
android:layout_width="match_parent">
<TextView android:layout_height="wrap_content"
android:layout_width="0dp"
android:layout_weight="1"
android:id="@+id/city_result"/>
<ProgressBar android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/city_progress"
android:indeterminate="true"
android:visibility="gone"/>
<Button android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Get Current Weather"
android:id="@+id/city_search"/>
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Celsius" />
246
<LinearLayout android:orientation="horizontal"
android:layout_height="wrap_content"
android:layout_width="match_parent">
<TextView android:layout_height="wrap_content"
android:layout_width="0dp"
android:text="Search by zip code"
android:layout_weight="1"/>
<EditText android:layout_height="wrap_content"
android:layout_width="0dp"
android:layout_weight="1"
android:inputType="number"
android:hint="zip code"
android:id="@+id/zip_code"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_height="wrap_content"
android:layout_width="match_parent">
<TextView android:layout_height="wrap_content"
android:layout_width="0dp"
android:layout_weight="1"
android:id="@+id/zip_code_result"/>
<ProgressBar android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/zip_code_progress"
android:indeterminate="true"
android:visibility="gone"/>
<Button android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Get Current Weather"
android:id="@+id/zip_code_search"
android:layout_gravity="end"/>
</LinearLayout>
247
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Fahrenheit" />
<LinearLayout android:orientation="horizontal"
android:layout_height="wrap_content"
android:layout_width="match_parent">
<TextView android:layout_height="wrap_content"
android:layout_width="0dp"
android:text="Search by coordinates"
android:layout_weight="1"/>
<EditText android:layout_height="wrap_content"
android:layout_width="0dp"
android:layout_weight="1"
android:inputType="text"
android:hint="lat:lon"
android:id="@+id/coordinates"/>
</LinearLayout>
<LinearLayout android:orientation="horizontal"
android:layout_height="wrap_content"
android:layout_width="match_parent">
<TextView android:layout_height="wrap_content"
android:layout_width="0dp"
android:layout_weight="1"
android:id="@+id/coordinates_result"/>
<ProgressBar android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/coordinates_progress"
android:indeterminate="true"
android:visibility="gone"/>
<Button android:layout_height="wrap_content"
android:layout_width="wrap_content"
248
android:text="Get Current Weather"
android:id="@+id/coordinates_search"
android:layout_gravity="end"/>
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Kelvin" />
<LinearLayout android:orientation="horizontal"
android:layout_height="wrap_content"
android:layout_width="match_parent">
<TextView android:layout_height="wrap_content"
android:layout_width="0dp"
android:text="Search by City ID"
android:layout_weight="1"/>
<EditText android:layout_height="wrap_content"
android:layout_width="0dp"
android:layout_weight="1"
android:inputType="text"
android:hint="city id"
android:id="@+id/city_id"/>
</LinearLayout>
<LinearLayout android:orientation="horizontal"
android:layout_height="wrap_content"
android:layout_width="match_parent">
<TextView android:layout_height="wrap_content"
android:layout_width="0dp"
android:layout_weight="1"
android:id="@+id/city_id_result"/>
<ProgressBar android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/city_id_progress"
android:indeterminate="true"
249
android:visibility="gone"/>
<Button android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Get Current Weather"
android:id="@+id/city_id_search"
android:layout_gravity="end"/>
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Fahrenheit" />
</LinearLayout>
Create a resource file in values i.e., create key.xml and add the following code:
<string name="weather_api_key">16f28aecfde1858cd9bda7e9444e54e8</string>
</resources>
<uses-permission android:name="android.permission.INTERNET"/>
Main activity.java:
import android.content.Context;
import android.hardware.GeomagneticField;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
250
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.WindowManager;
import android.widget.TextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textDirection = (TextView) findViewById(R.id.text);
251
compassView = (CompassView) findViewById(R.id.compass);
// keep screen light on (wake lock light)
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
@Override
protected void onStart() {
super.onStart();
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorGravity = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorMagnetic = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
@Override
public void onSensorChanged(SensorEvent event) {
boolean accelOrMagnetic = false;
252
SensorManager.getRotationMatrix(rotation, null, gravity, geomagnetic);
// get bearing to target
SensorManager.getOrientation(rotation, orientation);
// east degrees of true North
bearing = orientation[0];
// convert from radians to degrees
bearing = Math.toDegrees(bearing);
if (accelOrMagnetic) {
compassView.postInvalidate();
}
if (range == 15 || range == 0)
dirTxt = "N";
if (range == 1 || range == 2)
dirTxt = "NE";
if (range == 3 || range == 4)
dirTxt = "E";
if (range == 5 || range == 6)
dirTxt = "SE";
if (range == 7 || range == 8)
dirTxt = "S";
if (range == 9 || range == 10)
dirTxt = "SW";
253
if (range == 11 || range == 12)
dirTxt = "W";
if (range == 13 || range == 14)
dirTxt = "NW";
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
if (sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD
&& accuracy == SensorManager.SENSOR_STATUS_UNRELIABLE) {
// manage fact that compass data are unreliable ...
// toast ? display on screen ?
}
}
}
CompassView.java:
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
254
public CompassView(Context context, AttributeSet attr) {
super(context, attr);
initialize();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
width = MeasureSpec.getSize(widthMeasureSpec);
height = MeasureSpec.getSize(heightMeasureSpec);
setMeasuredDimension(width, height);
}
@Override
protected void onDraw(Canvas canvas) {
int bitmapWidth = bitmap.getWidth();
int bitmapHeight = bitmap.getHeight();
int canvasWidth = canvas.getWidth();
int canvasHeight = canvas.getHeight();
// center
int bitmapX = bitmap.getWidth() / 2;
int bitmapY = bitmap.getHeight() / 2;
int parentX = width / 2;
int parentY = height / 2;
int centerX = parentX - bitmapX;
255
int centerY = parentY - bitmapY;
// reset matrix
matrix.reset();
matrix.setRotate(rotation, bitmapX, bitmapY);
// center bitmap on canvas
matrix.postTranslate(centerX, centerY);
// draw bitmap
canvas.drawBitmap(bitmap, matrix, paint);
}
LowPassFilter.java:
return output;
activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
256
android:layout_height="match_parent"
android:background="@drawable/background"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="manju.example.com.myapplicationcompass.MainActivity" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp" >
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textSize="@dimen/dirSize" />
</RelativeLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
android:orientation="horizontal" >
</LinearLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<manju.example.com.myapplicationcompass.CompassView
android:id="@+id/compass"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_centerInParent="true" />
</RelativeLayout>
</LinearLayout>
257
In manifest file – the following permissions should be added
<uses-feature
android:name ="android.hardware.sensor.accelerometer"
android:required ="true"/>
<uses-feature
android:name ="android.hardware.sensor.compass"
android:required ="true"/>
<dimen name="dirSize">32dp</dimen>
Code in MainActivity.java:
import android.app.DownloadManager;
import android.app.DownloadManager.Query;
import android.app.DownloadManager.Request;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
258
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
long downloadId = intent.getLongExtra(
DownloadManager.EXTRA_DOWNLOAD_ID, 0);
Query query = new Query();
query.setFilterById(enqueue);
Cursor c = dm.query(query);
if (c.moveToFirst()) {
int columnIndex = c
.getColumnIndex(DownloadManager.COLUMN_STATUS);
}
}
}
};
<uses-permission android:name="android.permission.INTERNET"/>
259
activity_main.xml:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Next"
android:id="@+id/button"
android:layout_gravity="center_horizontal" />
</LinearLayout>
MainActivity.java:
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
260
public class MainActivity extends AppCompatActivity {
private ImageView img;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img = (ImageView) findViewById(R.id.imageView1);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true; }
public void open(View view){
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, "Hello, How r u ");
startActivity(Intent.createChooser(shareIntent, "Share your thoughts"));
}
}
activity_main.xml:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="98dp"
android:layout_marginTop="139dp"
android:onClick="open"
android:src="@drawable/ic_launcher" />
261
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="48dp"
android:text="@string/tap"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
String.xml:
<resources>
<string name="hello_world">Hello world!</string>
<string name="tap">Tap the button to share something</string>
</resources>
<uses-permission android:name="android.permission.INTERNET"/>
Main Activity.java:
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.View;
import java.io.File;
import java.io.IOException;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
262
import android.os.Environment;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
263
public void stop(View view){
myAudioRecorder.stop();
myAudioRecorder.release();
myAudioRecorder = null;
stop.setEnabled(false);
play.setEnabled(true);
Toast.makeText(getApplicationContext(),
"Audio recorded successfully",
Toast.LENGTH_LONG).show(); }
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true; }
public void play(View view) throws IllegalArgumentException,
SecurityException, IllegalStateException, IOException{
MediaPlayer m = new MediaPlayer();
m.setDataSource(outputFile);
m.prepare();
m.start();
Toast.makeText(getApplicationContext(), "Playing audio",
Toast.LENGTH_LONG).show();
}
}
activity_main.xml:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
264
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="32dp"
android:text="@string/Recording"
android:textAppearance="?android:attr/textAppearanceMedium" />
<ImageView
android:id="@+id/imageView1"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="37dp"
android:scaleType="fitXY"
android:src="@android:drawable/presence_audio_online" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/imageView1"
android:layout_marginTop="67dp"
android:layout_toLeftOf="@+id/imageView1"
android:onClick="start"
android:text="@string/start" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/button1"
android:layout_alignBottom="@+id/button1"
android:layout_alignRight="@+id/textView1"
android:layout_marginRight="40dp"
android:onClick="stop"
android:text="@string/stop" />
<Button
android:id="@+id/button3"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button2"
android:layout_centerHorizontal="true"
android:onClick="play"
android:text="@string/play" />
</RelativeLayout>
265
Permissions in manifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.RECORD_AUDIO" />
String.xml:
<resources>
<string name="Recording">Android Audio Recording Application</string>
<string name="start">start</string>
<string name="stop">stop</string>
<string name="play">play</string>
</resources>
Google Map
After Gradle build, open Google_maps_api.xml in layout folder and note Finger print and package
name i.e.,
Google_maps_api.xml
<!--
TODO: Before you run your application, you need a Google Maps API key.
266
To get one, follow this link, follow the directions and press "Create" at the end:
https://console.developers.google.com/flows/enableapi?apiid=maps_android_backend&keyTy
pe=CLIENT_SIDE_ANDROID&r=A0:4D:F6:41:65:95:F3:59:F7:E1:03:24:44:56:26:87:C8:ED:37:6C%3
Bcom.example.manju.myapplication
You can also add your credentials to an existing key, using this line:
A0:4D:F6:41:65:95:F3:59:F7:E1:03:24:44:56:26:87:C8:ED:37:6C;com.example.manju.myapplic
ation
Once you have your key (it starts with "AIza"), replace the "google_maps_key"
string in this file.
-->
https://code.google.com/apis/console/?pli=1
Then go to CREATE PROJECT → New Project (enter project name) → create → Under API Manager → go to
Credentials → APIs Credentials → API key → Android key → Add package name and finger print → fill package name
and finger print → create → Note down your API key
After noting down the API key — you need to enter it in the Manifest.xml file as follows:
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="AIzaSyDWOTqYHHYlrziUPoF4IshFKNxKxlo91PM" />
And you need to add the following permissions to your manifest file:
267
SCROLL VIEW
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginLeft="20dp"
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginLeft="20dp"
android:text="Button 2"
/>
268
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginLeft="20dp"
android:text="Button 3"
/>
<Button
android:id="@+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginLeft="20dp"
android:text="Button 4"
/>
<Button
android:id="@+id/button5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginLeft="20dp"
android:text="Button 5"
/>
269
<Button
android:id="@+id/button6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginLeft="20dp"
android:text="Button 6"
/>
<Button
android:id="@+id/button7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginLeft="20dp"
android:text="Button 7"
/>
<Button
android:id="@+id/button8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginLeft="20dp"
android:text="Button 8"
/>
270
<Button
android:id="@+id/button9"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginLeft="20dp"
android:text="Button 9"
/>
<Button
android:id="@+id/button10"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginLeft="20dp"
android:text="Button 10"
/>
</LinearLayout>
</ScrollView>
WEB VIEW
Code in MainActivity.java:
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
271
import android.webkit.WebSettings;
import android.webkit.WebView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
// Enable Javascript
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.loadUrl("http://google.com/");
}
}
activity_main.xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
tools:ignore="MergeRootFrame">
<WebView
android:id="@+id/activity_main_webview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
272
MainActivity.java:
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startActivity(i);
startActivity(i);
273
public void setting(View v)
startActivity(i);
System.exit(0);
Game.java:
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.media.MediaPlayer;
import android.os.Bundle;
274
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.view.Display;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.Window;
import android.view.WindowManager;
MediaPlayer mp1,jump,takecoin;
gameloop gameLoopThread;
super.onCreate(savedInstanceState);
//phone state
TelephonyMgr.listen(new TeleListener(),PhoneStateListener.LISTEN_CALL_STATE);
//for no title
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(new GameView(this));
Bitmap bmp,pause;
275
Bitmap background,kinfe,note1,powerimg,note2;
Bitmap run1;
Bitmap run2;
Bitmap run3;
Bitmap coin;
Bitmap exit;
int show=0,sx,sy;
int cspeed=0,kspeed=0,gameover=0;
int score=0,health=100,reset=0;
int pausecount=0,volume,power=0,powerrun=0,shieldrun=0;
@SuppressWarnings("deprecation")
@SuppressLint("NewApi")
super(context);
holder = getHolder();
holder.addCallback(new SurfaceHolder.Callback() {
@SuppressWarnings("deprecation")
@Override
276
public void surfaceDestroyed(SurfaceHolder holder)
gameLoopThread.setRunning(false);
gameLoopThread.getThreadGroup().interrupt();
@SuppressLint("WrongCall")
@Override
gameLoopThread.setRunning(true);
gameLoopThread.start();
@Override
});
sx = display.getWidth();
sy = display.getHeight();;
277
cspeed=sx/2;
kspeed=sx/2;
powerrun=(3*sx/4);
shieldrun=sx/8;
background = BitmapFactory.decodeResource(getResources(),
R.drawable.back);
run1=BitmapFactory.decodeResource(getResources(), R.drawable.run1);
run2=BitmapFactory.decodeResource(getResources(), R.drawable.run2);
run3=BitmapFactory.decodeResource(getResources(), R.drawable.run3);
coin=BitmapFactory.decodeResource(getResources(), R.drawable.coin);
exit=BitmapFactory.decodeResource(getResources(), R.drawable.exit);
kinfe=BitmapFactory.decodeResource(getResources(), R.drawable.kinfe);
note1=BitmapFactory.decodeResource(getResources(), R.drawable.note1);
pause=BitmapFactory.decodeResource(getResources(), R.drawable.pause);
powerimg=BitmapFactory.decodeResource(getResources(), R.drawable.power);
note2=BitmapFactory.decodeResource(getResources(), R.drawable.note2);
//health dec
278
note1=Bitmap.createScaledBitmap(note1, sx,sy, true);
mp1=MediaPlayer.create(Game.this,R.raw.game);
jump=MediaPlayer.create(Game.this,R.raw.jump);
takecoin=MediaPlayer.create(Game.this,R.raw.cointake);
// on touch method
@Override
if(event.getAction()==MotionEvent.ACTION_DOWN)
show=1;
getx=(int) event.getX();
gety=(int) event.getY();
//exit
if(getx<25&&gety<25)
//high score
SharedPreferences pref =
getApplicationContext().getSharedPreferences("higher", MODE_PRIVATE);
editor.putInt("score", score);
editor.commit();
279
System.exit(0);
// restart game
if(getx>91&&gety<25)
if(health<=0)
gameLoopThread.setPause(0);
health=100;
score=0;
//pause game
if((getx>(sx-25)&&gety<25&&pausecount==0))
gameLoopThread.setPause(1);
mp1.stop();
pausecount=1;
else if(getx>(sx-25)&&gety<25&&pausecount==1)
gameLoopThread.setPause(0);
mp1.start();
pausecount=0;
280
}
return true;
@SuppressLint("WrongCall")
@Override
//volume
SharedPreferences pref =
getApplicationContext().getSharedPreferences("higher", MODE_PRIVATE);
volume=pref.getInt("vloume", 0);
if(volume==0)
sound=0;
canvas.drawColor(Color.BLACK);
//background moving
z=z-10;
if(z==-sx)
281
{
z=0;
canvas.drawBitmap(background, z, 0, null);
else
canvas.drawBitmap(background, z, 0, null);
//running player
x+=5;
if(x==20)
x=5;
if(show==0)
if(x%2==0)
else
282
canvas.drawBitmap(run1, sx/16, 15*sy/18, null);
//kinfe hit
if(kspeed==20)
kspeed=sx;
health-=25;
canvas.drawBitmap(note1, 0, 0, null);
//power take
if(powerrun==30)
powerrun=3*sx;
health+=25;
canvas.drawBitmap(note2, 0, 0, null);
//power
powerrun=powerrun-10;
if(powerrun<0)
283
powerrun=3*sx/4;
//kinfe
kspeed=kspeed-20;
if(kspeed<0)
kspeed=sx;
// for jump
if(show==1)
if(sound==1)
jump.start();
//score
if(cspeed<=sx/8&&cspeed>=sx/16)
if(sound==1)
takecoin.start();
284
}
cspeed=sx/2;
score+=10;
// jump-hold
delay+=1;
if(delay==3)
show=0;
delay=0;
//for coins
cspeed=cspeed-5;
if(cspeed==-sx/2)
cspeed=sx/2;
else
285
canvas.drawBitmap(coin, cspeed, 3*sy/4, null);
//score
paint.setColor(Color.BLUE);
paint.setAntiAlias(true);
paint.setFakeBoldText(true);
paint.setTextSize(15);
paint.setTextAlign(Align.LEFT);
//exit
canvas.drawBitmap(exit, 0, 0, null);
if(sound==1)
mp1.start();
mp1.setLooping(true);
else
mp1.stop();
//health
myPaint.setColor(Color.RED);
myPaint.setStrokeWidth(10);
myPaint.setAntiAlias(true);
286
myPaint.setFakeBoldText(true);
//game over
if(health<=0)
gameover=1;
mp1.stop();
//high score
editor.putInt("score", score);
editor.commit();
gameLoopThread.setPause(1);
// restart
if(reset==1)
gameLoopThread.setPause(0);
health=100;
score=0;
287
}
//phone state
if(state==TelephonyManager.CALL_STATE_RINGING)
mp1.stop();
System.exit(0);
gameloop.java:
import android.annotation.SuppressLint;
import android.graphics.Canvas;
288
public class gameloop extends Thread {
boolean isPaused;
this.view = view;
running = run;
synchronized (view.getHolder())
if(i==0)
isPaused=false;
if(i==1)
289
isPaused = true;
@SuppressLint("WrongCall")
@Override
long startTime = 0;
long sleepTime;
while (running) {
if (isPaused)
try
this.sleep(50);
catch (InterruptedException e)
e.printStackTrace();
290
else
Canvas c = null;
startTime = System.currentTimeMillis();
try {
c = view.getHolder().lockCanvas();
synchronized (view.getHolder())
view.onDraw(c);
finally
if (c != null)
view.getHolder().unlockCanvasAndPost(c);
try {
if (sleepTime > 0)
291
sleep(sleepTime);
else
sleep(10);
catch (Exception e) {}
Highscore.java:
import android.R.string;
import android.os.Bundle;
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.view.Menu;
import android.widget.TextView;
TextView t1;
int score,hscore;
@Override
super.onCreate(savedInstanceState);
292
setContentView(R.layout.activity_highscore);
SharedPreferences pref =
getApplicationContext().getSharedPreferences("higher", MODE_PRIVATE);
score=pref.getInt("score", 0);
hscore=pref.getInt("hscore", 0);
if(score>hscore)
editor.putInt("hscore", score);
editor.commit();
hscore=pref.getInt("hscore", 0);
t1=(TextView) findViewById(R.id.textView1);
t1.setText("Highscore :"+hscore);
Setting.java:
import android.os.Bundle;
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.view.Menu;
293
import android.view.View;
import android.widget.CheckBox;
import android.widget.Toast;
CheckBox ch1;
int volume;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setting);
ch1=(CheckBox) findViewById(R.id.checkBox1);
SharedPreferences pref =
getApplicationContext().getSharedPreferences("higher", MODE_PRIVATE);
volume=pref.getInt("vloume", 0);
if(volume==1)
ch1.setChecked(true);
ch1 = (CheckBox)v;
SharedPreferences pref =
getApplicationContext().getSharedPreferences("higher", MODE_PRIVATE);
294
Editor editor = pref.edit();
if(ch1.isChecked())
editor.putInt("vloume", 1);
editor.commit();
else
editor.putInt("vloume", 0);
editor.commit();
@Override
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.setting, menu);
return true;
LAYOUT FILES:
activity_main.xml:
<?xml version="1.0"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
295
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity"
android:background="@drawable/back"><Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/button2"
android:layout_below="@+id/button4" android:layout_centerHorizontal="true"
android:layout_marginTop="23dp" android:onClick="setting"
android:text="@string/set"/><Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/button3"
android:layout_below="@+id/button2" android:layout_centerHorizontal="true"
android:layout_marginTop="16dp" android:onClick="exit"
android:text="@string/ex"/><Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/button4"
android:layout_below="@+id/button1" android:layout_centerHorizontal="true"
android:layout_marginTop="19dp" android:onClick="highscore"
android:text="@string/score"/><Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/button1"
android:layout_marginTop="43dp" android:onClick="play" android:text="@string/play"
android:layout_alignLeft="@+id/button4"
android:layout_alignParentTop="true"/></RelativeLayout>
activity_game.xml:
<?xml version="1.0"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin" tools:context=".Game">
</RelativeLayout>
activity_highscore.xml:
<?xml version="1.0"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
296
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin" tools:context=".Highscore"
android:background="@drawable/back"><TextView android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/textView1"
android:layout_alignParentLeft="true" android:layout_alignParentTop="true"
android:layout_marginLeft="20dp" android:layout_marginTop="55dp"
android:text="@string/hs"
android:textAppearance="?android:attr/textAppearanceLarge"/></RelativeLayout>
activity_setting.xml:
<?xml version="1.0"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin" tools:context=".Setting"
android:background="@drawable/back"><CheckBox android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/checkBox1"
android:layout_alignParentLeft="true" android:layout_alignParentTop="true"
android:layout_marginTop="45dp" android:text="@string/vol"
android:onClick="volume"/></RelativeLayout>
Menu
drawable folder
297
raw folder:
strings.xml:
298
android:label="@string/app_name" android:icon="@mipmap/ic_launcher"
android:allowBackup="true"><activity android:name=".MainActivity"
android:theme="@style/AppTheme.NoActionBar" android:label="@string/app_name"><intent-
filter><action android:name="android.intent.action.MAIN"/><category
android:name="android.intent.category.LAUNCHER"/></intent-filter></activity><activity
android:name="manju.example.com.game.Game" android:label="@string/title_activity_game"
android:screenOrientation="landscape"> </activity><activity
android:name="manju.example.com.game.Setting"
android:label="@string/title_activity_setting" android:screenOrientation="portrait">
</activity><activity android:name="manju.example.com.game.Highscore"
android:label="@string/title_activity_highscore"> </activity></application></manifest>
After installing android studio into your system (say computer or laptop) —and after installation,
when you open the android studio to create some project / application – you usually observe an
error stating that: junit cannot be resolved. In order to solve this error, you need to go to C drive → and
under C drive – you need to go to users → and under users – you need to go to manju folder → and
under manju folder – you need to go to AndroidStudioProjects→ and under AndroidStudioProjects → you
need to open Application folder → and you need to go to app folder → and under app folder → you need
to open libs folder → and in libs folder – you need to place junit (executable jar file
junit.jar
– which can be downloaded on internet). And you need to open android studio → and you need to go to
file → project structure → app → dependencies (if you click on it) – a window:
299
Choose library dependency will be opened and in that window you need to choose m junit:junit:4.12 and
press ok and that window will be disappeared and gradle build starts and your problem will be resolved.
Battery temperature
MainActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.TextView;
TemperatureReceiver.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
300
MainActivity activity=null;
public TemperatureReceiver(MainActivity mainActivity) {
activity=mainActivity;
}
@Override
public void onReceive(Context arg0, Intent arg1) {
activity.tempDisplay.setText(arg1.getIntExtra("temperature", 0)/10.0D+" ");
}
activity_main.xml
<?xml version="1.0"?>
<RelativeLayout tools:context=".MainActivity"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
android:layout_height="match_parent" android:layout_width="match_parent"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android">
</RelativeLayout>
MainActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Menu;
301
import android.view.MenuItem;
import android.app.SearchManager;
import android.content.Intent;
import android.view.View.OnClickListener;
import android.widget.EditText;
activity_main.xml
<requestFocus/>
302
</EditText>
<ImageView android:layout_height="wrap_content"
android:layout_width="wrap_content" android:id="@+id/imageView1"
android:src="@drawable/magglass" android:background="@drawable/button_background"/>
</LinearLayout>
Drawable folder
button_background.xml
Android manifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
Android manifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
303
import android.view.View;
import android.content.Intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
{
Intent i = new Intent(MainActivity.this, Sendmsg.class);
startActivity(i);
}
}
}
Sendmsg.java
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.telephony.TelephonyManager;
import android.widget.TextView;
import android.widget.Toast;
SharedPreferences sp=null;
SharedPreferences.Editor edit;
TelephonyManager telemananger=null;
TelephonyManager telemanager2=null;
String anothervar=null;
String var=null;
@Override
304
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sendms);
telemananger = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
anothervar = telemananger.getSimSerialNumber();
sp=getSharedPreferences("share1",Activity.MODE_APPEND);
edit=sp.edit();
var=sp.getString("sim_no",null);
if(var==null)
{
sp.edit().putString("sim_no",anothervar).commit();
var=sp.getString("sim_no",null);
TextView tv=(TextView)findViewById(R.id.textView2);
tv.setText(String.valueOf(anothervar));
}
else
Toast.makeText(this, "hi..", Toast.LENGTH_LONG).show();
TextView tv=(TextView)findViewById(R.id.textView4);
tv.setText(String.valueOf("this is the value of shared prefernces.......
="+var));
Comp.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
305
}
activity_main.xml
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button1"
android:id="@+id/Bdisplay"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="177dp"
android:onClick="onButtonClick" />
</RelativeLayout>
sendms.xml
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sim Number:" />
<TextView
306
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Sim Number:"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
</LinearLayout>
Android manifest.xml
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<activity android:name=".Sendmsg"/>
<receiver android:name=".Comp"/>
Popup window
MainActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
307
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.PopupWindow;
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
initiatePopupWindow();
}
});
} catch (Exception e) {
308
e.printStackTrace();
}
}
}
};
activity_main.xml
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
screen_popup.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/popup_element"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#444444"
309
android:orientation="vertical"
android:padding="10sp" >
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"></TableLayout>
<Button
android:layout_marginTop="50dp"
android:id="@+id/btn_close_popup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Close" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button1"
android:id="@+id/Bdisplay"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="177dp"
android:onClick="onButtonClick"
android:layout_gravity="center_horizontal" />
</LinearLayout>
LIST VIEW
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
310
setContentView(R.layout.activity_main);
ListView list = (ListView) findViewById(R.id.list1);
String[] days = { "Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday","Sunday", "Monday", "Tuesday",
"Wednesday",
"Thursday", "Friday", "Saturday"
};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, days);
list.setAdapter(adapter);
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView
android:id="@+id/list1"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
</RelativeLayout>
AGE CALCULATOR
MainActivity.java
import java.util.Calendar;
import java.util.Timer;
import android.os.Bundle;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
311
import android.widget.Toast;
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_START_DIALOG_ID:
return new DatePickerDialog(this,
mDateSetListener,
startYear, startMonth, startDay);
}
return null;
}
312
age.setDateOfBirth(startYear, startMonth, startDay);
birthDate.setText("Date of Birth(DD/MM/YY):
"+selectedDay+":"+(startMonth+1)+":"+startYear);
calculateAge();
}
};
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.button1:
showDialog(DATE_START_DIALOG_ID);
break;
default:
break;
}
}
private void calculateAge()
{
age.calcualteYear();
age.calcualteMonth();
age.calcualteDay();
Toast.makeText(getBaseContext(), "click the resulted
button"+age.getResult() , Toast.LENGTH_SHORT).show();
result.setText("AGE (DD/MM/YY) :"+age.getResult());
}
}
AgeCalculation.java
import java.util.Calendar;
import java.util.Date;
313
private int resDay;
private Calendar start;
private Calendar end;
public String getCurrentDate()
{
end=Calendar.getInstance();
endYear=end.get(Calendar.YEAR);
endMonth=end.get(Calendar.MONTH);
endMonth++;
endDay=end.get(Calendar.DAY_OF_MONTH);
return endDay+":"+endMonth+":"+endYear;
}
public void setDateOfBirth(int sYear, int sMonth, int sDay)
{
startYear=sYear;
startMonth=sMonth;
startMonth++;
startDay=sDay;
}
public void calcualteYear()
{
resYear=endYear-startYear;
}
public void calcualteDay()
{
if(endDay>=startDay)
314
{
resDay= endDay-startDay;
}
else
{
resDay=endDay-startDay;
resDay=30+resDay;
if(resMonth==0)
{
resMonth=11;
resYear--;
}
else
{
resMonth--;
}
}
}
activity_main.xml
315
<?xml version="1.0"?>
<RelativeLayout android:layout_height="match_parent"
android:layout_width="match_parent" xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android">
</RelativeLayout>
Send sms
MainActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.app.Activity;
import android.os.Bundle;
import android.telephony.gsm.SmsManager;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
316
import android.widget.Toast;
import android.view.View;
import android.view.Menu;
Button btnSend;
EditText txtPhoneNo;
EditText txtSMS;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
btnSend=(Button) findViewById(R.id.buttonSend);
txtPhoneNo=(EditText) findViewById(R.id.editTextPhoneNo);
txtSMS=(EditText) findViewById(R.id.editTextSMS);
btnSend.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String phoneNo=txtPhoneNo.getText().toString();
String SMS=txtSMS.getText().toString();
try {
SmsManager smsManager=SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, SMS, null, null);
Toast.makeText(getApplicationContext(),"SMS
Sent!...",Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "SMS faild, please try
again later!",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
});
317
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
activity_main.xml
<LinearLayout
android:orientation="vertical"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:id="@+id/linearLayout1"
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/textViewPhoneNo"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Enter Phone Number : "/>
<EditText android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:id="@+id/editTextPhoneNo"
android:phoneNumber="true"> </EditText>
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/textViewSMS"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Enter SMS Message : "/>
<EditText
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:id="@+id/editTextSMS"
318
android:gravity="top"
android:lines="5"
android:inputType="textMultiLine"/>
<Button
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:id="@+id/buttonSend"
android:text="Send"/>
</LinearLayout>
Android manifest.xml
<uses-permission android:name="android.permission.SEND_SMS"/>
MainActivity.java
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
319
private Parameters params;
private MediaPlayer mp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
/*
* First check if device is supporting flashlight or not
*/
hasFlash = getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if (!hasFlash) {
// device doesn't support flash
// Show alert message and close the application
AlertDialog alert = new AlertDialog.Builder(MainActivity.this)
.create();
alert.setTitle("Error");
alert.setMessage("Sorry, your device doesn't support flash light!");
alert.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// closing the application
finish();
}
});
alert.show();
return;
}
/*
* Switch button click event to toggle flash on/off
*/
btnSwitch.setOnClickListener(new View.OnClickListener() {
320
@Override
public void onClick(View v) {
if (isFlashOn) {
// turn off flash
turnOffFlash();
} else {
// turn on flash
turnOnFlash();
}
}
});
}
/*
* Get the camera
*/
private void getCamera() {
if (camera == null) {
try {
camera = Camera.open();
params = camera.getParameters();
} catch (RuntimeException e) {
Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());
}
}
}
/*
* Turning On flash
*/
private void turnOnFlash() {
if (!isFlashOn) {
if (camera == null || params == null) {
return;
}
// play sound
playSound();
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
321
// changing button/switch image
toggleButtonImage();
}
/*
* Turning Off flash
*/
private void turnOffFlash() {
if (isFlashOn) {
if (camera == null || params == null) {
return;
}
// play sound
playSound();
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashOn = false;
/*
* Playing sound will play button toggle sound on flash on / off
*/
private void playSound() {
if (isFlashOn) {
mp = MediaPlayer.create(MainActivity.this, R.raw.light_switch_off);
} else {
mp = MediaPlayer.create(MainActivity.this, R.raw.light_switch_on);
}
mp.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
322
}
});
mp.start();
}
/*
* Toggle switch button images changing image states to on / off
*/
private void toggleButtonImage() {
if (isFlashOn) {
btnSwitch.setImageResource(R.drawable.btn_switch_on);
} else {
btnSwitch.setImageResource(R.drawable.btn_switch_off);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
}
@Override
protected void onPause() {
super.onPause();
@Override
protected void onRestart() {
super.onRestart();
}
@Override
protected void onResume() {
super.onResume();
@Override
323
protected void onStart() {
super.onStart();
@Override
protected void onStop() {
super.onStop();
activity_main.xml
<?xml version="1.0"?>
</LinearLayout>
Android manifest.xml
<uses-permission android:name="android.permission.CAMERA"/>
<uses-feature android:name="android.hardware.camera"/>
324
Drawable folder
Raw folder
light_switch_on.mp3 light_switch_off.mp3
Bluetooth activation
MainActivity.java
import android.os.Bundle;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
BluetoothAdapter bt = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initialize bluetooth adapter object
bt = BluetoothAdapter.getDefaultAdapter();
325
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#024" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:onClick="action"
android:text="Enable and disable bluetooth"
326
android:textSize="18sp" />
</RelativeLayout>
Android manifest.xml
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
Wifi activation
MainActivity.java
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.support.v7.app.AppCompatActivity;
WifiManager wm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//this method will call on button click
public void wwf(View v)
{
Button b1=(Button)findViewById(R.id.button1);
//get Wifi service
wm=(WifiManager)getSystemService(WIFI_SERVICE);
//Check Wifi is on or off
if(wm.isWifiEnabled())
{
b1.setText("Wifi OFF");
//enable or disable Wifi
//for enable pass true value
//for disable pass false value
wm.setWifiEnabled(false);
}
else
327
{
b1.setText("Wifi ON");
wm.setWifiEnabled(true);
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#b21">
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:onClick="wwf"
android:text="Wifi OFF"
android:textSize="30sp" />
</RelativeLayout>
Android manifest.xml
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
Main activity.java
import android.os.Bundle;
import android.view.View;
import android.app.Activity;
import android.content.Intent;
328
Intent i=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
Login.java
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
329
public class Login extends Activity{
Intent i=null;
ImageView im=null;
EditText tv1,tv4;
boolean flag=false;
SQLiteDatabase db=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
im=(ImageView)findViewById(R.id.show_hide2);
tv1=(EditText)findViewById(R.id.phone2);
tv4=(EditText)findViewById(R.id.password2);
db=openOrCreateDatabase("mydb", MODE_PRIVATE, null);
// db.execSQL("create table if not exists login(name varchar,mobile_no
varchar,email_id varchar,password varchar,flag varchar)");
im.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
if(flag==false)
{
im.setImageResource(R.drawable.hide);
tv4.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
flag=true;
}
else
{
im.setImageResource(R.drawable.show);
tv4.setInputType(129);
flag=false;
}
}
});
}
330
i=new Intent(this,Signin.class);
startActivityForResult(i, 500);
overridePendingTransition(R.anim.slide_in_top,
R.anim.slide_out_bottom);
finish();
break;
case R.id.start:
String mobile_no=tv1.getText().toString();
String password=tv4.getText().toString();
if(mobile_no==null||mobile_no==""||mobile_no.length()<10)
{
show("Please Enter Correct mobile number.");
}
else if(password==null||password==""||password.length()<6)
{
show("Please Enter Correct Password.");
}
else
{
Cursor c=db.rawQuery("select * from login where
mobile_no='"+mobile_no+"' and password='"+password+"'",null);
c.moveToFirst();
if(c.getCount()>0)
{
i=new Intent(this,Welcome.class);
startActivityForResult(i,500);
overridePendingTransition(R.anim.slide_in_right,
R.anim.slide_out_left);
db.close();
finish();
}
else
show("Wrong Password or Mobile number.");
}
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
}
331
{
Toast.makeText(this, str, Toast.LENGTH_LONG).show();
}
Signin.java
import android.app.Activity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
im.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
if(flag==false)
{
332
im.setImageResource(R.drawable.hide);
tv4.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
flag=true;
}
else
{
im.setImageResource(R.drawable.show);
tv4.setInputType(129);
flag=false;
}
}
});
}
333
{
show("Please Enter Strong Password.");
}
else
{
db.execSQL("insert into login
values('"+name+"','"+mobile_no+"','"+email_id+"','"+password+"','nothing')");
i=new Intent(this,Welcome.class);
startActivityForResult(i, 500);
overridePendingTransition(R.anim.slide_in_right,
R.anim.slide_out_left);
db.close();
finish();
}
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
}
Welcome.java
import android.app.Activity;
import android.os.Bundle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcome);
}
}
334
activity_main.xml
<?xml version="1.0"?>
<RelativeLayout android:background="#999999"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_alignParentBottom="true">
<Button
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:onClick="login_sigin"
android:text="Sign In"
android:textSize="20sp"
android:layout_weight="1"
android:id="@+id/sign_in"/>
<Button
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:onClick="login_sigin"
android:text="Log In"
android:textSize="20sp"
android:layout_weight="1"
android:id="@+id/log_in"/>
</LinearLayout>
<TextView android:background="#CCCCCC"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text=" Welcome "
android:textSize="25sp"
android:id="@+id/text"
android:textColor="#333333"
android:textAppearance="?android:attr/textAppearanceLarge"
android:gravity="center"
335
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentLeft="true"/>
</RelativeLayout>
login.xml
<?xml version="1.0"?>
<RelativeLayout
android:background="@android:drawable/edit_text"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:gravity="center_vertical"
android:baselineAligned="false"
android:addStatesFromChildren="true"
android:layout_centerVertical="true"
android:layout_alignRight="@+id/phone2"
android:layout_alignLeft="@+id/phone2"
android:id="@+id/rl">
<ImageView
android:background="@drawable/show"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/show_hide2"
android:layout_marginTop="4dp"
android:layout_alignParentTop="true"
android:layout_alignBottom="@+id/rl"
android:layout_alignParentRight="true"
style="@android:style/Widget.Button.Inset"/>
<EditText
android:background="@null"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/password2"
336
android:layout_alignParentTop="true"
android:layout_alignBottom="@+id/rl"
android:singleLine="true"
android:maxLines="1"
android:inputType="textPassword"
android:hint="Password"
android:focusableInTouchMode="true"
android:focusable="true"
android:maxLength="40"
android:ems="10"
android:layout_toLeftOf="@+id/show_hide2"
android:layout_alignParentLeft="true"/>
</RelativeLayout>
<EditText android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/phone2"
android:inputType="phone"
android:hint="Mobile No."
android:maxLength="10"
android:ems="10"
android:layout_centerHorizontal="true"
android:layout_above="@+id/rl">
<requestFocus/>
</EditText>
<Button
android:layout_height="wrap_content"
android:layout_width="wrap_content" android:id="@+id/signin2"
android:layout_alignParentTop="true" android:layout_alignParentRight="true"
android:layout_alignParentLeft="true" android:textSize="20sp" android:onClick="action"
android:text="Sign in"/>
</RelativeLayout>
337
signin.xml
<?xml version="1.0"?>
<requestFocus/>
</EditText>
<RelativeLayout android:background="@android:drawable/edit_text"
android:layout_height="wrap_content" android:layout_width="wrap_content"
android:layout_alignLeft="@+id/email_id" android:id="@+id/rl"
android:gravity="center_vertical" android:baselineAligned="false"
android:addStatesFromChildren="true" android:layout_below="@+id/email_id"
android:layout_alignRight="@+id/email_id">
<ImageView android:background="@drawable/show"
android:layout_height="wrap_content" android:layout_width="wrap_content"
android:id="@+id/show_hide" android:layout_marginTop="4dp"
android:layout_alignParentTop="true" android:layout_alignBottom="@+id/rl"
android:layout_alignParentRight="true" style="@android:style/Widget.Button.Inset"/>
338
<EditText android:background="@null" android:layout_height="wrap_content"
android:layout_width="wrap_content" android:inputType="textPassword"
android:maxLength="40" android:hint="Password" android:ems="10"
android:id="@+id/password" android:layout_alignParentTop="true"
android:layout_alignBottom="@+id/rl" android:singleLine="true" android:maxLines="1"
android:focusableInTouchMode="true" android:focusable="true"
android:layout_toLeftOf="@+id/show_hide" android:layout_alignParentLeft="true"/>
</RelativeLayout>
</RelativeLayout>
Welcome.xml
<?xml version="1.0"?>
</RelativeLayout>
339
Drawable FOLDER
anim FOLDER
Android manifest.xml
340
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.example.manju.myapplication.Login"/>
<activity android:name="com.example.manju.myapplication.Signin"/>
<activity android:name="com.example.manju.myapplication.Welcome"/>
</application>
</manifest>
MainActivity.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONObject;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;
import com.google.android.gms.maps.GoogleMap;
341
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
GoogleMap map;
RadioButton rbDriving;
RadioButton rbBiCycling;
RadioButton rbWalking;
RadioGroup rgModes;
ArrayList<LatLng> markerPoints;
int mMode=0;
final int MODE_DRIVING=0;
final int MODE_BICYCLING=1;
final int MODE_WALKING=2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rgModes.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
342
LatLng origin = markerPoints.get(0);
LatLng dest = markerPoints.get(1);
// Initializing
markerPoints = new ArrayList<LatLng>();
@Override
public void onMapClick(LatLng point) {
343
// Checks, whether start and end locations are captured
if(markerPoints.size() >= 2){
LatLng origin = markerPoints.get(0);
LatLng dest = markerPoints.get(1);
for(int i=0;i<markerPoints.size();i++){
// Creating MarkerOptions
MarkerOptions options = new MarkerOptions();
/**
* For the start location, the color of marker is GREEN and
* for the end location, the color of marker is RED.
*/
if(i==0){
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
;
}else if(i==1){
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
}
344
}
}
private String getDirectionsUrl(LatLng origin,LatLng dest){
// Origin of route
String str_origin = "origin="+origin.latitude+","+origin.longitude;
// Destination of route
String str_dest = "destination="+dest.latitude+","+dest.longitude;
// Sensor enabled
String sensor = "sensor=false";
// Travelling Mode
String mode = "mode=driving";
if(rbDriving.isChecked()){
mode = "mode=driving";
mMode = 0 ;
}else if(rbBiCycling.isChecked()){
mode = "mode=bicycling";
mMode = 1;
}else if(rbWalking.isChecked()){
mode = "mode=walking";
mMode = 2;
}
// Output format
String output = "json";
return url;
}
345
HttpURLConnection urlConnection = null;
try{
URL url = new URL(strUrl);
// Connecting to url
urlConnection.connect();
data = sb.toString();
br.close();
}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
urlConnection.disconnect();
}
return data;
}
346
try{
// Fetching the data from web service
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try{
jObject = new JSONObject(jsonData[0]);
DirectionsJSONParser parser = new DirectionsJSONParser();
347
return routes;
}
points.add(position);
}
if(result.size()<1){
Toast.makeText(getBaseContext(), "No Points",
348
Toast.LENGTH_SHORT).show();
return;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}
DirectionsJSONParser.java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.android.gms.maps.model.LatLng;
/** Receives a JSONObject and returns a list of lists containing latitude and
longitude */
public List<List<HashMap<String,String>>> parse(JSONObject jObject){
try {
349
jRoutes = jObject.getJSONArray("routes");
/**
* Method to decode polyline points
* Courtesy : jeffreysambells.com/2010/05/27/decoding-polylines-from-google-maps-
direction-api-with-java
* */
350
private List<LatLng> decodePoly(String encoded) {
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<RadioGroup
351
android:id="@+id/rg_modes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="horizontal" >
<RadioButton android:id="@+id/rb_driving"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/str_rb_driving"
android:checked="true" />
<RadioButton android:id="@+id/rb_bicycling"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/str_rb_bicycling" />
<RadioButton android:id="@+id/rb_walking"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/str_rb_walking" />
</RadioGroup>
<fragment
android:id="@+id/map"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@id/rg_modes"
class="com.google.android.gms.maps.SupportMapFragment" />
</RelativeLayout>
Android Manifest.xml
<permission
android:name="com.example.manju.myapplication.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission
352
android:name="com.example.manju.myapplication.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission
android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyChFgoCG01fzZeXxxEvL-f7yElcekl3vwA"/>
</application>
</manifest>
String.xml
353
Class Time Table
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.content.Intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
{
Intent i = new Intent(MainActivity.this, ListBatchesActivity.class);
startActivity(i);
}
}
}
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
ListView listBatches;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listbatches);
354
}
@Override
public void onStart() {
super.onStart();
listBatches = (ListView) this.findViewById(R.id.listBatches);
BatchesAdapter adapter = new BatchesAdapter(this);
listBatches.setAdapter(adapter);
}
AddBatchActivity
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
@Override
public void onCreate(Bundle savedInstanceState) {
355
super.onCreate(savedInstanceState);
setContentView(R.layout.addbatch);
setDateToSysdate();
updateDateDisplay();
if ( done )
Toast.makeText(this,"Added batch successfully!",
Toast.LENGTH_LONG).show();
else
Toast.makeText(this,"Sorry! Could not add batch!",
Toast.LENGTH_LONG).show();
}
356
public void showDatePicker(View v) {
showDialog(DATE_DIALOG);
}
@Override
protected Dialog onCreateDialog(int id) {
super.onCreateDialog(id);
switch (id) {
case DATE_DIALOG:
return new DatePickerDialog(this, dateSetListener, year, month, day);
case TIME_DIALOG:
return new TimePickerDialog(this, timeSetListener, hours,mins, false);
}
return null;
}
public void onDateSet(DatePicker view, int pYear, int pMonth, int pDay) {
year = pYear;
month = pMonth;
day = pDay;
updateDateDisplay();
}
};
@Override
public void onTimeSet(TimePicker arg0, int pHours, int pMins) {
hours = pHours;
mins = pMins;
updateTimeDisplay();
}
357
};
AddClassActivity
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
358
setContentView(R.layout.addclass);
textBatchCode.setText( getIntent().getStringExtra("batchcode"));
setDateToSysdate();
updateDateDisplay();
}
if ( done )
Toast.makeText(this,"Added Class Successfully!",
Toast.LENGTH_LONG).show();
else
Toast.makeText(this,"Sorry! Could not add class!",
Toast.LENGTH_LONG).show();
}
359
showDialog(DATE_DIALOG);
}
@Override
protected Dialog onCreateDialog(int id) {
super.onCreateDialog(id);
switch (id) {
case DATE_DIALOG:
return new DatePickerDialog(this, dateSetListener, year, month, day);
case TIME_DIALOG:
return new TimePickerDialog(this, timeSetListener, hours,mins, false);
}
return null;
}
public void onDateSet(DatePicker view, int pYear, int pMonth, int pDay) {
year = pYear;
month = pMonth;
day = pDay;
updateDateDisplay();
}
};
@Override
public void onTimeSet(TimePicker arg0, int pHours, int pMins) {
hours = pHours;
mins = pMins;
updateTimeDisplay();
}
};
360
private void updateDateDisplay() {
// Month is 0 based so add 1
textClassDate.setText(String.format("%04d-%02d-%02d", year, month + 1,day));
}
Batch
361
public String getEnddate() {
return enddate;
}
362
public void setRemarks(String remarks) {
this.remarks = remarks;
}
BatchesAdapter
import java.util.ArrayList;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
@Override
public int getCount() {
return batches.size();
}
@Override
public Object getItem(int pos) {
return batches.get(pos);
}
@Override
public long getItemId(int position) {
363
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.batch, null);
Button btnClasses = (Button) convertView.findViewById(R.id.btnClasses);
Button btnUpdate = (Button) convertView.findViewById(R.id.btnUpdate);
Button btnAddClass = (Button) convertView.findViewById(R.id.btnAddClass);
btnClasses.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Context context = view.getContext();
Intent intent = new Intent(context, ListClassesActivity.class);
intent.putExtra("batchcode",batch.getCode());
context.startActivity(intent);
}
});
btnAddClass.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Context context = view.getContext();
Intent intent = new Intent(context, AddClassActivity.class);
364
intent.putExtra("batchcode",batch.getCode());
context.startActivity(intent);
}
});
btnUpdate.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Class
365
this.classId = classId;
}
366
return remarks;
}
ClassSchedulerActivity
import android.app.Activity;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
}
}
Database
import java.util.ArrayList;
import java.util.Calendar;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
367
public static final String BATCHES_BATCHCODE = "batchcode";
public static final String BATCHES_COURSE = "course";
public static final String BATCHES_STARTDATE = "startdate";
public static final String BATCHES_STARTTIME = "starttime";
public static final String BATCHES_CLASSES = "classes";
public static final String BATCHES_PERIOD = "period";
public static final String BATCHES_CLASSESPERWEEK = "classesperweek";
public static final String BATCHES_REMARKS = "remarks";
368
classes.getColumnIndex(Database.CLASSES_CLASSES_ID)));
cls.setBatchCode( classes.getString(
classes.getColumnIndex(Database.CLASSES_BATCHCODE)));
cls.setClassDate( classes.getString(
classes.getColumnIndex(Database.CLASSES_CLASSDATE)));
cls.setClassTime( classes.getString(
classes.getColumnIndex(Database.CLASSES_CLASSTIME)));
cls.setPeriod( classes.getString(
classes.getColumnIndex(Database.CLASSES_CLASSPERIOD)));
cls.setTopics( classes.getString(
classes.getColumnIndex(Database.CLASSES_TOPICS)));
cls.setRemarks( classes.getString(
classes.getColumnIndex(Database.CLASSES_REMARKS)));
return cls;
}
if ( adjust ) {
// delete last class for the batch
boolean deleted = deleteLastClass(db,batchCode);
if ( !deleted) {
db.endTransaction();
return false;
}
}
369
values.put(Database.CLASSES_TOPICS,topics);
if ( rowid >=0 ) {
db.setTransactionSuccessful();
db.endTransaction();
return true;
}
else {
db.endTransaction();
return false;
}
}
catch(Exception ex) {
Log.d("CS", "Error in addClass -->" + ex.getMessage());
return false;
}
finally {
if (db != null && db.isOpen()) {
db.close();
}
}
}
if ( lastClass.moveToFirst() ) {
classid = lastClass.getString( lastClass.getColumnIndex(
Database.CLASSES_CLASSES_ID));
int rows =
db.delete(Database.CLASSES_TABLE_NAME,Database.CLASSES_CLASSES_ID + " = ?",
new String[] { classid} );
done = rows == 1;
370
}
lastClass.close();
return done;
}
catch (Exception ex) {
Log.d("Account", "Error in deleteLastClass-->" + ex.getMessage());
return false;
}
} // deleteLastClass
int rows =
db.delete(Database.CLASSES_TABLE_NAME,Database.CLASSES_CLASSES_ID + " = ?",
new String[] { classid} );
if ( rows == 1)
{
// add a class after the last class
if ( addAfterLastClass(db,batchCode))
{
db.setTransactionSuccessful();
db.endTransaction();
return true;
}
}
db.endTransaction();
return false;
371
catch (Exception ex) {
Log.d("CS", "Error in cancelClass-->" + ex.getMessage());
return false;
}
finally {
if (db != null && db.isOpen()) {
db.close();
}
}
372
// insert with new data
lastClass.close();
ContentValues values = new ContentValues();
values.put(Database.CLASSES_BATCHCODE, batch.getCode());
values.put(Database.CLASSES_CLASSDATE, calendarToString(c));
values.put(Database.CLASSES_CLASSTIME, batch.getStarttime());
values.put(Database.CLASSES_CLASSPERIOD, batch.getPeriod());
values.put(Database.CLASSES_REMARKS,"");
values.put(Database.CLASSES_TOPICS,"");
373
} // deleteClass
db.setTransactionSuccessful();
db.endTransaction();
return true;
} catch (Exception ex) {
Log.d("Account", "Error in addTransaction -->" + ex.getMessage());
return false;
} finally {
if (db != null && db.isOpen()) {
db.close();
}
}
} // addBatch
374
public static boolean updateBatch(Context context, String batchcode,
String course, String starttime,String period,
String remarks) {
db.endTransaction();
return true;
} catch (Exception ex) {
Log.d("Account", "Error in updateBatch-->" + ex.getMessage());
return false;
} finally {
if (db != null && db.isOpen()) {
db.close();
}
}
} // updateBatch
375
try {
dbhelper = new DBHelper(context);
db = dbhelper.getWritableDatabase();
int rows =
db.delete(Database.CLASSES_TABLE_NAME,Database.BATCHES_BATCHCODE + " = ?",
new String[] { batchcode} );
rows = db.delete(Database.BATCHES_TABLE_NAME,Database.BATCHES_BATCHCODE +
" = ?",
376
new String[] { batchcode} );
if ( rows == 1)
db.setTransactionSuccessful();
db.endTransaction();
return true;
} catch (Exception ex) {
Log.d("Account", "Error in deleteBatch-->" + ex.getMessage());
return false;
} finally {
if (db != null && db.isOpen()) {
db.close();
}
}
} // deleteBatch
if (dow == 1)
return 7;
else
return dow - 1;
}
377
Calendar c = Calendar.getInstance();
c.set(year, month, day);
int classnumber = 1;
do {
int dow = c.get(Calendar.DAY_OF_WEEK);
} // addClasses
while (batches.moveToNext()) {
Batch batch = Database.cursorToBatch(batches);
String enddate = getEndDate(db, batch.getCode());
batch.setEnddate(enddate);
378
list.add(batch);
}
batches.close();
db.close();
dbhelper.close();
return list;
} // getBatches
while (classes.moveToNext()) {
Class cls = Database.cursorToClass(classes);
list.add(cls);
}
classes.close();
db.close();
dbhelper.close();
return list;
} // getBatches
379
new String [] { batchcode},
null, null, null, null);
Batch batch;
if ( batches.moveToNext() )
batch = Database.cursorToBatch(batches);
else
batch = null;
batches.close();
return batch;
}
} // getBatch
classes.close();
380
db.close();
dbhelper.close();
return clas;
} // getBatch
DBHelper
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
@Override
public void onCreate(SQLiteDatabase db) {
createTables(db);
}
@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
381
Database.BATCHES_CLASSES + " integer," +
Database.BATCHES_PERIOD + " integer," +
Database.BATCHES_CLASSESPERWEEK + " integer," +
Database.BATCHES_REMARKS + " TEXT)";
try {
database.execSQL(batches_table_sql);
database.execSQL("insert into batches (batchcode,course,
startdate,starttime,classes,period,classesperweek,remarks)"
+ "values ('HB2404','Hibernate','2012-04-
24','19:00',6,90,6,'Short course')");
database.execSQL(classes_table_sql);
382
+ "values ('HB2404','2012-04-30','19:00',90,null,'Last
class')");
Log.d("CS","Tables created!");
}
catch(Exception ex) {
Log.d("CS", "Error in DBHelper.onCreate() : " + ex.getMessage());
}
}
ListBatchesActivity
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
ListView listBatches;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listbatches);
}
@Override
public void onStart() {
super.onStart();
listBatches = (ListView) this.findViewById(R.id.listBatches);
BatchesAdapter adapter = new BatchesAdapter(this);
listBatches.setAdapter(adapter);
}
383
}
ListClassesActivity
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import java.util.List;
String batchcode;
TableLayout tableClasses;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listclasses);
@Override
public void onStart() {
super.onStart();
deleteRowsFromTable();
addRowsToTable(tableClasses,batchcode);
}
384
private void addRowsToTable(TableLayout table, String batchcode) {
int classno = 1;
for(final Class c : classes) {
TableRow row = (TableRow)
LayoutInflater.from(this).inflate(R.layout.classrow, null);
((TextView)row.findViewById(R.id.textNo)).setText(
String.valueOf(classno));
((TextView)row.findViewById(R.id.textDate)).setText(c.getClassDate());
((TextView)row.findViewById(R.id.textTime)).setText(c.getClassTime());
table.addView(row);
line.addView(tv);
table.addView(line);
385
classno ++;
}
UpdateBatchActivity
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.updatebatch);
386
editPeriod = (EditText) this.findViewById(R.id.editPeriod) ;
textClasses = (TextView) this.findViewById(R.id.textClasses) ;
textClassesPerWeek = (TextView) this.findViewById(R.id.textClassesPerWeek) ;
editRemarks = (EditText) this.findViewById(R.id.editRemarks) ;
setDateToStartDate( batch.getStartdate());
setTimeToStartTime( batch.getStarttime());
}
387
boolean done = Database.updateBatch(this,
editBatchcode.getText().toString(),
editCourse.getText().toString(),
textStartTime.getText().toString(),
editPeriod.getText().toString(),
editRemarks.getText().toString());
if ( done )
Toast.makeText(this,"Updated batch successfully!",
Toast.LENGTH_LONG).show();
else
Toast.makeText(this,"Sorry! Could not update batch!",
Toast.LENGTH_LONG).show();
@Override
protected Dialog onCreateDialog(int id) {
super.onCreateDialog(id);
switch (id) {
case DATE_DIALOG:
return new DatePickerDialog(this, dateSetListener, year, month, day);
case TIME_DIALOG:
return new TimePickerDialog(this, timeSetListener, hours,mins, false);
case DELETE_ALERT_DIALOG:
return getAlertDialog();
}
return null;
388
}
public void onDateSet(DatePicker view, int pYear, int pMonth, int pDay) {
year = pYear;
month = pMonth;
day = pDay;
updateDateDisplay();
}
};
@Override
public void onTimeSet(TimePicker arg0, int pHours, int pMins) {
hours = pHours;
mins = pMins;
updateTimeDisplay();
}
};
389
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
boolean done =
Database.deleteBatch(UpdateBatchActivity.this, editBatchcode.getText().toString());
if ( done ) {
Toast.makeText(UpdateBatchActivity.this,"Deleted
batch successfully!", Toast.LENGTH_LONG).show();
UpdateBatchActivity.this.finish();
}
else
Toast.makeText(UpdateBatchActivity.this,"Sorry!
Could not delete batch!", Toast.LENGTH_LONG).show();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
return builder.create();
}
UpdateClassActivity
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
390
private static final int TIME_DIALOG = 1;
private static final int CANCEL_ALERT_DIALOG = 2;
private static final int DELETE_ALERT_DIALOG = 3;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.updateclass);
391
private void setTimeToStartTime(String starttime) {
String [] parts = starttime.split(":");
hours = Integer.parseInt( parts[0]);
mins =Integer.parseInt( parts[1]);
}
if ( done )
Toast.makeText(this,"Updated class successfully!",
Toast.LENGTH_LONG).show();
else
Toast.makeText(this,"Sorry! Could not update class!",
Toast.LENGTH_LONG).show();
}
@Override
protected Dialog onCreateDialog(int id) {
super.onCreateDialog(id);
switch (id) {
case TIME_DIALOG:
return new TimePickerDialog(this, timeSetListener, hours,mins, false);
case CANCEL_ALERT_DIALOG:
392
return getCancelAlertDialog();
case DELETE_ALERT_DIALOG:
return getDeleteAlertDialog();
}
return null;
}
@Override
public void onTimeSet(TimePicker arg0, int pHours, int pMins) {
hours = pHours;
mins = pMins;
updateTimeDisplay();
}
};
boolean done =
Database.deleteClass(UpdateClassActivity.this, classid);
if ( done ) {
Toast.makeText(UpdateClassActivity.this,"Deleted
Class Successfully!", Toast.LENGTH_LONG).show();
UpdateClassActivity.this.finish();
}
else
Toast.makeText(UpdateClassActivity.this,"Sorry!
393
Could not delete class!", Toast.LENGTH_LONG).show();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
return builder.create();
}
394
activity_main.xml
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button1"
android:id="@+id/Bdisplay"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="177dp"
android:onClick="onButtonClick" />
</RelativeLayout>
Addbatch.xml
<TableLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:stretchColumns="1" >
<TableRow >
<TextView
android:id="@+id/textView1"
android:layout_width="100dp"
android:layout_height="wrap_content"
395
android:text="Code" />
<EditText
android:id="@+id/editBatchCode"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<requestFocus />
</EditText>
</TableRow>
<TableRow >
<TextView
android:id="@+id/textView1"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Course" />
<EditText
android:id="@+id/editCourse"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</EditText>
</TableRow>
<TableRow >
<TextView
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Start Date" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="showDatePicker"
android:src="@mipmap/ic_launcher" >
</ImageButton>
<TextView
396
android:id="@+id/textStartDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="2012-04-24" >
</TextView>
</LinearLayout>
</TableRow>
<TableRow >
<TextView
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Start Time" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="showTimePicker"
android:src="@mipmap/ic_launcher" >
</ImageButton>
<TextView
android:id="@+id/textStartTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="19:00" >
</TextView>
</LinearLayout>
</TableRow>
<TableRow >
<TextView
android:id="@+id/textView1"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="No. Classes" />
397
<EditText
android:id="@+id/editClasses"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number" >
</EditText>
</TableRow>
<TableRow >
<TextView
android:id="@+id/textView1"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:text="Classes Per Week" />
<EditText
android:id="@+id/editClassesPerWeek"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number" >
</EditText>
</TableRow>
<TableRow >
<TextView
android:id="@+id/textView1"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Period (Min)" />
<EditText
android:id="@+id/editPeriod"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number" >
</EditText>
</TableRow>
<TableRow >
398
<TextView
android:id="@+id/textView1"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Remarks" />
<EditText
android:id="@+id/editRemarks"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</EditText>
</TableRow>
<TableRow >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="addBatch"
android:text="Add Batch" >
</Button>
</TableRow>
</TableLayout>
</ScrollView>
Addclass.xml
<TextView
android:id="@+id/textBatchCode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
399
android:textSize="20sp"
android:text="Hib2404" >
</TextView>
</TableRow>
<TableRow >
<TextView
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Class Date" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="showDatePicker"
android:src="@mipmap/ic_launcher" >
</ImageButton>
<TextView
android:id="@+id/textClassDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="2012-04-24" >
</TextView>
</LinearLayout>
</TableRow>
<TableRow >
<TextView
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Class Time" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageButton
400
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="showTimePicker"
android:src="@mipmap/ic_launcher" >
</ImageButton>
<TextView
android:id="@+id/textClassTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="19:00" >
</TextView>
</LinearLayout>
</TableRow>
<TableRow >
<TextView
android:id="@+id/textView1"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Period (Min)" />
<EditText
android:id="@+id/editPeriod"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:inputType="number" >
</EditText>
</TableRow>
<TableRow >
<TextView
android:id="@+id/textView1"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Topics" />
401
<EditText
android:id="@+id/editTopics"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</EditText>
</TableRow>
<TableRow >
<TextView
android:id="@+id/textView1"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Remarks" />
<EditText
android:id="@+id/editRemarks"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</EditText>
</TableRow>
<TableRow android:layout_span="2">
<CheckBox
android:id="@+id/chkAdjust"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Adjust Last Class?" >
</CheckBox>
</TableRow>
</TableLayout>
402
Batch.xml
<TextView
android:id="@+id/textCode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="code"
android:textSize="16sp" />
<TextView
android:id="@+id/textCourse"
android:gravity="right"
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp"
android:text="Course"/>
</LinearLayout>
<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/textStartDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp"
android:text="stdate" />
<TextView
android:id="@+id/textEndDate"
android:gravity="right"
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp"
android:text="EndDate"/>
403
</LinearLayout>
<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
<Button
android:id="@+id/btnClasses"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:text="List Classes" />
<Button
android:id="@+id/btnAddClass"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:text="Add Class" />
<Button
android:id="@+id/btnUpdate"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:text="Update" />
</LinearLayout>
<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="3dp"
android:background="#ff0000"
android:text="" />
</LinearLayout>
</LinearLayout>
404
Classrow.xml
<TextView
android:id="@+id/textNo"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:gravity="center"
android:text="no" />
<TextView
android:id="@+id/textDate"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Date" />
<TextView
android:id="@+id/textTime"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Time" />
<ImageButton
android:id="@+id/btnUpdate"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_gravity="center"
android:adjustViewBounds="true"
android:src="@mipmap/ic_launcher"
android:textSize="12sp" />
</TableRow>
Listbatches.xml
405
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="@+id/listBatches"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
<Button
android:id="@+id/butAddBatch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="addBatch"
android:layout_gravity="center_horizontal"
android:text="Add New Batch" />
</LinearLayout>
Listclasses.xml
<TableLayout
android:id="@+id/tableClasses"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:stretchColumns="*">
<TableRow android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="80dp"
android:gravity="center"
android:layout_height="wrap_content"
android:text="Class No." />
406
<TextView
android:layout_width="80dp"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Class Date" />
<TextView
android:layout_width="80dp"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Class Time" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="" />
</TableRow>
<TableRow android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_span="4"
android:layout_height="3dp"
android:background="#ff0000"
android:text="" />
</TableRow>
</TableLayout>
</ScrollView>
Main.xml
407
</LinearLayout>
Updatebatch.xml
<TableLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:stretchColumns="1" >
<TableRow >
<TextView
android:id="@+id/textView1"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Code" />
<EditText
android:id="@+id/editBatchCode"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<requestFocus />
</EditText>
</TableRow>
<TableRow >
<TextView
android:id="@+id/textView1"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Course" />
<EditText
android:id="@+id/editCourse"
408
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</EditText>
</TableRow>
<TableRow >
<TextView
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Start Date" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textStartDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="2012-04-24"
android:textSize="20sp" >
</TextView>
</LinearLayout>
</TableRow>
<TableRow >
<TextView
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Start Time" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageButton
android:layout_width="wrap_content"
409
android:layout_height="wrap_content"
android:onClick="showTimePicker"
android:src="@mipmap/ic_launcher" >
</ImageButton>
<TextView
android:id="@+id/textStartTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="19:00"
android:textSize="20sp" >
</TextView>
</LinearLayout>
</TableRow>
<TableRow >
<TextView
android:id="@+id/textView1"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="No. Classes" />
<TextView
android:id="@+id/textClasses"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp" />
</TableRow>
<TableRow >
<TextView
android:id="@+id/textView1"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:text="Classes Per Week" />
410
<TextView
android:id="@+id/textClassesPerWeek"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp" />
</TableRow>
<TableRow >
<TextView
android:id="@+id/textView1"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Period (Min)" />
<EditText
android:id="@+id/editPeriod"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number" >
</EditText>
</TableRow>
<TableRow >
<TextView
android:id="@+id/textView1"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Remarks" />
<EditText
android:id="@+id/editRemarks"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</EditText>
</TableRow>
<TableRow>
<LinearLayout
android:layout_span="2"
411
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="updateBatch"
android:text="Update" >
</Button>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="deleteBatch"
android:text="Delete" >
</Button>
</LinearLayout>
</TableRow>
</TableLayout>
</ScrollView>
Updateclass.xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Batch Code " />
<TextView
android:id="@+id/textBatchCode"
android:layout_width="wrap_content"
412
android:layout_height="wrap_content"
android:text="Hib2404"
android:textSize="20sp" >
</TextView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Class Date" />
<TextView
android:id="@+id/textClassDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2012-04-24"
android:textSize="20sp" >
</TextView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Class Time" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="showTimePicker"
android:src="@mipmap/ic_launcher" >
</ImageButton>
<TextView
android:id="@+id/textClassTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
413
android:paddingRight="10dp"
android:text="00:00"
android:textSize="20sp" >
</TextView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView1"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Period (Min)" />
<EditText
android:id="@+id/editPeriod"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:inputType="number" >
</EditText>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView1"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Topics" />
<EditText
android:id="@+id/editTopics"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</EditText>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
414
<TextView
android:id="@+id/textView1"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Remarks" />
<EditText
android:id="@+id/editRemarks"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</EditText>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="updateClass"
android:text="Update" >
</Button>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="cancelClass"
android:text="Cancel Class" >
</Button>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="deleteClass"
android:text="Delete" >
</Button>
</LinearLayout>
</LinearLayout>
</ScrollView>
415
String.xml
<resources>
<string name="app_name">My Application</string>
<string name="action_settings">Settings</string>
<string name="hello">Hello World, ClassSchedulerActivity!</string>
</resources>
Manifest.xml file
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
416
<activity android:label="Update Batch" android:name=".UpdateBatchActivity"/>
</application>
</manifest>
ListAccounts.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
ListView listAccounts;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listaccounts);
listAccounts = (ListView) this.findViewById(R.id.listAccounts);
listAccounts.setOnItemClickListener( new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View selectedView, int
417
arg2,long arg3) {
TextView textAccountId = (TextView)
selectedView.findViewById(R.id.textAccountId);
Log.d("Accounts", "Selected Account Id : " +
textAccountId.getText().toString());
Intent intent = new Intent(ListAccounts.this, UpdateAccount.class);
intent.putExtra("accountid", textAccountId.getText().toString());
startActivity(intent);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return Utils.inflateMenu(this,menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return Utils.handleMenuOption(this,item);
}
@Override
public void onStart() {
super.onStart();
try {
DBHelper dbhelper = new DBHelper(this);
SQLiteDatabase db = dbhelper.getReadableDatabase();
Cursor accounts = db.query(
Database.ACCOUNTS_TABLE_NAME,null,null,null,null,null,null);
418
Toast.makeText(this, ex.getMessage(), Toast.LENGTH_LONG).show();
}
}
Account.java
419
}
@Override
public String toString() {
return holder + " - " + bank;
}
AddAccount.java
import android.app.Activity;
import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
420
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addaccount);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return Utils.inflateMenu(this,menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return Utils.handleMenuOption(this,item);
}
try {
DBHelper dbhelper = new DBHelper(this);
SQLiteDatabase db = dbhelper.getWritableDatabase();
Log.d("Account","Got Writable database");
// execute insert command
421
values.put( Database.ACCOUNTS_CNO, editCno.getText().toString());
values.put( Database.ACCOUNTS_HOLDERS, editHolders.getText().toString());
values.put( Database.ACCOUNTS_BANK, editBankName.getText().toString());
values.put( Database.ACCOUNTS_BRANCH,
editBranchName.getText().toString());
values.put( Database.ACCOUNTS_ADDRESS, editAddress.getText().toString());
values.put( Database.ACCOUNTS_IFSC, editIFSC.getText().toString());
values.put( Database.ACCOUNTS_MICR, editMICR.getText().toString());
values.put( Database.ACCOUNTS_BALANCE, editBalance.getText().toString());
values.put( Database.ACCOUNTS_REMARKS, editRemarks.getText().toString());
AddTransaction
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
422
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_transaction);
spinnerAccounts = (Spinner) this.findViewById(R.id.spinnerAccounts);
Database.populateAccounts(spinnerAccounts);
textTransDate = (TextView) this.findViewById(R.id.textTransDate);
// get the current date
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
updateDateDisplay();
}
@Override
public void onStart() {
super.onStart();
423
public void showDateDialog(View v) {
showDialog(DATE_DIALOG);
}
@Override
protected Dialog onCreateDialog(int id) {
super.onCreateDialog(id);
switch (id) {
case DATE_DIALOG:
return new DatePickerDialog(this,
dateSetListener, year, month, day);
}
return null;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return Utils.inflateMenu(this,menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return Utils.handleMenuOption(this,item);
}
424
boolean done = Database.addTransaction(this,
accountId,
radioDeposit.isChecked() ? "d" : "w", // trans type
textTransDate.getText().toString(),
editTransAmount.getText().toString(),
editChequeNo.getText().toString(),
editChequeParty.getText().toString(),
editChequeDetails.getText().toString(),
editRemarks.getText().toString());
if ( done )
Toast.makeText(this,"Added Transaction Successfully!",
Toast.LENGTH_LONG).show();
else
Toast.makeText(this, "Sorry Could Not Add Transaction!",
Toast.LENGTH_LONG).show();
} // addDeposit
}
Database
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.Spinner;
425
public static final String ACCOUNTS_BALANCE = "balance";
public static final String ACCOUNTS_LASTTRANS = "last_tran_date";
public static final String ACCOUNTS_REMARKS = "remarks";
account.setHolder(accounts.getString(accounts.getColumnIndex(Database.ACCOUNTS_HOLDERS
)));
account.setBank(
accounts.getString(accounts.getColumnIndex(Database.ACCOUNTS_BANK)));
return account;
}
//
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
while (accounts.moveToNext()) {
Account account = Database.cursorToAccount(accounts);
list.add(account);
}
accounts.close();
db.close();
dbhelper.close();
426
ArrayAdapter<Account> adapter = new ArrayAdapter<Account>(context,
android.R.layout.simple_spinner_item,list);
spinnerAccounts.setAdapter(adapter);
}
427
ContentValues values = new ContentValues();
values.put(Database.TRANSACTIONS_ACCOUNT_ID, accountId);
values.put(Database.TRANSACTIONS_TRANSDATE, transDate);
values.put(Database.TRANSACTIONS_TRANSAMOUNT, transAmount);
values.put(Database.TRANSACTIONS_CHEQUE_NO, chequeNo);
values.put(Database.TRANSACTIONS_CHEQUE_PARTY, chequeParty);
values.put(Database.TRANSACTIONS_CHEQUE_DETAILS,chequeDetails);
values.put(Database.TRANSACTIONS_REMARKS, remarks);
values.put(Database.TRANSACTIONS_TRANSTYPE, transType);
428
DBHelper.java
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
@Override
public void onCreate(SQLiteDatabase db) {
createTables(db);
}
@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
429
String transactions_table_sql = "create table " +
Database.TRANSACTIONS_TABLE_NAME + " ( " +
Database.TRANSACTIONS_ID + " integer primary key autoincrement," +
Database.TRANSACTIONS_ACCOUNT_ID + " TEXT," +
Database.TRANSACTIONS_TRANSDATE + " TEXT," +
Database.TRANSACTIONS_TRANSAMOUNT + " FLOAT," +
Database.TRANSACTIONS_TRANSTYPE+ " TEXT," +
Database.TRANSACTIONS_CHEQUE_NO + " TEXT," +
Database.TRANSACTIONS_CHEQUE_PARTY + " TEXT," +
Database.TRANSACTIONS_CHEQUE_DETAILS+ " TEXT," +
Database.TRANSACTIONS_REMARKS + " TEXT)";
try {
database.execSQL(account_table_sql);
database.execSQL(transactions_table_sql);
Log.d("Accounts","Tables created!");
}
catch(Exception ex) {
Log.d("Accounts", "Error in DBHelper.onCreate() : " + ex.getMessage());
}
}
ListAccountTransactions.java
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.opengl.Visibility;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
430
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_account_transactions);
accountId = this.getIntent().getStringExtra("accountid");
listTransactions = (ListView) this.findViewById(R.id.listTransactions);
listTransactions.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View selectedView,
int arg2, long arg3) {
TextView textTransId = (TextView) selectedView
.findViewById(R.id.textTransId);
Intent intent = new Intent(ListAccountTransactions.this,
TransactionDetails.class);
intent.putExtra("transid", textTransId.getText().toString());
startActivity(intent);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return Utils.inflateMenu(this, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return Utils.handleMenuOption(this, item);
}
@Override
public void onStart() {
431
super.onStart();
try {
DBHelper dbhelper = new DBHelper(this);
SQLiteDatabase db = dbhelper.getReadableDatabase();
Cursor trans = db.query(Database.TRANSACTIONS_TABLE_NAME, null,
Database.TRANSACTIONS_ACCOUNT_ID + " = ?",
new String[] { accountId }, null, null,
Database.TRANSACTIONS_TRANSDATE + " desc");
432
}
trans.close();
db.close();
dbhelper.close();
listTransactions.setAdapter(adapter);
} catch (Exception ex) {
Toast.makeText(this, ex.getMessage(), Toast.LENGTH_LONG).show();
}
}
ListRecentTransactions.java
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
433
String condition = " 1 = 1 ";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_transactions);
listTransactions = (ListView) this.findViewById(R.id.listTransactions);
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return Utils.inflateMenu(this,menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return Utils.handleMenuOption(this,item);
}
@Override
public void onStart() {
super.onStart();
try {
DBHelper dbhelper = new DBHelper(this);
SQLiteDatabase db = dbhelper.getReadableDatabase();
Cursor trans = db.rawQuery("select t._id, acno,bank,
transdate,transamount,transtype,cheque_no,cheque_party,cheque_details, t.remarks from
transactions t inner join accounts a on ( a._id = t.account_id) order by transdate
desc LIMIT 10",null);
if ( trans.getCount() == 0 )
this.findViewById(R.id.textError).setVisibility(View.VISIBLE);
434
else
this.findViewById(R.id.textError).setVisibility(View.INVISIBLE);
tran.put("transdate",trans.getString(trans.getColumnIndex(Database.TRANSACTIONS_TRANSD
ATE)));
tran.put("transtype",trans.getString(trans.getColumnIndex(Database.TRANSACTIONS_TRANST
YPE)));
tran.put("transamount",trans.getString(trans.getColumnIndex(Database.TRANSACTIONS_TRAN
SAMOUNT)));
tran.put("transremarks",trans.getString(trans.getColumnIndex(Database.TRANSACTIONS_REM
ARKS)));
String chequeno =
trans.getString(trans.getColumnIndex(Database.TRANSACTIONS_CHEQUE_NO));
String transDetails = "Cash";
if (! chequeno.trim().equals(""))
transDetails = "Cheque No: " + chequeno;
tran.put("transdetails",transDetails);
listTrans.add(tran);
}
trans.close();
db.close();
dbhelper.close();
435
"transtype", "transamount" ,"transremarks"},
new int [] { R.id.textTransId, R.id.textAcno,
R.id.textTransDate, R.id.textTransDetails, R.id.textTransType, R.id.textTransAmount,
R.id.textTransRemarks});
listTransactions.setAdapter(adapter);
} catch (Exception ex) {
Toast.makeText(this, ex.getMessage(), Toast.LENGTH_LONG).show();
}
}
SearchTransactions.java
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
436
setContentView(R.layout.search_transactions);
editFromDate = (EditText) this.findViewById(R.id.editFromDate);
editToDate = (EditText) this.findViewById(R.id.editToDate);
updateToDateDisplay();
updateFromDateDisplay();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return Utils.inflateMenu(this,menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return Utils.handleMenuOption(this,item);
}
437
toYear = pYear;
toMonth = pMonth;
toDay = pDay;
updateToDateDisplay();
}
};
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case FROM_DATE_DIALOG:
return new DatePickerDialog(this,
fromDateSetListener, fromYear, fromMonth, fromDay);
case TO_DATE_DIALOG:
return new DatePickerDialog(this,
toDateSetListener, toYear, toMonth, toDay);
}
return null;
}
438
startActivity(intent);
}
editFromDate.setText("");
editToDate.setText("");
editFromAmount.setText("");
editToAmount.setText("");
}
TransactionDetails.java
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
transId = this.getIntent().getStringExtra("transid");
Log.d("Account", "Trans id : " + transId);
439
textAcno = (TextView) this.findViewById(R.id.textAcno);
TextView textTransDate = (TextView) this.findViewById(R.id.textTransDate);
TextView textTransType = (TextView) this.findViewById(R.id.textTransType);
TextView textTransAmount = (TextView) this.findViewById(R.id.textTransAmount);
TextView textChequeNo = (TextView) this.findViewById(R.id.textChequeNo);
TextView textChequeParty = (TextView) this.findViewById(R.id.textChequeParty);
TextView textChequeDetails = (TextView)
this.findViewById(R.id.textChequeDetails);
TextView textRemarks = (TextView) this.findViewById(R.id.textTransRemarks);
if (tran.moveToFirst()) {
accountId =
tran.getString(tran.getColumnIndex(Database.TRANSACTIONS_ACCOUNT_ID));
textAcno.setText(
tran.getString(tran.getColumnIndex(Database.ACCOUNTS_ACNO)));
textTransDate.setText(
tran.getString(tran.getColumnIndex(Database.TRANSACTIONS_TRANSDATE)));
textTransType.setText(
tran.getString(tran.getColumnIndex(Database.TRANSACTIONS_TRANSTYPE)));
textTransAmount.setText(
tran.getString(tran.getColumnIndex(Database.TRANSACTIONS_TRANSAMOUNT)));
textChequeNo.setText(
tran.getString(tran.getColumnIndex(Database.TRANSACTIONS_CHEQUE_NO)));
textChequeParty.setText(
tran.getString(tran.getColumnIndex(Database.TRANSACTIONS_CHEQUE_PARTY)));
textChequeDetails.setText(
tran.getString(tran.getColumnIndex(Database.TRANSACTIONS_CHEQUE_DETAILS)));
textRemarks.setText(tran.getString(tran.getColumnIndex(Database.TRANSACTIONS_REMARKS))
);
}
else
Log.d("Accounts","No transaction found!");
440
db.close();
dbhelper.close();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return Utils.inflateMenu(this,menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return Utils.handleMenuOption(this,item);
}
441
}
else
Toast.makeText(this, "Could not delet transaction!",
Toast.LENGTH_LONG).show();
}
catch (Exception ex) {
Toast.makeText(this, ex.getMessage(), Toast.LENGTH_LONG).show();
}
}
UpdateAccount.java
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
@Override
442
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.update_account);
editAcno = (EditText) this.findViewById(R.id.editAcno);
editCno = (EditText) this.findViewById(R.id.editCno);
editHolders = (EditText) this.findViewById(R.id.editHolders);
editBankName = (EditText) this.findViewById(R.id.editBankName);
editBranchName = (EditText) this.findViewById(R.id.editBranchName);
editAddress = (EditText) this.findViewById(R.id.editAddress);
editIFSC = (EditText) this.findViewById(R.id.editIFSC);
editMICR = (EditText) this.findViewById(R.id.editMICR);
editBalance = (EditText) this.findViewById(R.id.editBalance);
editRemarks = (EditText) this.findViewById(R.id.editRemarks);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return Utils.inflateMenu(this,menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return Utils.handleMenuOption(this,item);
}
@Override
public void onStart() {
super.onStart();
accountId = this.getIntent().getStringExtra("accountid");
Log.d("Accounts", "Account Id : " + accountId);
DBHelper dbhelper = new DBHelper(this);
SQLiteDatabase db = dbhelper.getReadableDatabase();
Cursor account = db.query(Database.ACCOUNTS_TABLE_NAME, null,
" _id = ?", new String[] { accountId }, null, null, null);
//startManagingCursor(accounts);
if (account.moveToFirst()) {
// update view
editAcno.setText(account.getString(account
.getColumnIndex(Database.ACCOUNTS_ACNO)));
editCno.setText(account.getString(account
.getColumnIndex(Database.ACCOUNTS_CNO)));
editHolders.setText(account.getString(account
443
.getColumnIndex(Database.ACCOUNTS_HOLDERS)));
editBankName.setText(account.getString(account
.getColumnIndex(Database.ACCOUNTS_BANK)));
editBranchName.setText(account.getString(account
.getColumnIndex(Database.ACCOUNTS_BRANCH)));
editAddress.setText(account.getString(account
.getColumnIndex(Database.ACCOUNTS_ADDRESS)));
editIFSC.setText(account.getString(account
.getColumnIndex(Database.ACCOUNTS_IFSC)));
editMICR.setText(account.getString(account
.getColumnIndex(Database.ACCOUNTS_MICR)));
editBalance.setText(account.getString(account
.getColumnIndex(Database.ACCOUNTS_BALANCE)));
editRemarks.setText(account.getString(account
.getColumnIndex(Database.ACCOUNTS_REMARKS)));
}
account.close();
db.close();
dbhelper.close();
444
long rows = db.update(Database.ACCOUNTS_TABLE_NAME, values,
"_id = ?", new String[] { accountId });
db.close();
if (rows > 0)
Toast.makeText(this, "Updated Account Successfully!",
Toast.LENGTH_LONG).show();
else
Toast.makeText(this, "Sorry! Could not update account!",
Toast.LENGTH_LONG).show();
} catch (Exception ex) {
Toast.makeText(this, ex.getMessage(), Toast.LENGTH_LONG).show();
}
}
445
Toast.makeText(this, "Account Deleted Successfully!",
Toast.LENGTH_LONG).show();
this.finish();
}
else
Toast.makeText(this, "Could not delet account!",
Toast.LENGTH_LONG).show();
Utils.java
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
446
activity.startActivity(intent);
break;
case R.id.optAddTransaction :
intent = new Intent(activity,AddTransaction.class);
activity.startActivity(intent);
break;
case R.id.optSearchTransactions :
intent = new Intent(activity,SearchTransactions.class);
activity.startActivity(intent);
break;
case R.id.optListAccounts :
intent = new Intent(activity,ListAccounts.class);
activity.startActivity(intent);
break;
case R.id.optRecentTransactions :
intent = new Intent(activity,ListRecentTransactions.class);
activity.startActivity(intent);
break;
}
return true;
}
listaccounts.xml
<LinearLayout android:orientation="horizontal"
android:layout_height="wrap_content" android:layout_width="match_parent"
447
android:gravity="center">
<Button android:layout_height="wrap_content"
android:layout_width="wrap_content" android:id="@+id/btnAddAccount" android:text="Add
Account" android:onClick="addAccount"/>
<Button android:layout_height="wrap_content"
android:layout_width="wrap_content" android:id="@+id/btnAddTransaction"
android:text="Add Trans" android:onClick="addTransaction"/>
<Button android:layout_height="wrap_content"
android:layout_width="wrap_content" android:id="@+id/btnRecentTransactions"
android:text="Recent Trans" android:onClick="recentTransactions"/>
</LinearLayout>
</LinearLayout>
account.xml
-<LinearLayout android:orientation="horizontal"
android:layout_height="wrap_content" android:layout_width="match_parent">
448
-<LinearLayout android:orientation="horizontal"
android:layout_height="wrap_content" android:layout_width="match_parent"
android:gravity="right" android:layout_weight="1">
</LinearLayout>
</LinearLayout>
</LinearLayout>
account_transaction.xml
-<TableLayout android:layout_height="wrap_content"
android:layout_width="match_parent" android:stretchColumns="2">
-<TableRow>
449
android:text="Type" android:id="@+id/textTransType" android:gravity="center"/>
</TableRow>
</TableLayout>
</LinearLayout>
add_transaction.xml
<TableLayout android:layout_height="match_parent"
android:layout_width="match_parent">
<TableRow>
</TableRow>
<TableRow>
450
<RadioGroup android:layout_height="wrap_content"
android:layout_width="wrap_content" android:orientation="horizontal">
<RadioButton android:layout_height="wrap_content"
android:layout_width="wrap_content" android:text="Deposit"
android:id="@+id/radioDeposit" android:checked="true"/>
<RadioButton android:layout_height="wrap_content"
android:layout_width="wrap_content" android:text="Withdraw"
android:id="@+id/radioWithdraw"/>
</RadioGroup>
</TableRow>
<TableRow>
<LinearLayout android:layout_height="wrap_content"
android:layout_width="wrap_content" android:layout_marginBottom="5dp"
android:padding="5dp">
</LinearLayout>
</TableRow>
<TableRow>
451
android:id="@+id/editTransAmount" android:inputType="numberDecimal"> </EditText>
</TableRow>
<TableRow>
</TableRow>
<TableRow>
</TableRow>
<TableRow>
</TableRow>
<TableRow>
452
android:id="@+id/editRemarks" android:inputType="text" android:layout_weight="1">
</EditText>
</TableRow>
<TableRow>
</TableRow>
</TableLayout>
</ScrollView>
addaccount.xml
<TableLayout android:layout_height="match_parent"
android:layout_width="match_parent">
<TableRow>
<requestFocus/>
</EditText>
453
</TableRow>
<TableRow>
</TableRow>
<TableRow>
</TableRow>
<TableRow>
</TableRow>
<TableRow>
454
</TableRow>
<TableRow>
</TableRow>
<TableRow>
</TableRow>
<TableRow>
</TableRow>
<TableRow>
455
</TableRow>
<TableRow>
</TableRow>
<TableRow>
</TableRow>
</TableLayout>
</ScrollView>
list_account_transactions.xml
<TableLayout android:layout_height="wrap_content"
android:layout_width="match_parent" android:id="@+id/heading"
android:stretchColumns="1">
456
<TableRow>
</TableRow>
</TableLayout>
</LinearLayout>
list_transactions.xml
457
<TextView android:layout_height="wrap_content" android:layout_width="match_parent"
android:id="@+id/textError" android:text="Sorry! No Transactions Found!"
android:visibility="invisible"/>
</LinearLayout>
Search_transactions.xml
<TableLayout android:layout_height="wrap_content"
android:layout_width="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<TableRow>
<requestFocus/>
</EditText>
<ImageButton android:id="@+id/buttonFromDateDialog"
android:src="@mipmap/ic_launcher" android:onClick="showFromDateDialog"
android:layout_marginLeft="5dp"/>
</TableRow>
<TableRow>
458
android:text="To Date :"/>
<ImageButton android:id="@+id/buttonToDateDialog"
android:src="@mipmap/ic_launcher" android:onClick="showToDateDialog"
android:layout_marginLeft="5dp"/>
</TableRow>
<TableRow>
</TableRow>
<TableRow>
</TableRow>
</TableLayout>
<LinearLayout android:orientation="horizontal"
android:layout_height="wrap_content" android:layout_width="match_parent">
459
android:text="Clear" android:id="@+id/btnClear" android:onClick="clearFields"/>
</LinearLayout>
</LinearLayout>
Transaction.xml
<TableLayout android:layout_height="wrap_content"
android:layout_width="match_parent" android:stretchColumns="1">
<TableRow>
</TableRow>
<TableRow>
</TableRow>
460
<TableRow>
</TableRow>
<TableRow>
</TableRow>
<TableRow>
</TableRow>
<TableRow>
461
android:text="remarks" android:id="@+id/textTransRemarks"
android:layout_marginLeft="5dp"/>
</TableRow>
</TableLayout>
</LinearLayout>
Transaction_details.xml
-<TableLayout android:layout_height="wrap_content"
android:layout_width="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android" android:stretchColumns="*">
-<TableRow>
</TableRow>
</TableLayout>
<TableLayout android:layout_height="wrap_content"
android:layout_width="match_parent" android:stretchColumns="1">
<TableRow>
462
<TextView android:layout_height="wrap_content" android:layout_width="wrap_content"
android:text="Account Number :" android:gravity="right"/>
</TableRow>
<TableRow>
</TableRow>
<TableRow>
</TableRow>
<TableRow>
</TableRow>
<TableRow>
463
<TextView android:layout_height="wrap_content" android:layout_width="wrap_content"
android:text="Cheque No :" android:gravity="right"/>
</TableRow>
<TableRow>
</TableRow>
<TableRow>
</TableRow>
<TableRow>
</TableRow>
</TableLayout>
464
</LinearLayout>
Update_account.xml
<LinearLayout android:layout_height="match_parent"
android:layout_width="match_parent" android:orientation="vertical">
-<LinearLayout android:layout_height="wrap_content"
android:layout_width="match_parent" android:orientation="horizontal"
android:gravity="center">
<Button android:layout_height="wrap_content"
android:layout_width="wrap_content" android:onClick="updateAccount"
android:text="Update" android:id="@+id/buttonUpdate"> </Button>
<Button android:layout_height="wrap_content"
android:layout_width="wrap_content" android:onClick="deleteAccount"
android:text="Delete" android:id="@+id/buttonDelete"> </Button>
<Button android:layout_height="wrap_content"
android:layout_width="wrap_content" android:onClick="listAccountTransactions"
android:text="Transactions" android:id="@+id/buttonListTrans"> </Button>
</LinearLayout>
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content" android:text="Account Number"/>
-<EditText android:layout_height="wrap_content"
android:layout_width="match_parent" android:id="@+id/editAcno">
<requestFocus/>
</EditText>
465
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content" android:text="Customer Number"/>
<EditText android:layout_height="wrap_content"
android:layout_width="match_parent" android:id="@+id/editCno"> </EditText>
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content" android:text="Account Holder(s)"/>
<EditText android:layout_height="wrap_content"
android:layout_width="match_parent" android:id="@+id/editHolders"> </EditText>
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content" android:text="Bank Name "/>
<EditText android:layout_height="wrap_content"
android:layout_width="match_parent" android:id="@+id/editBankName"> </EditText>
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content" android:text="Branch Name "/>
<EditText android:layout_height="wrap_content"
android:layout_width="match_parent" android:id="@+id/editBranchName"> </EditText>
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content" android:text="Branch Address "/>
<EditText android:layout_height="wrap_content"
android:layout_width="match_parent" android:id="@+id/editAddress"
android:inputType="textPostalAddress"/>
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content" android:text="IFSC"/>
<EditText android:layout_height="wrap_content"
android:layout_width="match_parent" android:id="@+id/editIFSC"> </EditText>
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content" android:text="MICR"/>
<EditText android:layout_height="wrap_content"
android:layout_width="match_parent" android:id="@+id/editMICR"> </EditText>
466
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content" android:text="Current Balance"/>
<EditText android:layout_height="wrap_content"
android:layout_width="match_parent" android:id="@+id/editBalance"> </EditText>
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content" android:text="Remarks "/>
<EditText android:layout_height="wrap_content"
android:layout_width="match_parent" android:id="@+id/editRemarks"> </EditText>
</LinearLayout>
</ScrollView>
Menu
Common_menu.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android">
</menu>
String.xml
467
<resources>
<string name="app_name">My Application</string>
<string name="action_settings">Settings</string>
<string name="accountsprompt">Select Account</string>
</resources>
Manifest.xml
<manifest package="com.example.manju.myapplication"
xmlns:android="http://schemas.android.com/apk/res/android">
-<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
468
</manifest>
Quiz application
SoccerQuizGame.java
import android.support.v7.app.AppCompatActivity;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.AssetManager;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
469
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.AssetManager;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
//Instance Variables
private List<String> fileNameList; // player file names
private List<String> quizPlayersList; // names of players in quiz
private String correctAnswer; // current correct answer
private int totalGuesses; // number of guesses
private int correctAnswers; // number of correct guesses
private int guessRows; // number of rows displaying choices
private Random random; // random number generator
private Handler handler; // used to delay loading of next player
private Animation shakeAnimation; // animation for incorrect answers
470
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
471
// get list of all player names in this region
String[] paths = null;
try {
paths = assets.list("Players");
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e(TAG, "Error loading ", e);
}
472
//get the filename of the next flag and remove it from the list
String nextImageName = quizPlayersList.remove(0);
correctAnswer = nextImageName; //update correct answer
try{
473
LayoutInflater inflater = (LayoutInflater)
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// parses the player file name and returns the player name
474
private String getPlayerName(String name){
if (guess.equals(answer)){
answerTextView.setTextColor(getResources().getColor(R.color.correct_answer));
builder.setCancelable(false);
475
@Override
public void onClick(DialogInterface dialog, int which)
{
resetQuiz();
} // end onClick
} // end anonymous inner class
); //end call to setPositiveButton
} // end if
} // end else
} // end if
answerTextView.setTextColor(getResources().getColor(R.color.incorrect_answer));
476
} // end submitGuess method
super.onCreateOptionsMenu(menu);
477
//create an AlertDialog Builder and set its title
AlertDialog.Builder choicesBuilder = new
AlertDialog.Builder(this);
choicesBuilder.setTitle(R.string.choices);
@Override
public void onClick(DialogInterface dialog, int item)
{
resetQuiz();
}
});
break;
} // end switch
return super.onOptionsItemSelected(item);
@Override
public void onClick(View v){
submitGuess((Button) v); // pass selected Button to submitGuess method
}
478
};
} // end SoccerQuizGame
main.xml
<ImageView android:layout_height="@dimen/face_height"
android:layout_width="@dimen/face_width" android:id="@+id/faceImageView"
android:adjustViewBounds="false"/>
479
<TableRow android:layout_height="wrap_content" android:layout_width="match_parent"
android:id="@+id/tableRow2"> </TableRow>
</TableLayout>
</LinearLayout>
guess_button.xml
color.xml
<color name="background_color">#FFFFCC</color>
<color name="correct_answer">#FFFFFF</color>
<color name="incorrect_answer">#FF0000</color>
<color name="text_color">#FFFFFF</color>
string.xml
<string name="menu_settings">Settings</string>
<string name="correct">correct</string>
480
<string name="guesses">guesses</string>
<string name="incorrect_answer">Wrong!</string>
<string name="of">of</string>
<string name="ok">OK</string>
<string name="question">Question</string>
<string-array name="guessesList">
<item>3</item>
<item>6</item>
<item>9</item>
</string-array>
dimen.xml
<resources>
<!-- Default screen margins, per the Android Design guidelines. -->
<dimen name="activity_horizontal_margin">16dp</dimen>
<dimen name="activity_vertical_margin">16dp</dimen>
<dimen name="fab_margin">16dp</dimen>
<dimen name="title_size">25sp</dimen>
<dimen name="face_width">227dp</dimen>
<dimen name="face_height">150dp</dimen>
<dimen name="answer_size">40sp</dimen>
<dimen name="text_size">20sp</dimen>
<dimen name="padding_small">8dp</dimen>
481
<dimen name="padding_medium">8dp</dimen>
<dimen name="padding_large">16dp</dimen>
</resources>
Drawable folder
anim folder
incorrect_shake.xml
assets folder
PLAYERS PHOTO
MainActivity.java
482
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.support.v7.app.ActionBar;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
483
private static final int REQUEST_CONNECT_DEVICE_SECURE = 1;
private static final int REQUEST_CONNECT_DEVICE_INSECURE = 2;
private static final int REQUEST_ENABLE_BT = 3;
@Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case ChatService.STATE_CONNECTED:
setStatus(getString(R.string.title_connected_to,
connectedDeviceName));
chatArrayAdapter.clear();
break;
case ChatService.STATE_CONNECTING:
setStatus(R.string.title_connecting);
break;
case ChatService.STATE_LISTEN:
case ChatService.STATE_NONE:
setStatus(R.string.title_not_connected);
break;
}
break;
case MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
484
String readMessage = new String(readBuf, 0, msg.arg1);
chatArrayAdapter.add(connectedDeviceName + ": " +
readMessage);
break;
case MESSAGE_DEVICE_NAME:
connectedDeviceName = msg.getData().getString(DEVICE_NAME);
Toast.makeText(getApplicationContext(),
"Connected to " + connectedDeviceName,
Toast.LENGTH_SHORT).show();
break;
case MESSAGE_TOAST:
Toast.makeText(getApplicationContext(),
msg.getData().getString(TOAST), Toast.LENGTH_SHORT)
.show();
break;
}
return false;
}
});
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
getWidgetReferences();
bindEventHandler();
if (bluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available",
Toast.LENGTH_LONG).show();
finish();
return;
}
}
485
}
btnSend.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String message = etMain.getText().toString();
sendMessage(message);
}
});
}
@Override
486
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.option_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent serverIntent = null;
switch (item.getItemId()) {
case R.id.secure_connect_scan:
serverIntent = new Intent(this, DeviceListActivity.class);
startActivityForResult(serverIntent,
REQUEST_CONNECT_DEVICE_SECURE);
return true;
case R.id.insecure_connect_scan:
serverIntent = new Intent(this, DeviceListActivity.class);
startActivityForResult(serverIntent,
REQUEST_CONNECT_DEVICE_INSECURE);
return true;
case R.id.discoverable:
ensureDiscoverable();
return true;
}
return false;
}
487
if (message.length() > 0) {
byte[] send = message.getBytes();
chatService.write(send);
outStringBuffer.setLength(0);
etMain.setText(outStringBuffer);
}
}
@Override
public void onStart() {
488
super.onStart();
if (!bluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
} else {
if (chatService == null)
setupChat();
}
}
@Override
public synchronized void onResume() {
super.onResume();
if (chatService != null) {
if (chatService.getState() == ChatService.STATE_NONE) {
chatService.start();
}
}
}
@Override
public synchronized void onPause() {
super.onPause();
}
@Override
public void onStop() {
super.onStop();
}
@Override
public void onDestroy() {
super.onDestroy();
if (chatService != null)
chatService.stop();
}
DeviceListActivity
489
import java.util.Set;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.device_list);
setResult(Activity.RESULT_CANCELED);
getWidgetReferences();
bindEventHandler();
initializeValues();
490
}
lvDeviceListPairedDevice = (ListView)
findViewById(R.id.lvDeviceListPairedDevice);
lvDeviceListNewDevice = (ListView) findViewById(R.id.lvDeviceListNewDevice);
btnDeviceListScan.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startDiscovery();
btnDeviceListScan.setVisibility(View.GONE);
}
});
}
lvDeviceListPairedDevice.setAdapter(pairedDevicesArrayAdapter);
lvDeviceListNewDevice.setAdapter(newDevicesArrayAdapter);
491
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = bluetoothAdapter
.getBondedDevices();
tvDeviceListNewDeviceTitle.setVisibility(View.VISIBLE);
if (bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
}
bluetoothAdapter.startDiscovery();
}
setResult(Activity.RESULT_OK, intent);
finish();
492
}
};
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
newDevicesArrayAdapter.add(device.getName() + "\n"
+ device.getAddress());
}
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED
.equals(action)) {
setProgressBarIndeterminateVisibility(false);
setTitle(R.string.select_device);
if (newDevicesArrayAdapter.getCount() == 0) {
String noDevices = getResources().getText(
R.string.none_found).toString();
newDevicesArrayAdapter.add(noDevices);
}
}
}
};
@Override
protected void onDestroy() {
super.onDestroy();
if (bluetoothAdapter != null) {
bluetoothAdapter.cancelDiscovery();
}
this.unregisterReceiver(discoveryFinishReceiver);
}
ChatService
493
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
// Member fields
private final BluetoothAdapter bluetoothAdapter;
private final Handler handler;
private AcceptThread secureAcceptThread;
private AcceptThread insecureAcceptThread;
private ConnectThread connectThread;
private ConnectedThread connectedThread;
private int state;
494
this.handler = handler;
}
// start service
public synchronized void start() {
// Cancel any thread
if (connectThread != null) {
connectThread.cancel();
connectThread = null;
}
setState(STATE_LISTEN);
495
public synchronized void connect(BluetoothDevice device, boolean secure) {
// Cancel any thread
if (state == STATE_CONNECTING) {
if (connectThread != null) {
connectThread.cancel();
connectThread = null;
}
}
if (secureAcceptThread != null) {
secureAcceptThread.cancel();
secureAcceptThread = null;
}
if (insecureAcceptThread != null) {
insecureAcceptThread.cancel();
insecureAcceptThread = null;
496
}
setState(STATE_CONNECTED);
}
if (connectedThread != null) {
connectedThread.cancel();
connectedThread = null;
}
if (secureAcceptThread != null) {
secureAcceptThread.cancel();
secureAcceptThread = null;
}
if (insecureAcceptThread != null) {
insecureAcceptThread.cancel();
insecureAcceptThread = null;
}
setState(STATE_NONE);
}
497
return;
r = connectedThread;
}
r.write(out);
}
try {
if (secure) {
tmp = bluetoothAdapter.listenUsingRfcommWithServiceRecord(
NAME_SECURE, MY_UUID_SECURE);
} else {
tmp = bluetoothAdapter
.listenUsingInsecureRfcommWithServiceRecord(
498
NAME_INSECURE, MY_UUID_INSECURE);
}
} catch (IOException e) {
}
serverSocket = tmp;
}
499
public void cancel() {
try {
serverSocket.close();
} catch (IOException e) {
}
}
}
try {
if (secure) {
tmp = device
.createRfcommSocketToServiceRecord(MY_UUID_SECURE);
} else {
tmp = device
.createInsecureRfcommSocketToServiceRecord(MY_UUID_INSECURE);
}
} catch (IOException e) {
}
socket = tmp;
}
500
socket.close();
} catch (IOException e2) {
}
connectionFailed();
return;
}
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
}
inputStream = tmpIn;
outputStream = tmpOut;
}
501
public void run() {
byte[] buffer = new byte[1024];
int bytes;
// write to OutputStream
public void write(byte[] buffer) {
try {
outputStream.write(buffer);
handler.obtainMessage(MainActivity.MESSAGE_WRITE, -1, -1,
buffer).sendToTarget();
} catch (IOException e) {
}
}
activity_main.xml
502
<?xml version="1.0" encoding="UTF-8"?>
-<LinearLayout android:orientation="horizontal"
android:layout_height="wrap_content" android:layout_width="match_parent">
</LinearLayout>
</LinearLayout>
device_list.xml
503
android:visibility="gone" android:textColor="#fff"
android:text="@string/title_other_devices" android:paddingLeft="5dp"
android:background="#666" android:id="@+id/tvDeviceListNewDeviceTitle"/>
</LinearLayout>
device_name.xml
message.xml
MENU
option_menu.xml
<menu xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:title="@string/secure_connect"
android:showAsAction="ifRoom|withText" android:icon="@android:drawable/ic_menu_search"
android:id="@+id/secure_connect_scan"
tools:ignore="AppCompatResource" />
<item android:title="@string/insecure_connect"
504
android:showAsAction="ifRoom|withText" android:icon="@android:drawable/ic_menu_search"
android:id="@+id/insecure_connect_scan"
tools:ignore="AppCompatResource" />
</menu>
string.xml
<resources xmlns:xliff="http://schemas.android.com/tools">
<string name="app_name">My Application</string>
<string name="action_settings">Settings</string>
<string name="send">Send</string>
<string name="title_connecting">Connecting...</string>
<string name="title_connected_to">
Connected to
<xliff:g id="device_name">%1$s</xliff:g>
</string>
505
<string name="title_other_devices">Other Available Devices</string>
</resources>
Manifest.xml
<?xml version="1.0"?>
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
506
</activity>
<activity android:name=".DeviceListActivity"
android:theme="@android:style/Theme.Dialog" android:label="@string/select_device"
android:screenOrientation="portrait"/>
</application>
</manifest>
Contacts View
ContactsView.java
import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.TextView;
while (cursor.moveToNext()) {
507
cursor.close();
}
main.xml
Android manifest.xml
<uses-permission android:name="android.permission.READ_CONTACTS"/>
MainActivity.java:
508
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.view.View;
import android.widget.Toast;
};
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
509
intent.putExtra("MESSENGER", messenger);
intent.setData(Uri.parse("http://www.vogella.de/index.html"));
intent.putExtra("urlpath", "http://www.vogella.de/index.html");
startService(intent);
}
DownloadService.java
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import android.app.Activity;
import android.app.IntentService;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.os.Messenger;
import android.util.Log;
public DownloadService() {
super("DownloadService");
}
try {
510
Thread.sleep(4000);
} catch (InterruptedException e2) {
e2.printStackTrace();
}
Uri data = intent.getData();
String urlPath = intent.getStringExtra("urlpath");
String fileName = data.getLastPathSegment();
File output = new File(Environment.getExternalStorageDirectory(),
fileName);
if (output.exists()) {
output.delete();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
511
}
}
}
}
}
WrongDownloadService.java
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import android.app.Activity;
import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.StrictMode;
import android.util.Log;
512
private int result = Activity.RESULT_CANCELED;
public WrongDownloadService() {
super();
}
513
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return Service.START_NOT_STICKY;
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
514
activity_main.xml
</LinearLayout>
Android manifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
SHARE WORDS
MainActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.content.Intent;
import android.view.View;
515
import android.widget.EditText;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
ShareReceiver.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
516
Toast.makeText(this, string, Toast.LENGTH_LONG).show();
}
}
activity_main.xml
<requestFocus/>
</EditText>
</LinearLayout>
receiver.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
517
Battery charge information
MainActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.os.BatteryManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.widget.TextView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerBatteryLevelReceiver();
}
@Override
protected void onDestroy() {
unregisterReceiver(battery_receiver);
super.onDestroy();
}
518
int health = intent.getIntExtra("health", 0);
int status = intent.getIntExtra("status", 0);
int rawlevel = intent.getIntExtra("level", -1);
int voltage = intent.getIntExtra("voltage", 0);
int temperature = intent.getIntExtra("temperature", 0);
int level = 0;
Log.i("BatteryLevel", bundle.toString());
if (isPresent) {
if (rawlevel >= 0 && scale > 0) {
level = (rawlevel * 100) / scale;
}
switch (plugged) {
case BatteryManager.BATTERY_PLUGGED_AC:
plugType = "AC";
break;
case BatteryManager.BATTERY_PLUGGED_USB:
plugType = "USB";
break;
}
return plugType;
519
}
switch (health) {
case BatteryManager.BATTERY_HEALTH_DEAD:
healthString = "Dead";
break;
case BatteryManager.BATTERY_HEALTH_GOOD:
healthString = "Good";
break;
case BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE:
healthString = "Over Voltage";
break;
case BatteryManager.BATTERY_HEALTH_OVERHEAT:
healthString = "Over Heat";
break;
case BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE:
healthString = "Failure";
break;
}
return healthString;
}
switch (status) {
case BatteryManager.BATTERY_STATUS_CHARGING:
statusString = "Charging";
break;
case BatteryManager.BATTERY_STATUS_DISCHARGING:
statusString = "Discharging";
break;
case BatteryManager.BATTERY_STATUS_FULL:
statusString = "Full";
break;
case BatteryManager.BATTERY_STATUS_NOT_CHARGING:
statusString = "Not Charging";
break;
}
520
return statusString;
}
registerReceiver(battery_receiver, filter);
}
}
activity_main.xml:
<?xml version="1.0"?>
</LinearLayout>
MainActivity.java
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
521
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
// GUI Widget
Button btnSent, btnInbox, btnDraft;
TextView lblMsg, lblNo;
ListView lvMsg;
// Cursor Adapter
SimpleCursorAdapter adapter;
@Override
public void onClick(View v) {
if (v == btnInbox) {
522
String[] reqCols = new String[] { "_id", "address", "body" };
if (v == btnSent) {
if (v == btnDraft) {
// Create Draft box URI
Uri draftURI = Uri.parse("content://sms/draft");
523
// List required columns
String[] reqCols = new String[] { "_id", "address", "body" };
}
}
messagebox.xml
524
android:id="@+id/lvMsg"></ListView>
</LinearLayout>
row.xml
</LinearLayout>
Android manifest.xml
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.READ_SMS"/>
Date Picker
MainActivity.java
import android.os.Bundle;
import android.widget.TextView;
import android.support.v7.app.AppCompatActivity;
import java.util.Calendar;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.view.View;
import android.view.View.OnClickListener;
525
import android.widget.Button;
import android.widget.DatePicker;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Output.setText(new StringBuilder()
// Month is 0 based, just add 1
.append(month + 1).append("-").append(day).append("-")
.append(year).append(" "));
changeDate.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
526
showDialog(DATE_PICKER_ID);
});
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_PICKER_ID:
year = selectedYear;
month = selectedMonth;
day = selectedDay;
}
};
527
activity_main.xml
</LinearLayout>
Time Picker
MainActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import java.util.Calendar;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;
import android.app.Dialog;
import android.app.TimePickerDialog;
528
static final int TIME_DIALOG_ID = 1111;
private TextView output;
public Button btnClick;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnClick.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showDialog(TIME_DIALOG_ID);
529
}
});
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case TIME_DIALOG_ID:
}
return null;
}
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minutes) {
// TODO Auto-generated method stub
hour = hourOfDay;
minute = minutes;
updateTime(hour,minute);
};
530
private void updateTime(int hours, int mins) {
// Append in a StringBuilder
String aTime = new StringBuilder().append(hours).append(':')
.append(minutes).append(" ").append(timeSet).toString();
output.setText(aTime);
}
}
activity_main.xml
531
android:text="Current Time (H:M): " android:id="@+id/lblTime"
android:textAppearance="?android:attr/textAppearanceLarge"/>
</LinearLayout>
MainActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.net.ConnectivityManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
Save.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
isInternetOn();
}
532
});
}
} else if ( connec.getNetworkInfo(0).getState() ==
android.net.NetworkInfo.State.DISCONNECTED || connec.getNetworkInfo(1).getState() ==
android.net.NetworkInfo.State.DISCONNECTED ) {
activity_main.xml
<LinearLayout android:layout_height="fill_parent"
android:layout_width="fill_parent" android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android">
533
<Button android:layout_height="wrap_content" android:layout_width="wrap_content"
android:text="Click to check internet connectivity" android:id="@+id/save"> </Button>
</LinearLayout>
Android manifest.xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Camera
MainActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import java.io.File;
import java.util.List;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
534
Button btnTackPic;
TextView tvHasCamera, tvHasCameraApp;
ImageView ivThumbnailPhoto;
Bitmap bitMap;
static int TAKE_PICTURE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
535
"my-photo.jpg");
Uri photoPath = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoPath); */
// The Android Camera application encodes the photo in the return Intent
delivered to onActivityResult()
// as a small Bitmap in the extras, under the key "data"
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent
intent) {
// get
bitMap = (Bitmap) extras.get("data");
ivThumbnailPhoto.setImageBitmap(bitMap);
}
}
536
}
}
activity_main.xml
<?xml version="1.0"?>
</LinearLayout>
Android manifest.xml
<uses-feature android:name="android.hardware.camera"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
537
List view (Search engine)
MainActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
// List view
private ListView lv;
// Listview Adapter
ArrayAdapter<String> adapter;
// Search EditText
EditText inputSearch;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Listview Data
String products[] = {"Afghanistan",
"Albania",
"Algeria",
"Andorra",
538
"Angola",
"Antigua and Barbuda",
"Argentina",
"Armenia",
"Australia",
"Austria",
"Azerbaijan",
"Bahamas",
"Bahrain",
"Bangladesh",
"Barbados",
"Belarus",
"Belgium",
"Belize",
"Benin",
"Bhutan",
"Bolivia",
"Bosnia and Herzegovina",
"Botswana",
"Brazil",
"Brunei",
"Bulgaria",
"Burkina Faso",
"Burundi",
"Cambodia",
"Cameroon",
"Canada",
"Cape Verde",
"Central African Republic",
"Chad",
"Chile",
"China",
"Colombi",
"Comoros",
"Congo (Brazzaville)",
"Congo",
"Costa Rica",
"Cote d'Ivoire",
"Croatia",
"Cuba",
"Cyprus",
"Czech Republic",
"Denmark",
"Djibouti",
539
"Dominica",
"Dominican Republic",
"East Timor (Timor Timur)",
"Ecuador",
"Egypt",
"El Salvador",
"Equatorial Guinea",
"Eritrea",
"Estonia",
"Ethiopia",
"Fiji",
"Finland",
"France",
"Gabon",
"Gambia, The",
"Georgia",
"Germany",
"Ghana",
"Greece",
"Grenada",
"Guatemala",
"Guinea",
"Guinea-Bissau",
"Guyana",
"Haiti",
"Honduras",
"Hungary",
"Iceland",
"India",
"Indonesia",
"Iran",
"Iraq",
"Ireland",
"Israel",
"Italy",
"Jamaica",
"Japan",
"Jordan",
"Kazakhstan",
"Kenya",
"Kiribati",
"Korea, North",
"Korea, South",
"Kuwait",
540
"Kyrgyzstan",
"Laos",
"Latvia",
"Lebanon",
"Lesotho",
"Liberia",
"Libya",
"Liechtenstein",
"Lithuania",
"Luxembourg",
"Macedonia",
"Madagascar",
"Malawi",
"Malaysia",
"Maldives",
"Mali",
"Malta",
"Marshall Islands",
"Mauritania",
"Mauritius",
"Mexico",
"Micronesia",
"Moldova",
"Monaco",
"Mongolia",
"Morocco",
"Mozambique",
"Myanmar",
"Namibia",
"Nauru",
"Nepal",
"Netherlands",
"New Zealand",
"Nicaragua",
"Niger",
"Nigeria",
"Norway",
"Oman",
"Pakistan",
"Palau",
"Panama",
"Papua New Guinea",
"Paraguay",
"Peru",
541
"Philippines",
"Poland",
"Portugal",
"Qatar",
"Romania",
"Russia",
"Rwanda",
"Saint Kitts and Nevis",
"Saint Lucia",
"Saint Vincent",
"Samoa",
"San Marino",
"Sao Tome and Principe",
"Saudi Arabia",
"Senegal",
"Serbia and Montenegro",
"Seychelles",
"Sierra Leone",
"Singapore",
"Slovakia",
"Slovenia",
"Solomon Islands",
"Somalia",
"South Africa",
"Spain",
"Sri Lanka",
"Sudan",
"Suriname",
"Swaziland",
"Sweden",
"Switzerland",
"Syria",
"Taiwan",
"Tajikistan",
"Tanzania",
"Thailand",
"Togo",
"Tonga",
"Trinidad and Tobago",
"Tunisia",
"Turkey",
"Turkmenistan",
"Tuvalu",
"Uganda",
542
"Ukraine",
"United Arab Emirates",
"United Kingdom",
"United States",
"Uruguay",
"Uzbekistan",
"Vanuatu",
"Vatican City",
"Venezuela",
"Vietnam",
"Yemen",
"Zambia",
"Zimbabwe"};
lv = (ListView) findViewById(R.id.list_view);
inputSearch = (EditText) findViewById(R.id.inputSearch);
/**
* Enabling Search Filter
* */
inputSearch.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int
arg3) {
// When user changed the Text
MainActivity.this.adapter.getFilter().filter(cs);
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
@Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
543
}
});
}
activity_main.xml
</LinearLayout>
list_item.xml
544
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dip"
android:textSize="16dip"
android:textStyle="bold"/>
</LinearLayout>
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import java.lang.reflect.Method;
import android.content.Context;
import android.os.Bundle;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.TextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
@Override
protected void onResume() {
super.onResume();
545
String serialNumber = "unknown";
try {
Class<?> c = Class.forName("android.os.SystemProperties");
Method get = c.getMethod("get", String.class, String.class);
serialNumber = (String) get.invoke(c, "ro.serialno", serialNumber);
} catch (Exception e) {
Log.e(TAG, "Failed to get serial number", e);
}
((TextView) findViewById(R.id.serial_number)).setText(serialNumber);
main.xml
<?xml version="1.0"?>
<TableRow>
546
android:id="@+id/serial_number"/>
</TableRow>
<TableRow>
</TableRow>
<TableRow>
</TableRow>
</TableLayout>
string.xml
Android manifest.xml
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
547
Telephony Manager
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import java.util.List;
import android.os.Bundle;
import android.telephony.CellLocation;
import android.telephony.NeighboringCellInfo;
import android.telephony.PhoneStateListener;
import android.telephony.ServiceState;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;
import android.util.Log;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
548
startSignalLevelListener();
displayTelephonyInfo();
}
@Override
protected void onPause() {
super.onPause();
stopListening();
}
@Override
protected void onResume() {
super.onResume();
startSignalLevelListener();
}
@Override
protected void onDestroy() {
stopListening();
super.onDestroy();
}
549
return signalLevelString;
}
switch (direction) {
case TelephonyManager.DATA_ACTIVITY_IN:
resid = R.drawable.data_in;
break;
case TelephonyManager.DATA_ACTIVITY_OUT:
resid = R.drawable.data_out;
break;
case TelephonyManager.DATA_ACTIVITY_INOUT:
resid = R.drawable.data_both;
break;
case TelephonyManager.DATA_ACTIVITY_NONE:
resid = R.drawable.data_none;
break;
default:
resid = R.drawable.data_none;
break;
}
return resid;
}
550
| PhoneStateListener.LISTEN_CALL_FORWARDING_INDICATOR
| PhoneStateListener.LISTEN_DATA_CONNECTION_STATE
| PhoneStateListener.LISTEN_MESSAGE_WAITING_INDICATOR
| PhoneStateListener.LISTEN_SERVICE_STATE;
tm.listen(phoneStateListener, events);
}
551
deviceinfo += ("Operator Name: " + operatorname + "\n");
deviceinfo += ("SIM Country Code: " + simcountrycode + "\n");
deviceinfo += ("SIM Operator: " + simoperator + "\n");
deviceinfo += ("SIM Serial No.: " + simserialno + "\n");
deviceinfo += ("Subscriber ID: " + subscriberid + "\n");
deviceinfo += ("Network Type: " + networktype + "\n");
deviceinfo += ("Phone Type: " + phonetype + "\n");
List<NeighboringCellInfo> cellinfo = tm.getNeighboringCellInfo();
if (null != cellinfo) {
for (NeighboringCellInfo info : cellinfo) {
deviceinfo += ("\tCellID: " + info.getCid() + ", RSSI: "
+ info.getRssi() + "\n");
}
}
setTextViewText(info_ids[INFO_DEVICE_INFO_INDEX], deviceinfo);
}
552
break;
default:
typeString = "UNKNOWN";
break;
}
return typeString;
}
@Override
public void onCallForwardingIndicatorChanged(boolean cfi) {
Log.i(APP_NAME, "onCallForwardingIndicatorChanged " + cfi);
super.onCallForwardingIndicatorChanged(cfi);
}
@Override
public void onCallStateChanged(int state, String incomingNumber) {
String callState = "UNKNOWN";
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
callState = "IDLE";
break;
case TelephonyManager.CALL_STATE_RINGING:
callState = "Ringing (" + incomingNumber + ")";
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
callState = "Offhook";
break;
}
setTextViewText(info_ids[INFO_CALL_STATE_INDEX], callState);
Log.i(APP_NAME, "onCallStateChanged " + callState);
super.onCallStateChanged(state, incomingNumber);
}
@Override
public void onCellLocationChanged(CellLocation location) {
String locationString = location.toString();
setTextViewText(info_ids[INFO_CELL_LOCATION_INDEX], locationString);
553
Log.i(APP_NAME, "onCellLocationChanged " + locationString);
super.onCellLocationChanged(location);
}
@Override
public void onDataActivity(int direction) {
String directionString = "none";
switch (direction) {
case TelephonyManager.DATA_ACTIVITY_IN:
directionString = "IN";
break;
case TelephonyManager.DATA_ACTIVITY_OUT:
directionString = "OUT";
break;
case TelephonyManager.DATA_ACTIVITY_INOUT:
directionString = "INOUT";
break;
case TelephonyManager.DATA_ACTIVITY_NONE:
directionString = "NONE";
break;
default:
directionString = "UNKNOWN: " + direction;
break;
}
setDataDirection(info_ids[INFO_DATA_DIRECTION_INDEX], direction);
Log.i(APP_NAME, "onDataActivity " + directionString);
super.onDataActivity(direction);
}
@Override
public void onDataConnectionStateChanged(int state) {
String connectionState = "Unknown";
switch (state) {
case TelephonyManager.DATA_CONNECTED:
connectionState = "Connected";
break;
case TelephonyManager.DATA_CONNECTING:
connectionState = "Connecting";
break;
case TelephonyManager.DATA_DISCONNECTED:
connectionState = "Disconnected";
break;
554
case TelephonyManager.DATA_SUSPENDED:
connectionState = "Suspended";
break;
default:
setTextViewText(info_ids[INFO_CONNECTION_STATE_INDEX],
connectionState);
super.onDataConnectionStateChanged(state);
}
@Override
public void onMessageWaitingIndicatorChanged(boolean mwi) {
Log.i(APP_NAME, "onMessageWaitingIndicatorChanged " + mwi);
super.onMessageWaitingIndicatorChanged(mwi);
}
@Override
public void onServiceStateChanged(ServiceState serviceState) {
String serviceStateString = "UNKNOWN";
switch (serviceState.getState()) {
case ServiceState.STATE_IN_SERVICE:
serviceStateString = "IN SERVICE";
break;
case ServiceState.STATE_EMERGENCY_ONLY:
serviceStateString = "EMERGENCY ONLY";
break;
case ServiceState.STATE_OUT_OF_SERVICE:
serviceStateString = "OUT OF SERVICE";
break;
case ServiceState.STATE_POWER_OFF:
serviceStateString = "POWER OFF";
break;
default:
serviceStateString = "UNKNOWN";
break;
}
555
setTextViewText(info_ids[INFO_SERVICE_STATE_INDEX],
serviceStateString);
super.onServiceStateChanged(serviceState);
}
@Override
public void onSignalStrengthChanged(int asu) {
Log.i(APP_NAME, "onSignalStrengthChanged " + asu);
setSignalLevel(info_ids[INFO_SIGNAL_LEVEL_INDEX],
info_ids[INFO_SIGNAL_LEVEL_INFO_INDEX], asu);
super.onSignalStrengthChanged(asu);
}
};
}
activity_main.xml
<ScrollView android:scrollbarAlwaysDrawVerticalTrack="false"
android:scrollbarStyle="insideOverlay" android:orientation="vertical"
android:layout_height="wrap_content" android:layout_width="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
-<LinearLayout android:orientation="horizontal"
android:layout_height="wrap_content" android:layout_width="fill_parent">
556
</LinearLayout>
-<LinearLayout android:orientation="horizontal"
android:layout_height="wrap_content" android:layout_width="fill_parent">
</LinearLayout>
<LinearLayout android:orientation="horizontal"
android:layout_height="wrap_content" android:layout_width="fill_parent">
</LinearLayout>
<LinearLayout android:orientation="horizontal"
android:layout_height="wrap_content" android:layout_width="fill_parent">
</LinearLayout>
557
<LinearLayout android:orientation="horizontal"
android:layout_height="wrap_content" android:layout_width="fill_parent">
<LinearLayout android:orientation="horizontal"
android:layout_height="wrap_content" android:layout_width="fill_parent"
android:layout_weight="0.5">
</LinearLayout>
</LinearLayout>
<LinearLayout android:orientation="horizontal"
android:layout_height="wrap_content" android:layout_width="fill_parent">
</LinearLayout>
558
</LinearLayout>
</ScrollView>
Android manifest.xml
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
Video Capture
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.VideoView;
Button captureVideoButton;
Button playVideoButton;
VideoView videoView;
Uri videoFileUri;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
559
playVideoButton.setOnClickListener(this);
playVideoButton.setEnabled(false);
videoView = (VideoView) this.findViewById(R.id.VideoView);
}
activity_main.xml
Android manifest.xml
560
<uses-permission android:name="android.permission.RECORD_AUDIO"></uses-permission>
<uses-permission android:name="android.permission.CAMERA"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-
permission>
MainActivity.java
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.support.v7.app.AppCompatActivity;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
561
if(resultCode == Activity.RESULT_OK) {
Uri selectedContent = data.getData();
if(requestCode == REQUEST_IMAGE) {
//Display the image
}
if(requestCode == REQUEST_VIDEO) {
//Play the video clip
}
if(requestCode == REQUEST_AUDIO) {
//Play the audio clip
}
}
}
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
switch(v.getId()) {
case R.id.imageButton:
intent.setType("image/*");
startActivityForResult(intent, REQUEST_IMAGE);
return;
case R.id.videoButton:
intent.setType("video/*");
startActivityForResult(intent, REQUEST_VIDEO);
return;
case R.id.audioButton:
intent.setType("audio/*");
startActivityForResult(intent, REQUEST_AUDIO);
return;
default:
return;
}
}
}
activity_main.xml
562
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:id="@+id/imageButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Images"
/>
<Button
android:id="@+id/videoButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Video"
/>
<Button
android:id="@+id/audioButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Audio"
/>
</LinearLayout>
MainActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.widget.TextView;
563
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/** Setting the density, width and height of the screen to the TextView
object */
tvMetrics.setText("Density : "+density + "\n" + "Resolution in pixels : "
+ resolution + "\nResolution in dp : " + resolution_dp );
}
}
activity_main.xml
564
android:layout_width="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
</LinearLayout>
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
565
};
activity_main.xml
</LinearLayout>
string.xml
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
566
public class MainActivity extends AppCompatActivity {
@Override
public void onClick(View v) {
/** Getting a reference to the textedit object of the main.xml */
EditText txt = (EditText) findViewById(R.id.te_url);
/** Start an activity that matches intent action and intent data
*/
startActivity(intent);
}
};
btn.setOnClickListener(listener);
}
}
activity_main.xml
567
<?xml version="1.0" encoding="UTF-8"?>
</LinearLayout>
string.xml
<string name="lbl_btn_browse">Browse</string>
Android manifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
Calculator
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
568
EditText edt1 ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
edt1.setText(edt1.getText()+"1");
}
});
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
edt1.setText(edt1.getText()+"2");
}
569
});
button3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
edt1.setText(edt1.getText()+"3");
}
});
button4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
edt1.setText(edt1.getText()+"4");
}
});
button5.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
edt1.setText(edt1.getText()+"5");
}
});
button6.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
edt1.setText(edt1.getText()+"6");
}
});
button7.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
edt1.setText(edt1.getText()+"7");
}
});
button8.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
edt1.setText(edt1.getText()+"8");
}
});
570
button9.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
edt1.setText(edt1.getText()+"9");
}
});
button0.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
edt1.setText(edt1.getText()+"0");
}
});
buttonAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (edt1 == null){
edt1.setText("");
}else {
mValueOne = Float.parseFloat(edt1.getText() + "");
mAddition = true;
edt1.setText(null);
}
}
});
buttonSub.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mValueOne = Float.parseFloat(edt1.getText() + "");
mSubtract = true ;
edt1.setText(null);
}
});
buttonMul.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mValueOne = Float.parseFloat(edt1.getText() + "");
mMultiplication = true ;
edt1.setText(null);
}
571
});
buttonDivision.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mValueOne = Float.parseFloat(edt1.getText()+"");
mDivision = true ;
edt1.setText(null);
}
});
buttonEqual.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mValueTwo = Float.parseFloat(edt1.getText() + "");
if (mAddition == true){
if (mSubtract == true){
edt1.setText(mValueOne - mValueTwo+"");
mSubtract=false;
}
if (mMultiplication == true){
edt1.setText(mValueOne * mValueTwo+"");
mMultiplication=false;
}
if (mDivision == true){
edt1.setText(mValueOne / mValueTwo+"");
mDivision=false;
}
}
});
buttonC.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
edt1.setText("");
572
}
});
button10.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
edt1.setText(edt1.getText()+".");
}
});
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:id="@+id/relative1">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/edt1"/>
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1"
android:id="@+id/button1"
android:layout_marginTop="94dp"
android:layout_below="@+id/edt1"
android:layout_toStartOf="@+id/button4"
android:layout_alignRight="@+id/button4"
android:layout_alignEnd="@+id/button4" />
<Button
573
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2"
android:id="@+id/button2"
android:layout_alignTop="@+id/button1"
android:layout_toLeftOf="@+id/button3"
android:layout_toStartOf="@+id/button3" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="3"
android:id="@+id/button3"
android:layout_alignTop="@+id/button2"
android:layout_centerHorizontal="true" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="4"
android:id="@+id/button4"
android:layout_below="@+id/button1"
android:layout_toLeftOf="@+id/button2" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="5"
android:id="@+id/button5"
android:layout_alignBottom="@+id/button4"
android:layout_alignLeft="@+id/button2"
android:layout_alignStart="@+id/button2" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="6"
android:id="@+id/button6"
android:layout_below="@+id/button3"
574
android:layout_alignLeft="@+id/button3"
android:layout_alignStart="@+id/button3" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="7"
android:id="@+id/button7"
android:layout_below="@+id/button4"
android:layout_toLeftOf="@+id/button2" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="8"
android:id="@+id/button8"
android:layout_below="@+id/button5"
android:layout_alignLeft="@+id/button5"
android:layout_alignStart="@+id/button5" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="9"
android:id="@+id/button9"
android:layout_below="@+id/button6"
android:layout_alignLeft="@+id/button6"
android:layout_alignStart="@+id/button6" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="+"
android:id="@+id/buttonadd"
android:layout_alignTop="@+id/button3"
android:layout_toRightOf="@+id/button3"
android:layout_marginLeft="46dp"
android:layout_marginStart="46dp"
android:layout_alignRight="@+id/edt1"
android:layout_alignEnd="@+id/edt1" />
575
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="-"
android:id="@+id/buttonsub"
android:layout_below="@+id/buttonadd"
android:layout_alignLeft="@+id/buttonadd"
android:layout_alignStart="@+id/buttonadd"
android:layout_alignRight="@+id/buttonadd"
android:layout_alignEnd="@+id/buttonadd" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="*"
android:id="@+id/buttonmul"
android:layout_below="@+id/buttonsub"
android:layout_alignLeft="@+id/buttonsub"
android:layout_alignStart="@+id/buttonsub"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="."
android:id="@+id/button10"
android:layout_below="@+id/button7"
android:layout_toLeftOf="@+id/button2" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:id="@+id/button0"
android:layout_below="@+id/button8"
android:layout_alignLeft="@+id/button8"
android:layout_alignStart="@+id/button8" />
576
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="C"
android:id="@+id/buttonC"
android:layout_below="@+id/button9"
android:layout_alignLeft="@+id/button9"
android:layout_alignStart="@+id/button9" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="/"
android:id="@+id/buttondiv"
android:layout_below="@+id/buttonmul"
android:layout_alignLeft="@+id/buttonmul"
android:layout_alignStart="@+id/buttonmul"
android:layout_alignRight="@+id/buttonmul"
android:layout_alignEnd="@+id/buttonmul" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="="
android:id="@+id/buttoneql"
android:layout_below="@+id/button0"
android:layout_marginTop="37dp"
android:layout_alignRight="@+id/buttondiv"
android:layout_alignEnd="@+id/buttondiv"
android:layout_alignLeft="@+id/button10"
android:layout_alignStart="@+id/button10" />
</RelativeLayout>
Battery level
MainActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.os.BatteryManager;
577
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.Menu;
import android.widget.TextView;
/* @Override*/
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
batteryPercent = (TextView) this.findViewById(R.id.batteryLevel);
getBatteryPercentage();
}
// @Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
578
activity_main.xml
<?xml version="1.0"?>
</RelativeLayout>
Airplane mode
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.Toast;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@SuppressWarnings("deprecation")
public void airPlanemodeON(View v) {
boolean isEnabled = Settings.System.getInt(this.getContentResolver(),
Settings.System.AIRPLANE_MODE_ON, 0) == 1;
if (isEnabled == false) {
modifyAirplanemode(true);
Toast.makeText(getApplicationContext(), "Airplane Mode ON",
579
Toast.LENGTH_LONG).show();
}
}
}
}
activity_main.xml
580
android:text="Airplane Mode OFF" android:onClick="airPlanemodeOFF"
android:layout_marginTop="116dp" android:layout_centerHorizontal="true"
android:id="@+id/ModeOFF" android:layout_below="@+id/buttonStop"/>
</RelativeLayout>
Android manifest.xml
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
MainActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.view.Menu;
import android.widget.TextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView value = (TextView) findViewById(R.id.res);
String result = "";
Context context = this;
PackageManager packageManager = context.getPackageManager();
if (packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
result += "Camera: YES";
}else{
result += "Camera: NO";
}
if (packageManager
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT)) {
result += "\nFront facing camera: YES";
}else{
result += "\nFront facing camera: NO";
581
}
if (packageManager
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) {
result += "\nCamera support flash: YES";
}else{
result += "\nCamera support flash: NO";
}
if (packageManager.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH)) {
result += "\nBluetooth: YES";
}else{
result += "\nBluetooth: NO";
}
if (packageManager.hasSystemFeature(PackageManager.FEATURE_NFC)) {
result += "\nNFC: YES";
}else{
result += "\nNFC: NO";
}
if (packageManager.hasSystemFeature(PackageManager.FEATURE_MICROPHONE)) {
result += "\nMicrophone: YES";
}else{
result += "\nMicrophone: NO";
}
if (packageManager
.hasSystemFeature(PackageManager.FEATURE_SENSOR_ACCELEROMETER)) {
result += "\nAccelerometer sensor: YES";
}else{
result += "\nAccelerometer sensor: NO";
}
if (packageManager
.hasSystemFeature(PackageManager.FEATURE_SENSOR_BAROMETER)) {
result += "Barometer (air pressure sensor) :YES";
}else{
result += "Barometer (air pressure sensor) :NO";
}
if (packageManager
.hasSystemFeature(PackageManager.FEATURE_SENSOR_COMPASS)) {
result += "\nMagnetometer (compass): YES";
}else{
result += "\nMagnetometer (compass): NO";
}
if (packageManager
.hasSystemFeature(PackageManager.FEATURE_SENSOR_GYROSCOPE)) {
result += "\nGyroscope: YES";
}else{
582
result += "\nGyroscope: NO";
}
if (packageManager
.hasSystemFeature(PackageManager.FEATURE_SENSOR_LIGHT)) {
result += "\nLight sensor: YES";
}else{
result += "\nLight sensor: YES";
}
if (packageManager
.hasSystemFeature(PackageManager.FEATURE_SENSOR_PROXIMITY)) {
result += "\nProximity sensor: YES";
} else {
result += "\nProximity sensor: NO";
}
value.setText(result);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
activity_main.xml
<?xml version="1.0"?>
</RelativeLayout>
583
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
584
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
activity_main.xml
<?xml version="1.0"?>
</RelativeLayout>
Android manifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
MainActivity.java
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
585
import android.provider.AlarmClock;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
activity_main.xml
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="alarm"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="177dp"
android:onClick="browser1" />
</LinearLayout>
Android manifest.xml
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
586
Battery Information
MainActivity.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Bundle;
import android.widget.TextView;
import android.support.v7.app.AppCompatActivity;
batteryLevel = (TextView)findViewById(R.id.batterylevel);
batteryVoltage = (TextView)findViewById(R.id.batteryvoltage);
batteryTemperature = (TextView)findViewById(R.id.batterytemperature);
batteryTechnology = (TextView)findViewById(R.id.batterytechology);
batteryStatus = (TextView)findViewById(R.id.batterystatus);
batteryHealth = (TextView)findViewById(R.id.batteryhealth);
this.registerReceiver(this.myBatteryReceiver,
new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
@Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
587
if (arg1.getAction().equals(Intent.ACTION_BATTERY_CHANGED)){
batteryLevel.setText("Level: "
+ String.valueOf(arg1.getIntExtra("level", 0)) + "%");
batteryVoltage.setText("Voltage: "
+ String.valueOf((float)arg1.getIntExtra("voltage", 0)/1000) +
"V");
batteryTemperature.setText("Temperature: "
+ String.valueOf((float)arg1.getIntExtra("temperature", 0)/10)
+ "c");
batteryTechnology.setText("Technology: " +
arg1.getStringExtra("technology"));
588
}
batteryHealth.setText("Health: " + strHealth);
}
}
};
}
activity_main.xml
589
android:text="Battery Temperature:"
/>
<TextView
android:id="@+id/batterytechology"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Technology:"
/>
<TextView
android:id="@+id/batterystatus"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Status:"
/>
<TextView
android:id="@+id/batteryhealth"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Health:"
/>
</LinearLayout>
Note: If you want to change the application name (from MyApplication to MyApplication5496), you
have to replace the statement
Brightness Control
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.content.ContentResolver;
import android.os.Bundle;
import android.provider.Settings.SettingNotFoundException;
590
import android.provider.Settings.System;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
TextView txtPerc;
try {
// Get the current system brightness
591
brightness = System.getInt(cResolver, System.SCREEN_BRIGHTNESS);
} catch (SettingNotFoundException e) {
// Throw an error case it couldn't be retrieved
Log.e("Error", "Cannot access system brightness");
e.printStackTrace();
}
// Set the progress of the seek bar based on the system's brightness
brightbar.setProgress(brightness);
592
});
}
}
activity_main.xml
</LinearLayout>
Android manifest.xml
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import java.util.List;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
593
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnRefresh.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
scanWifiList();
}
});
}
594
private void scanWifiList() {
mainWifi.startScan();
wifiList = mainWifi.getScanResults();
setAdapter();
ListAdapter.java
import java.util.List;
import android.content.Context;
import android.net.wifi.ScanResult;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
Context context;
LayoutInflater inflater;
List<ScanResult> wifiList;
@Override
public int getCount() {
return wifiList.size();
}
595
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Holder holder;
View view = convertView;
if (view == null) {
view = inflater.inflate(R.layout.dataset, null);
holder = new Holder();
holder.tvDetails = (TextView) view.findViewById(R.id.tvDetails);
view.setTag(holder);
} else {
holder = (Holder) view.getTag();
}
holder.tvDetails.setText("SSID :: " + wifiList.get(position).SSID
+ "\nStrength :: " + wifiList.get(position).level
+ "\nBSSID :: " + wifiList.get(position).BSSID
+ "\nChannel :: "
+ convertFrequencyToChannel(wifiList.get(position).frequency)
+ "\nFrequency :: " + wifiList.get(position).frequency
+ "\nCapability :: " + wifiList.get(position).capabilities);
return view;
}
596
class Holder {
TextView tvDetails;
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="${relativePackage}.${activityClass}" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.9"
android:orientation="vertical" >
<ListView
android:id="@+id/lvWifiDetails"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.1"
android:orientation="vertical" >
<Button
android:id="@+id/btnRefresh"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="5dp"
android:text="Refresh" />
</LinearLayout>
597
</LinearLayout>
dataset.xml
<TextView
android:id="@+id/tvDetails"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#000000" />
</LinearLayout>
Android manifest.xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
598
import android.content.IntentFilter;
import android.widget.ProgressBar;
import android.widget.TextView;
};
activity_main.xml
<ProgressBar android:layout_height="wrap_content"
android:layout_width="wrap_content" android:layout_marginTop="20dip"
android:layout_gravity="center" android:id="@+id/progressbar"
599
android:minWidth="200dip" android:minHeight="100dip" android:maxWidth="300dip"
android:maxHeight="500dip" android:max="100"
style="?android:attr/progressBarStyleHorizontal"/>
</LinearLayout>
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Intents.Insert;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.Toast;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtName = (EditText) findViewById(R.id.edtName);
edtNumber = (EditText) findViewById(R.id.edtPhone);
findViewById(R.id.btnInsert).setOnClickListener(this);
findViewById(R.id.btnGetContact).setOnClickListener(this);
}
@Override
public void onClick(View v) {
600
switch (v.getId()) {
case R.id.btnInsert:
Intent i = new Intent(Intent.ACTION_INSERT_OR_EDIT);
i.setType(Contacts.CONTENT_ITEM_TYPE);
i.putExtra(Insert.NAME, edtName.getText().toString());
i.putExtra(Insert.PHONE, edtNumber.getText().toString());
startActivity(i);
break;
case R.id.btnGetContact:
Intent callContactPickerIntent = new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI);
// filters contact with phone numbers
callContactPickerIntent
.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(callContactPickerIntent,
CALL_CONTACT_PICKER);
break;
default:
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == RESULT_OK) {
Cursor cursor = null;
cursor.close();
601
Toast.makeText(this, "Selection Fail", Toast.LENGTH_LONG)
.show();
return;
}
String contactName = cursor
.getString(cursor
.getColumnIndex((ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)
.toString().trim()));
String contactNumber = cursor
.getString(cursor
.getColumnIndex((ContactsContract.CommonDataKinds.Phone.NUMBER)));
switch (requestCode) {
case CALL_CONTACT_PICKER:
Toast.makeText(this,
"Name :" + contactName + "Number :" + contactNumber,
Toast.LENGTH_LONG).show();
break;
default:
break;
}
cursor.close();
} else {
// gracefully handle failure
Log.w("Auto Respond", "Warning: activity result not ok");
}
}
activity_main.xml
602
<EditText android:layout_height="wrap_content" android:layout_width="match_parent"
android:hint="Name" android:id="@+id/edtName"/>
</LinearLayout>
IP Address
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.text.format.Formatter;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
Button button;
TextView textview;
String IPaddress;
Boolean IPValue;
@Override
603
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button1);
textview = (TextView)findViewById(R.id.textView1);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
NetwordDetect();
}
});
ConnectivityManager CM = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
if (netInfo.getTypeName().equalsIgnoreCase("WIFI"))
if (netInfo.isConnected())
WIFI = true;
if (netInfo.getTypeName().equalsIgnoreCase("MOBILE"))
if (netInfo.isConnected())
604
MOBILE = true;
}
if(WIFI == true)
{
IPaddress = GetDeviceipWiFiData();
textview.setText(IPaddress);
if(MOBILE == true)
{
IPaddress = GetDeviceipMobileData();
textview.setText(IPaddress);
605
public String GetDeviceipWiFiData()
{
@SuppressWarnings("deprecation")
String ip =
Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
return ip;
activity_main.xml
<?xml version="1.0"?>
<RelativeLayout
tools:context="com.displayipaddress_android_examples.com.MainActivity"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
android:layout_height="match_parent" android:layout_width="match_parent"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android">
</RelativeLayout>
606
Android manifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
ZoomInOut WebView
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
WebView Webview;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Webview = (WebView)findViewById(R.id.webView1);
WebSettings webSetting = Webview.getSettings();
Webview.setWebViewClient(new WebViewClient());
Webview.loadUrl("http://google.com");
}
607
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
return super.shouldOverrideUrlLoading(view, url);
}
}
activity_main.xml
<?xml version="1.0"?>
<RelativeLayout tools:context=".MainActivity"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
android:layout_height="match_parent" android:layout_width="match_parent"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android">
</RelativeLayout>
Android manifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
608
import android.widget.Button;
import android.widget.TextView;
Button button;
Context context;
Intent intent1, intent2;
TextView textview;
LocationManager locationManager ;
boolean GpsStatus ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button1);
textview = (TextView)findViewById(R.id.textView1);
context = getApplicationContext();
CheckGpsStatus();
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
locationManager =
(LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
GpsStatus =
609
locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if(GpsStatus == true)
{
textview.setText("Location Services Is Enabled");
}else {
textview.setText("Location Services Is Disabled");
}
activity_main.xml
<?xml version="1.0"?>
<RelativeLayout tools:context=".MainActivity"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
android:layout_height="match_parent" android:layout_width="match_parent"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android">
</RelativeLayout>
Android manifest.xml
610
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
BLUETOOTH
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import java.util.Set;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
611
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
on(v);
}
});
offBtn = (Button)findViewById(R.id.turnOff);
offBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
off(v);
}
});
listBtn = (Button)findViewById(R.id.paired);
listBtn.setOnClickListener(new OnClickListener() {
@Override
612
public void onClick(View v) {
// TODO Auto-generated method stub
list(v);
}
});
findBtn = (Button)findViewById(R.id.search);
findBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
find(v);
}
});
myListView = (ListView)findViewById(R.id.listView1);
// create the arrayAdapter that contains the BTDevices, and set it to the
ListView
BTArrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1);
myListView.setAdapter(BTArrayAdapter);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if(requestCode == REQUEST_ENABLE_BT){
613
if(myBluetoothAdapter.isEnabled()) {
text.setText("Status: Enabled");
} else {
text.setText("Status: Disabled");
}
}
}
614
registerReceiver(bReceiver, new
IntentFilter(BluetoothDevice.ACTION_FOUND));
}
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregisterReceiver(bReceiver);
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="@string/Text" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="30dp" >
615
<Button
android:id="@+id/turnOn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/on" />
<Button
android:id="@+id/turnOff"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/off" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginTop="80dp" >
<Button
android:id="@+id/paired"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/List" />
<Button
android:id="@+id/search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/Find" />
<ListView
android:id="@+id/listView1"
android:layout_width="fill_parent"
android:layout_height="200dp" >
</ListView>
</LinearLayout>
</RelativeLayout>
616
String.xml
Android manifest.xml
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.app.Activity;
import android.content.Context;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
Button button;
TextView textview;
Context context;
LocationManager locationManager ;
boolean GpsStatus ;
@Override
protected void onCreate(Bundle savedInstanceState) {
617
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button1);
textview = (TextView)findViewById(R.id.textView1);
context = getApplicationContext();
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
CheckGpsStatus() ;
if(GpsStatus == true)
{
textview.setText("Location Services Is Enabled");
}else {
textview.setText("Location Services Is Disabled");
}
}
});
}
locationManager =
(LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
GpsStatus =
locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
activity_main.xml
<?xml version="1.0"?>
<RelativeLayout tools:context=".MainActivity"
618
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
android:layout_height="match_parent" android:layout_width="match_parent"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android">
</RelativeLayout>
Android manifest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.VideoView;
VideoView videoview ;
MediaController mediacontroller;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
619
videoview = (VideoView)findViewById(R.id.videoView1);
mediacontroller = new MediaController(MainActivity.this);
videoview.setVideoPath(
"http://www.android-examples.com/wp-
content/uploads/2016/01/sample_video.3gp");
mediacontroller.setAnchorView(videoview);
videoview.setMediaController(mediacontroller);
videoview.start();
}
}
activity_main.xml
<?xml version="1.0"?>
<VideoView android:layout_height="wrap_content"
android:layout_width="wrap_content" android:layout_centerVertical="true"
android:layout_centerHorizontal="true" android:id="@+id/videoView1"/>
</RelativeLayout>
Android manifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
620
Play music from internet
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import java.io.IOException;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
Button buttonStop,buttonStart ;
MediaPlayer mediaplayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonStart = (Button)findViewById(R.id.button1);
buttonStop = (Button)findViewById(R.id.button2);
buttonStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
mediaplayer.setDataSource(AudioURL);
mediaplayer.prepare();
621
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mediaplayer.start();
}
});
buttonStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mediaplayer.stop();
}
});
}
activity_main.xml
<?xml version="1.0"?>
<RelativeLayout tools:context=".MainActivity"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
622
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
android:layout_height="match_parent" android:layout_width="match_parent"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android">
</RelativeLayout>
Android manifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
model = (TextView)findViewById(R.id.textView1);
623
device = (TextView)findViewById(R.id.textView2);
getboth = (Button)findViewById(R.id.button1);
getboth.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DeviceModel= android.os.Build.MODEL;
DeviceName= android.os.Build.MANUFACTURER;
model.setText(DeviceModel);
device.setText(DeviceName);
}
});
}
}
activity_main.xml
<?xml version="1.0"?>
<RelativeLayout tools:context=".MainActivity"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
android:layout_height="match_parent" android:layout_width="match_parent"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android">
624
android:layout_centerVertical="true"/>
</RelativeLayout>
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.content.Context;
import android.media.AudioManager;
import android.os.Bundle;
import android.widget.SeekBar;
alarm = (SeekBar)findViewById(R.id.seekBar1);
mediaPlayer = (SeekBar)findViewById(R.id.seekBar2);
ringer = (SeekBar)findViewById(R.id.seekBar3);
notification = (SeekBar)findViewById(R.id.seekBar4);
alarm.setMax(audioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM));
mediaPlayer.setMax(audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
ringer.setMax(audioManager.getStreamMaxVolume(AudioManager.STREAM_RING));
625
notification.setMax(audioManager.getStreamMaxVolume(AudioManager.STREAM_NOTIFICATION))
;
alarm.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
audioManager.setStreamVolume(AudioManager.STREAM_ALARM, i, 0);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
mediaPlayer.setOnSeekBarChangeListener(new
SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, i, 0);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
626
ringer.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
audioManager.setStreamVolume(AudioManager.STREAM_RING, i, 0);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
notification.setOnSeekBarChangeListener(new
SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION, i,
0);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
}
activity_main.xml
627
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="Set Alarm Volume"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_marginTop="10dp" />
<SeekBar
android:id="@+id/seekBar1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/seekBar1"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:text="Set Media Player Volume"
android:textAppearance="?android:attr/textAppearanceLarge" />
<SeekBar
android:id="@+id/seekBar2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView2"
628
android:layout_marginTop="10dp" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/seekBar2"
android:layout_centerHorizontal="true"
android:text="Set Ringer Volume"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_marginTop="10dp" />
<SeekBar
android:id="@+id/seekBar3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginTop="10dp" />
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/seekBar3"
android:layout_centerHorizontal="true"
android:text="Set Notification Volume"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_marginTop="10dp" />
<SeekBar
android:id="@+id/seekBar4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView4"
android:layout_marginTop="10dp" />
</RelativeLayout>
Intent
629
MainActivity.java
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.EditText;
630
Intent i = new Intent();
i.setAction(Intent.ACTION_VIEW);
i.setData(Uri.parse("content://media/external/images/media/"));
startActivity(i);
}
});
});
631
Intent i = new Intent();
i.setAction(Intent.ACTION_VIEW);
i.setData(Uri.parse("content://contacts/people/"));
startActivity(i);
}
});
}
});
632
}
}
activity_main.xml
<!-- EDIT TEXT with the hint of "Enter Phone No." -->
<EditText
android:id="@+id/etNo"
android:layout_width="match_parent"
android:layout_height="60dp"
android:hint="Enter phone no."
android:inputType="phone" />
633
<Button
android:id="@+id/btnBrowser"
android:layout_width="match_parent"
android:layout_height="55dp"
android:text="Browser" />
</LinearLayout>
Android manifest.xml
MainActivity.java
634
import android.content.Intent;
import android.content.res.AssetManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.content.Context;
import android.util.Log;
;import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
InputStream in = null;
OutputStream out = null;
File file = new File(getFilesDir(), "006JavaScript.pdf");
try {
in = assetManager.open("006JavaScript.pdf");
out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);
copyPdfFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e) {
Log.e("exception", e.getMessage());
}
635
"application/pdf");
startActivity(intent);
}
Android manifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
MainActivity.java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.ExpandableListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.SimpleExpandableListAdapter;
import android.widget.Toast;
636
private ExpandableListAdapter mAdapter;
ExpandableListView expand;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/* ***ChildData ***/
Map<String, String> curChildMap4 = new HashMap<String, String>();
children1.add(curChildMap4);
curChildMap4.put("child", "State");
/* ***ChildData ***/
Map<String, String> curChildMap5 = new HashMap<String, String>();
children1.add(curChildMap5);
curChildMap5.put("child", "City");
childData.add(children1);
637
/* *************************End Group **************************/
childData.add(children2);
expand = getExpandableListView();
expand.setOnChildClickListener(new OnChildClickListener() {
638
@Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id)
{
// TODO Auto-generated method stub
switch (groupPosition)
{
case 0 :
switch(childPosition)
{
case 0 :
Toast.makeText(getBaseContext(), "Bank",
Toast.LENGTH_SHORT).show();
break;
case 1:
Toast.makeText(getBaseContext(), "Executive",
Toast.LENGTH_SHORT).show();
break;
case 2:
Toast.makeText(getBaseContext(), "Customer",
Toast.LENGTH_SHORT).show();
break;
case 3 :
Toast.makeText(getBaseContext(), "State",
Toast.LENGTH_SHORT).show();
break;
case 4 :
Toast.makeText(getBaseContext(), "City",
Toast.LENGTH_SHORT).show();
break;
}
break;
case 1:
switch(childPosition)
{
case 0 :
Toast.makeText(getBaseContext(), "Android",
Toast.LENGTH_SHORT).show();
break;
case 1:
Toast.makeText(getBaseContext(), "iPhone",
Toast.LENGTH_SHORT).show();
639
break;
case 2:
Toast.makeText(getBaseContext(), "Windows",
Toast.LENGTH_SHORT).show();
break;
}
break;
}
return false;
}
});
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</RelativeLayout>
Android Manifest.xml file stores essential information about the android application
and provides essential information about your app to the Android system, information
the system must have before it can run any of the app's code.
Send EMAIL
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.net.Uri;
640
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
Button Send;
EditText TO, CC, SUBJECT, MSG;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Send.setOnClickListener(new View.OnClickListener() {
String to = TO.getText().toString();
String cc = CC.getText().toString();
String subject = SUBJECT.getText().toString();
String msg = MSG.getText().toString();
TO.setText(null);
CC.setText(null);
SUBJECT.setText(null);
MSG.setText(null);
}
});
}
641
private void sendEmail(String emailAddresses, String carbonCopies,
String subject, String message)
{
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.setData(Uri.parse("mailto:"));
String to = emailAddresses;
String cc = carbonCopies;
emailIntent.putExtra(Intent.EXTRA_EMAIL, to);
emailIntent.putExtra(Intent.EXTRA_CC, cc);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
emailIntent.putExtra(Intent.EXTRA_TEXT, message);
emailIntent.setType("message/rfc822");
startActivity(Intent.createChooser(emailIntent, "Email"));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<EditText
android:id="@+id/editText1"
android:hint="To"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:ems="13"
android:inputType="textEmailAddress" >
642
<requestFocus />
</EditText>
<EditText
android:id="@+id/editText2"
android:hint="cc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp"
android:ems="13"
android:inputType="textEmailAddress" />
<EditText
android:id="@+id/editText3"
android:hint="Subject"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="150dp"
android:ems="13" />
<EditText
android:id="@+id/editText4"
android:hint="Message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="200dp"
android:ems="13"
android:inputType="textMultiLine" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="280dp"
android:text="Send E-Mail" />
643
</RelativeLayout>
Android manifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
MainActivity.java
import android.annotation.TargetApi;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import java.util.Calendar;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
@Override
public void onClick(View arg0) {
});
644
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/txt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Android Calender" />
<Button
android:id="@+id/btn1"
android:layout_below="@+id/txt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/event" />
645
</RelativeLayout>
Android manifest.xml
String.xml
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ViewFlipper
android:id="@+id/viewflipper"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:autoStart="true"
android:flipInterval="2000" >
646
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/picture1" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/picture2" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/picture3" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/picture4" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/picture4" />
</ViewFlipper>
</RelativeLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
647
android:layout_height="wrap_content"
android:text="Hello"
android:textStyle="bold|italic"
android:layout_gravity="center_horizontal" />
<TextView
android:id="@+id/shadowtext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="http://android-er.blogspot.com/"
android:textStyle="bold"
android:textSize="50sp"
android:textColor="#0000ff"
android:focusable="true"
android:focusableInTouchMode="true"
android:singleLine="true"
android:scrollHorizontally="true"
android:ellipsize="marquee"
android:marqueeRepeatLimit ="marquee_forever" />
</LinearLayout>
MainActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import java.text.DecimalFormat;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
648
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mLoanAmount = (EditText)findViewById(R.id.loan_amount);
mInterestRate = (EditText)findViewById(R.id.interest_rate);
mLoanPeriod = (EditText)findViewById(R.id.loan_period);
mMontlyPaymentResult = (TextView)findViewById(R.id.monthly_payment_result);
mTotalPaymentsResult = (TextView)findViewById(R.id.total_payments_result);
}
mMontlyPaymentResult.setText(new
DecimalFormat("##.##").format(monthlyPayment));
mTotalPaymentsResult.setText(new DecimalFormat("##.##").format(totalPayment));
}
}
activity_main.xml
649
</EditText>
</TableRow>
<TableRow>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/interest_rate_prompt"
android:gravity="right"/>
<EditText android:id="@+id/interest_rate"
android:inputType="numberDecimal"
android:layout_height="wrap_content"/>
</TableRow>
<TableRow>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/loan_period_prompt"
android:gravity="right"/>
<EditText android:id="@+id/loan_period"
android:inputType="number"
android:layout_height="wrap_content"/>
</TableRow>
<TableRow>
<Button android:text="@string/loan_button_text"
android:layout_span="2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="showLoanPayments"/>
</TableRow>
<TableRow android:layout_marginTop="20dp">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/monthly_payment_prompt"
android:gravity="right"/>
<TextView android:id="@+id/monthly_payment_result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ff0000"
android:gravity="left"/>
</TableRow>
<TableRow>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/total_payments_prompt"
android:gravity="right"/>
<TextView android:id="@+id/total_payments_result"
android:layout_width="wrap_content"
650
android:layout_height="wrap_content"
android:textColor="#ff0000"
android:gravity="left"/>
</TableRow>
</TableLayout>
strings.xml
<resources>
<string name="hello_world">Hello world!</string>
<string name="menu_settings">Settings</string>
<string name="loan_amount_prompt">Loan amount:  </string>
<string name="interest_rate_prompt">Interest rate:  </string>
<string name="loan_period_prompt">Months:  </string>
<string name="loan_button_text">Calculate Payments</string>
<string name="monthly_payment_prompt">Monthly payment:  </string>
<string name="total_payments_prompt">Total payments:  </string>
</resources>
MainActivity.java
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
// variable declaration
private ListView mainList;
private MediaPlayer mp;
private final String[] listContent = { "chimes", "chord", "ding" };
651
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initializing variables
mp = new MediaPlayer();
mainList = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, listContent);
mainList.setAdapter(adapter);
mainList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view,
int position, long id) {
playSong(position);
}
});
@Override
public void onDestroy() {
super.onDestroy();
mp.release();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
652
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.audio.MainActivity" >
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" >
</ListView>
</RelativeLayout>
raw folder
653
chimes.mp3 chord.mp3 ding.mp3
MainActivity.java
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.app.Activity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
654
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#458"
android:orientation="vertical" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="200dp"
android:layout_height="200dp"
/>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:text="First Image "
android:onClick="mess"/>
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:text="Second Image"
android:onClick="mess"/>
</LinearLayout>
MainActivity.java
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
655
public class MainActivity extends Activity {
protected static final String TAG = "MainActivity";
/** Called when the activity is first created. */
Button meowBtn;
MediaPlayer mPlayer;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
meowBtn = (Button) findViewById(R.id.button1);
mPlayer = MediaPlayer.create(MainActivity.this, R.raw.chimes);
meowBtn.setOnClickListener(new View.OnClickListener() {
});
}
}
}
activity_main.xml
656
android:orientation="vertical" >
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/image1" />
</LinearLayout>
activity_main.xml
<TableRow
android:id="@+id/tableRow1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal" >
<TextView
android:id="@+id/textView11"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_span="6"
android:gravity="center"
android:text="Weather Report"
android:textSize="18dp"
android:textStyle="bold" >
</TextView>
</TableRow>
<TableRow
android:id="@+id/tableRow2"
android:layout_width="match_parent"
657
android:layout_height="wrap_content" >
<TextView
android:id="@+id/TextView21"
android:text="" >
</TextView>
<TextView
android:id="@+id/TextView22"
android:gravity="center"
android:text="M"
android:textStyle="bold"
android:typeface="serif" >
</TextView>
<TextView
android:id="@+id/TextView23"
android:gravity="center"
android:text="T"
android:textStyle="bold"
android:typeface="serif" >
</TextView>
<TextView
android:id="@+id/TextView24"
android:gravity="center"
android:text="W"
android:textStyle="bold"
android:typeface="serif" >
</TextView>
<TextView
android:id="@+id/TextView25"
android:gravity="center"
android:text="T"
android:textStyle="bold"
android:typeface="serif" >
</TextView>
<TextView
android:id="@+id/textView26"
android:gravity="center"
android:text="F"
android:textStyle="bold"
android:typeface="serif" >
658
</TextView>
</TableRow>
<TableRow
android:id="@+id/tableRow3"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView31"
android:text="Day High"
android:textStyle="bold" >
</TextView>
<TextView
android:id="@+id/textView32"
android:gravity="center_horizontal"
android:text="34°C" >
</TextView>
<TextView
android:id="@+id/textView33"
android:gravity="center_horizontal"
android:text="35°C" >
</TextView>
<TextView
android:id="@+id/textView34"
android:gravity="center_horizontal"
android:text="34°C" >
</TextView>
<TextView
android:id="@+id/textView35"
android:gravity="center_horizontal"
android:text="35°C" >
</TextView>
<TextView
android:id="@+id/textView36"
android:gravity="center_horizontal"
android:text="33°C" >
</TextView>
</TableRow>
659
<TableRow
android:id="@+id/tableRow4"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView41"
android:text="Day Low"
android:textStyle="bold" >
</TextView>
<TextView
android:id="@+id/textView42"
android:gravity="center_horizontal"
android:text="28°C" >
</TextView>
<TextView
android:id="@+id/textView43"
android:gravity="center_horizontal"
android:text="27°C" >
</TextView>
<TextView
android:id="@+id/textView44"
android:gravity="center_horizontal"
android:text="29°C" >
</TextView>
<TextView
android:id="@+id/textView45"
android:gravity="center_horizontal"
android:text="26°C" >
</TextView>
<TextView
android:id="@+id/textView46"
android:gravity="center_horizontal"
android:text="29°C" >
</TextView>
</TableRow>
<TableRow
android:id="@+id/tableRow5"
android:layout_width="match_parent"
660
android:layout_height="wrap_content"
android:gravity="center" >
<TextView
android:id="@+id/textView8"
android:text="Conditions"
android:textStyle="bold" >
</TextView>
<ImageView
android:id="@+id/imageView1"
android:src="@drawable/monday" >
</ImageView>
<ImageView
android:id="@+id/imageView2"
android:src="@drawable/tuesday" >
</ImageView>
<ImageView
android:id="@+id/imageView3"
android:src="@drawable/wednesday" >
</ImageView>
<ImageView
android:id="@+id/imageView4"
android:src="@drawable/thursday" >
</ImageView>
<ImageView
android:id="@+id/imageView5"
android:src="@drawable/friday" >
</ImageView>
</TableRow>
</TableLayout>
MainActivity.java
import android.os.Bundle;
661
import android.app.Activity;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.ib1).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (TextUtils.isEmpty(str1)) {
e1.setError("Please enter your weight");
e1.requestFocus();
return;
}
if (TextUtils.isEmpty(str2)) {
e2.setError("Please enter your height");
e2.requestFocus();
return;
}
662
tv4.setText(String.valueOf(bmiValue + "-" + bmiInterpretation));
}
});
return "Underweight";
} else if (bmiValue < 25) {
return "Normal";
} else if (bmiValue < 30) {
return "Overweight";
} else {
return "Obese";
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/green_back"
android:fadingEdge="horizontal"
663
android:orientation="vertical" >
<TextView
android:id="@+id/tv1"
android:layout_width="124dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:paddingLeft="15dp"
android:paddingTop="40dp"
android:shadowColor="@android:color/black"
android:shadowDx="4"
android:shadowDy="4"
android:text="BMI"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="@android:color/white"
android:textSize="50sp"
android:typeface="serif" />
<TextView
android:id="@+id/tv2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Calculator"
android:textColor="@android:color/white"
android:textSize="20dp"
android:textStyle="bold" />
<TextView
android:id="@+id/tv3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:paddingTop="30dp"
android:text="WEIGHT (KG)"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="@android:color/white"
android:textStyle="bold|italic"
android:typeface="serif" />
<EditText
android:id="@+id/et1"
android:layout_width="96dp"
android:layout_height="wrap_content"
664
android:layout_gravity="center"
android:hint="IN KGs"
android:ems="10"
android:fadingEdgeLength="10dp"
android:inputType="numberDecimal"
android:textAlignment="center" >
<requestFocus />
</EditText>
<TextView
android:id="@+id/tv3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:paddingTop="30dp"
android:text="HEIGHT (CM)"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="@android:color/white"
android:textStyle="bold|italic"
android:typeface="serif" />
<EditText
android:id="@+id/et2"
android:layout_width="96dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:hint="IN CMs"
android:ems="10"
android:inputType="numberDecimal"
>
</EditText>
<Button
android:id="@+id/ib1"
android:layout_width="158dp"
android:layout_height="51dp"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:fadingEdge="vertical"
android:longClickable="true"
android:nextFocusRight="@color/colorPrimary"
android:text="Calculate"
android:visibility="visible" />
665
<TextView
android:id="@+id/tv4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:paddingTop="20dp"
android:text=""
android:textSize="20dp"
android:textStyle="bold"
android:textColor="@color/colorPrimary"/>
</LinearLayout>
colors.xml
MainActivity.java
import android.Manifest;
import android.content.pm.PackageManager;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.support.v4.app.ActivityCompat;
import android.widget.Toast;
Button button ;
666
TextView textView;
Boolean SDcard ;
public static final int RequestPermissionCode = 1 ;
int RequestCheckResult ;
boolean RequestTF ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button);
textView = (TextView)findViewById(R.id.textView);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
PermissionStatus();
if(RequestTF){
SDCardCheck();
}
else {
EnableRuntimePermission();
}
}
});
}
SDcard =
android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_M
OUNTED);
if(SDcard)
{
textView.setText("SD CARD IS AVAILABLE");
}
else
{
667
textView.setText("SD CARD NOT AVAILABLE");
}
}
RequestCheckResult =
ContextCompat.checkSelfPermission(getApplicationContext(),
Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (RequestCheckResult == PackageManager.PERMISSION_GRANTED){
RequestTF = true;
} else {
RequestTF = false;
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE))
{
} else {
ActivityCompat.requestPermissions(MainActivity.this,new String[]{
Manifest.permission.WRITE_EXTERNAL_STORAGE},
RequestPermissionCode);
}
}
@Override
public void onRequestPermissionsResult(int RC, String per[], int[] PResult) {
switch (RC) {
668
case RequestPermissionCode:
} else {
}
break;
}
}
activity_main.xml
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="click here to detect whether the sd card is available or not"
android:id="@+id/button"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="SD CARD STATUS"
android:id="@+id/textView"
android:layout_above="@+id/button"
669
android:layout_centerHorizontal="true"
android:layout_marginBottom="38dp"
android:gravity="center"/>
</RelativeLayout>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
MainActivity.java
import java.util.Locale;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
String Language;
Button GetLanguageButton;
TextView DisplayLanguageTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GetLanguageButton = (Button)findViewById(R.id.button1);
DisplayLanguageTextView = (TextView)findViewById(R.id.textView1);
GetLanguageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Language = Locale.getDefault().getDisplayLanguage().toString();
670
DisplayLanguageTextView.setText(Language);
}
});
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="22dp"
android:text="Click here to Get current device language in android
programmatically" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="168dp"
android:text="Default Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
671
Detect battery is charging, not charging, discharge and full and show on screen on button
click in android
MainActivity.java
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
TextView textview;
Button button;
IntentFilter intentfilter;
int deviceStatus;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button1);
textview = (TextView)findViewById(R.id.textView1);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
MainActivity.this.registerReceiver(broadcastreceiver,intentfilter);
}
});
672
}
deviceStatus = intent.getIntExtra(BatteryManager.EXTRA_STATUS,-1);
if(deviceStatus == BatteryManager.BATTERY_STATUS_CHARGING){
if(deviceStatus == BatteryManager.BATTERY_STATUS_DISCHARGING){
if (deviceStatus == BatteryManager.BATTERY_STATUS_FULL){
if(deviceStatus == BatteryManager.BATTERY_STATUS_UNKNOWN){
if (deviceStatus == BatteryManager.BATTERY_STATUS_NOT_CHARGING){
}
};
}
activity_main.xml
673
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Status"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"
android:text="Click here to Get battery status in android programmatically" />
</RelativeLayout>
MainActivity.java
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Bundle;
674
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
TextView textview;
Button button;
Context context;
IntentFilter intentfilter;
int status;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textview = (TextView)findViewById(R.id.textView1);
button = (Button)findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
MainActivity.this.registerReceiver(broadcastreceiver,intentfilter);
}
});
}
status = intent.getIntExtra(BatteryManager.EXTRA_HEALTH,0);
if(status == BatteryManager.BATTERY_HEALTH_COLD){
}
if (status == BatteryManager.BATTERY_HEALTH_DEAD){
675
textview.setText("Battery health = Dead");
}
if (status == BatteryManager.BATTERY_HEALTH_GOOD){
}
if (status == BatteryManager.BATTERY_HEALTH_OVERHEAT){
}
if (status == BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE){
}
if(status == BatteryManager.BATTERY_HEALTH_UNKNOWN){
}
if(status == BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE){
}
}
};
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
676
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="184dp"
android:text="Battery health"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="17dp"
android:text="Click here to Check/Get battery health in android
programmatically" />
</RelativeLayout>
MainActivity.java
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.WindowManager;
import android.widget.TextView;
TextView one,two;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
677
one = (TextView)findViewById(R.id.textView2);
two = (TextView)findViewById(R.id.textView4);
one.setText(String.valueOf(deviceWidth));
two.setText(String.valueOf(deviceHeight));
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
678
android:layout_centerHorizontal="true"
android:layout_marginTop="176dp"
android:text="Width in Pixels"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/textView1"
android:layout_below="@+id/textView2"
android:layout_marginTop="24dp"
android:text="Height in Pixels"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView2"
android:layout_below="@+id/textView3"
android:layout_marginTop="16dp"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
activity_main.xml
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="25dp" />
679
How to parse xml file in Assert folder in Android using Dom Parser
MainActivity.java
import android.os.Bundle;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import android.app.Activity;
import android.widget.TextView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView1);
try {
inputStream = getAssets().open("employeesdetails.xml");
dbFactory = DocumentBuilderFactory.newInstance();
docBuilder = dbFactory.newDocumentBuilder();
doc = docBuilder.parse(inputStream);
element = doc.getDocumentElement();
element.normalize();
680
} catch (Exception e) {
e.printStackTrace();
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="86dp"
android:layout_marginTop="77dp"
android:text="TextView" />
</RelativeLayout>
<?xml version="1.0"?>
<employee_list>
<employee>
<employee_id>1001</employee_id>
<employee_name>Android </employee_name>
<employee_salary>50000</employee_salary>
</employee>
<employee>
<employee_id>1002</employee_id>
<employee_name>Surya </employee_name>
<employee_salary>60000</employee_salary>
</employee>
<employee>
<employee_id>1003</employee_id>
<employee_name>Narayana </employee_name>
<employee_salary>40000</employee_salary>
</employee>
681
</employee_list>
StrikeTextView in Android
MainActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.StrikethroughSpan;
import android.view.Menu;
import android.widget.TextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
activity_main.xml
<TextView
android:id="@+id/striketxt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
682
android:text=""
android:textSize="25px" />
</LinearLayout>
MainActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.UnderlineSpan;
import android.view.Menu;
import android.widget.TextView;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spanned.SPAN_PARAGRAPH);
txtView.setText(str);
@Override
// Inflate the menu; this adds items to the action bar if it is present.
683
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
activity_main.xml
<TextView
android:id="@+id/underlinetxt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=""
android:textSize="25px" />
</LinearLayout>
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ViewFlipper;
ViewFlipper viewFlipper;
Button next;
Button previous;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
684
viewFlipper = (ViewFlipper)findViewById(R.id.viewFlipper);
next.setOnClickListener(this);
previous.setOnClickListener(this);
@Override
if (v == next) {
viewFlipper.showNext();
else if (v == previous) {
viewFlipper.showPrevious();
activity_main.xml
685
android:src="@drawable/picture1"/>
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="fitXY"
android:id="@+id/imageView2"
android:src="@drawable/picture2"/>
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="fitXY"
android:id="@+id/imageView3"
android:src="@drawable/picture3"/>
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="fitXY"
android:id="@+id/imageView4"
android:src="@drawable/picture4"/>
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="fitXY"
android:id="@+id/imageView5"
android:src="@drawable/picture5"/>
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="fitXY"
android:id="@+id/imageView6"
android:src="@drawable/picture1"/>
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="fitXY"
android:id="@+id/imageView7"
android:src="@drawable/picture2"/>
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="fitXY"
android:id="@+id/imageView8"
android:src="@drawable/picture3"/>
<ImageView
android:layout_width="fill_parent"
686
android:layout_height="fill_parent"
android:scaleType="fitXY"
android:id="@+id/imageView9"
android:src="@drawable/picture4"/>
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="fitXY"
android:id="@+id/imageView10"
android:src="@drawable/picture4"/>
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="fitXY"
android:id="@+id/imageView11"
android:src="@drawable/picture5"/>
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="fitXY"
android:id="@+id/imageView12"
android:src="@drawable/picture1"/>
</ViewFlipper>
<Button
android:id="@+id/next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Next"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
<Button
android:id="@+id/previous"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Prev"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_alignTop="@+id/next"/>
</RelativeLayout>
687
Kotlin versus Java
Kotlin Java
violation.
object.
688
Unit Description
sp Scale Independent Pixel. This is very similar to dp but just that this is recommended for specifying font
sizes.
Method Description
onStartCommand() This method is called when any other component, like say an activity,
requests the service to be started, by calling startService().
It is your responsibility to stop the service when the corresponding
work is done by using stopSelf() or stopService() methods.
onBind() Calls this method when another component wants to bind with the
service by calling bindService().
To implement this, you must provide an interface that clients use in
order to communicate with the service. It returns an IBinder object.
If you don’t want to allow binding, then return null.
onUnbind() The system calls this method when all clients are disconnected from a
particular interface published by the service.
onRebind() Calls this method when new clients are connected to the service after it had
previously been notified that all are disconnected in onUnbind(Intent).
onCreate() The system calls this method when the service is created first using
onStartCommand() or onBind(). It is required to perform a one-time set-
up.
onDestroy() This method is called when the service is no longer used and is being
destroyed. Your service should implement this in order to clean up any
resources such as threads, registered listeners, receivers, etc.
689
Android versus iOS
Android iOS
Development Complexity High Low
Cost Costs more due to higher Costs less
testing period
Programming language Java and Kotlin Require Objective C or Swift for
Native development
Security Not very secure Highly secured
Speed Faster mean download Much faster than Android
690
Linus Benedict Torvalds is a Finnish-American software engineer who is the creator and,
historically, the main developer of the Linux kernel, used by Linux distributions and other
operating systems such as Android and Chrome OS.
Source of information:
https://www.wikipedia.org/
https://www.google.com/
691