Notes and

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 87

Use dp for button images

Use sp for texts


Import
Definition and Usage
The import keyword is used to import a package, class or interface.

Example
Import the Scanner class from the Java API:

import java.util.Scanner;

class MyClass {

public static void main(String[] args) {

Scanner myObj = new Scanner(System.in);

System.out.println("Enter username");

String userName = myObj.nextLine();

System.out.println("Username is: " + userName);

Public
Definition and Usage
The public keyword is an access modifier used for classes, attributes,
methods and constructors, making them accessible by any other class.
Example
MyClass accesses a public Person class with public attributes:

/* Code from filename: Person.java

public class Person {

public String fname = "John";

public String lname = "Doe";

public String email = "john@doe.com";

public int age = 24;

*/

class MyClass {

public static void main(String[] args) {

Person myObj = new Person();

System.out.println("Name: " + myObj.fname + " " + myObj.lname);

System.out.println("Email: " + myObj.email);

System.out.println("Age: " + myObj.age);

class

A type that defines the implementation of a particular kind of object. A class definition defines instance and
class fields, methods, and inner classes as well as specifying the interfaces the class implements and the
immediate superclass of the class. If the superclass is not explicitly specified, the superclass is implicitly Object.
The class keyword can also be used in the form Class.class to get a Class object without needing an instance of
that class. For example, String.class can be used instead of doing new String().getClass().

Class

Collection of objects is called class. It is a logical entity.

Inheritance
When one object acquires all the properties and behaviours of parent object i.e.
known as inheritance. It provides code reusability. It is used to achieve runtime
polymorphism.

Link

http://tutorials.jenkov.com/java/classes.html

extends
extends

Used in a class declaration to specify the superclass; used in an interface declaration to specify one or more
superinterfaces. Class X extends class Y to add functionality, either by adding fields or methods to class Y, or by
overriding methods of class Y. An interface Z extends one or more interfaces by adding methods. Class X is said
to be a subclass of class Y; Interface Z is said to be a subinterface of the interfaces it extends.
Inheritance in Java
1. Inheritance
2. Types of Inheritance
3. Why multiple inheritance is not possible in java in case of class?

Inheritance in java is a mechanism in which one object acquires all the properties and
behaviors of parent object.

The idea behind inheritance in java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and fields
of parent class, and you can add new methods and fields also.

Inheritance represents the IS-A relationship, also known as parent-child relationship.

Why use inheritance in java


o For Method Overriding (so runtime polymorphism can be achieved).
o For Code Reusability.

Syntax of Java Inheritance


1. class Subclass-name extends Superclass-name
2. {
3. //methods and fields
4. }

The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.

In the terminology of Java, a class which is inherited is called parent or super class and
the new class is called child or subclass.
Java Inheritance Example

As displayed in the above figure, Programmer is the subclass and Employee is the
superclass. Relationship between two classes is Programmer IS-A Employee.It means
that Programmer is a type of Employee.

1. class Employee{
2. float salary=40000;
3. }
4. class Programmer extends Employee{
5. int bonus=10000;
6. public static void main(String args[]){
7. Programmer p=new Programmer();
8. System.out.println("Programmer salary is:"+p.salary);
9. System.out.println("Bonus of Programmer is:"+p.bonus);
10. }
11. }
Test it Now
Programmer salary is:40000.0
Bonus of programmer is:10000

In the above example, Programmer object can access the field of own class as well as of
Employee class i.e. code reusability.

Types of inheritance in java

On the basis of class, there can be three types of inheritance in java: single, multilevel
and hierarchical.

In java programming, multiple and hybrid inheritance is supported through interface only.
We will learn about interfaces later.
Note: Multiple inheritance is not supported in java through class.

When a class extends multiple classes i.e. known as multiple inheritance. For Example:
Single Inheritance Example

File: TestInheritance.java

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class TestInheritance{
8. public static void main(String args[]){
9. Dog d=new Dog();
10. d.bark();
11. d.eat();
12. }}

Output:

barking...
eating...
Multilevel Inheritance Example

File: TestInheritance2.java

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class BabyDog extends Dog{
8. void weep(){System.out.println("weeping...");}
9. }
10. class TestInheritance2{
11. public static void main(String args[]){
12. BabyDog d=new BabyDog();
13. d.weep();
14. d.bark();
15. d.eat();
16. }}

Output:

weeping...
barking...
eating...
Hierarchical Inheritance Example

File: TestInheritance3.java

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class Cat extends Animal{
8. void meow(){System.out.println("meowing...");}
9. }
10. class TestInheritance3{
11. public static void main(String args[]){
12. Cat c=new Cat();
13. c.meow();
14. c.eat();
15. //c.bark();//C.T.Error
16. }}

Output:

meowing...
eating...

Q) Why multiple inheritance is not supported in java?

To reduce the complexity and simplify the language, multiple inheritance is not supported
in java.

Consider a scenario where A, B and C are three classes. The C class inherits A and B
classes. If A and B classes have same method and you call it from child class object, there
will be ambiguity to call method of A or B class.

Since compile time errors are better than runtime errors, java renders compile time error
if you inherit 2 classes. So whether you have same method or different, there will be
compile time error now.

1. class A{
2. void msg(){System.out.println("Hello");}
3. }
4. class B{
5. void msg(){System.out.println("Welcome");}
6. }
7. class C extends A,B{//suppose if it were
8.
9. Public Static void main(String args[]){
10. C obj=new C();
11. obj.msg();//Now which msg() method would be invoked?
12. }
13. }
Test it Now
Compile Time Error
AppCompatActivity
As Chris wrote, new deprecated version of ActionBarActivity (the one
extending AppCompatActivity class) is a safe to use backward compatibility class. Its
deprecation is just a hint for you asking to use new AppCompatActivity directly
instead. AppCompatActivity is a new, more generic implementation which
uses AppCompatDelegate class internally.
If you start a new development, then you should rather use new AppCompatActivity class
right away. If you have a chance to update your app, then replace
deprecated ActionBarActivity by the new activity as well. Otherwise you can stay with
deprecated activity and there will be no difference in behavior at all.
Regarding AppCompatDelegate, it allows you to have new tinted widgets in an activity,
which is neither AppCompatActivity nor ActionBarActivity.
For instance, you inherit an activity from an external library, which, in turn,
does not inherit from AppCompatActivity but you want this activity to have tinted
materials widgets (views). To make it happen you need to create an instance
of AppCompatDelegate inside your activity, override methods of that activity
like addContentView(), setContentView() etc. (see AppCompatDelegate javadoc for the full
list of methods), and inside of those overridden methods forward the calls to the
inner AppCompatDelegate instance. AppCompatDelegate will do the rest and your "old-
fashion" activity will be "materialized".
So for API Level 22 (with a minimum support for API Level 15 or 16), what exactly should I
use both to host the components, and for the components themselves? Are there uses for all
of these, or should I be using one or two almost exclusively?
Activity is the baseline. Every activity inherits from Activity, directly or indirectly.
FragmentActivity is for use with the backport of fragments found in the support-
v4 and support-v13 libraries. The native implementation of fragments was added in API
Level 11, which is lower than your proposed minSdkVersion values. The only reason why
you would need to consider FragmentActivity specifically is if you want to use nested
fragments (a fragment holding another fragment), as that was not supported in native
fragments until API Level 17.
AppCompatActivity is from the appcompat-v7 library. Principally, this offers a backport of
the action bar. Since the native action bar was added in API Level 11, you do not
need AppCompatActivity for that. However, current versions of appcompat-v7 also add a
limited backport of the Material Design aesthetic, in terms of the action bar and various
widgets. There are pros and cons of using appcompat-v7, well beyond the scope of this
specific Stack Overflow answer.
ActionBarActivity is the old name of the base activity from appcompat-v7. For various
reasons, they wanted to change the name. Unless some third-party library you are using
insists upon an ActionBarActivity, you should
prefer AppCompatActivity over ActionBarActivity.
So, given your minSdkVersion in the 15-16 range:
 If you want the backported Material Design look, use AppCompatActivity
 If not, but you want nested fragments, use FragmentActivity
 If not, use Activity
Just adding from comment as note: AppCompatActivity extends FragmentActivity, so
anyone who needs to use features of FragmentActivity can use AppCompatActivity.

 Activity is the base class of all the other activities, including


AppCompatActivity. The Activity class serves as the entry point for an app’s
interaction with the user, providing the window in which the app draws its
UI. You implement an activity as a subclass of the Activity class. Generally,
one activity implements one screen in an app. Most apps contain multiple
screens, which means they comprise multiple activities. Typically, one
activity in an app is specified as the main activity, which is the first screen to
appear when the user launches the app. Each activity can then start another
activity in order to perform different actions. To use activities in your app,
you must register information about them in the app’s manifest, and you
must manage activity lifecycles appropriately. The activities libraries provide
you with the functionality of an activity.
 AppCompatActivity is a specific type of activity that allows you to use the
support library action bar features.
 Fragment represents a behavior or a portion of user interface in an Activity.
You can combine multiple fragments in a single activity to build a multi-
pane UI and reuse a fragment in multiple activities. You can think of a
fragment as a modular section of an activity, which has its own lifecycle,
receives its own input events, and which you can add or remove while the
activity is running (sort of like a "sub activity" that you can reuse in different
activities). A fragment must always be embedded in an activity and the
fragment's lifecycle is directly affected by the host activity's lifecycle. For
example, when the activity is paused, so are all fragments in it, and when
the activity is destroyed, so are all fragments. However, while an activity is
running, you can manipulate each fragment independently, such as add or
remove them. The fragments libraries provide you with the functionality of a
fragment.
Method Overriding
o Method overriding is used to provide specific implementation of a method that is
already provided by its super class.
o Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


1. method must have same name as in the parent class
2. method must have same parameter as in the parent class.
3. must be IS-A relationship (inheritance).

Understanding the problem without method overriding

Let's understand the problem that we may face in the program if we don't use method
overriding.

1. class Vehicle{
2. void run(){System.out.println("Vehicle is running");}
3. }
4. class Bike extends Vehicle{
5.
6. public static void main(String args[]){
7. Bike obj = new Bike();
8. obj.run();
9. }
10. }
Test it Now
Output:Vehicle is running

Problem is that I have to provide a specific implementation of run() method in subclass


that is why we use method overriding.

Example of method overriding

In this example, we have defined the run method in the subclass as defined in the parent
class but it has some specific implementation. The name and parameter of the method is
same and there is IS-A relationship between the classes, so there is method overriding.

1. class Vehicle{
2. void run(){System.out.println("Vehicle is running");}
3. }
4. class Bike2 extends Vehicle{
5. void run(){System.out.println("Bike is running safely");}
6.
7. public static void main(String args[]){
8. Bike2 obj = new Bike2();
9. obj.run();
10. }
Test it Now
Output:Bike is running safely

Real example of Java Method Overriding

Consider a scenario, Bank is a class that provides functionality to get rate of interest. But,
rate of interest varies according to banks. For example, SBI, ICICI and AXIS banks could
provide 8%, 7% and 9% rate of interest.
1. class Bank{
2. int getRateOfInterest(){return 0;}
3. }
4.
5. class SBI extends Bank{
6. int getRateOfInterest(){return 8;}
7. }
8.
9. class ICICI extends Bank{
10. int getRateOfInterest(){return 7;}
11. }
12. class AXIS extends Bank{
13. int getRateOfInterest(){return 9;}
14. }
15.
16. class Test2{
17. public static void main(String args[]){
18. SBI s=new SBI();
19. ICICI i=new ICICI();
20. AXIS a=new AXIS();
21. System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
22. System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
23. System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
24. }
25. }
Test it Now
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
Can we override static method?

No, static method cannot be overridden. It can be proved by runtime polymorphism, so


we will learn it later.
Why we cannot override static method?

because static method is bound with class whereas instance method is bound with object.
Static belongs to class area and instance belongs to heap area.

Can we override java main method?

No, because main is a static method.

Difference between method Overloading and Method Overriding in java

Click me for difference between method overloading and overriding

More topics on Method Overriding (Not For Beginners)


Method Overriding with Access Modifier

Let's see the concept of method overriding with access modifier.

Exception Handling with Method Overriding

Let's see the concept of method overriding with exception handling.

Covariant Return Type

The covariant return type specifies that the return type may vary in the same direction as
the subclass.

Before Java5, it was not possible to override any method by changing the return type. But
now, since Java5, it is possible to override method by changing the return type if subclass
overrides any method whose return type is Non-Primitive but it changes its return type to
subclass type. Let's take a simple example:

Note: If you are beginner to java, skip this topic and return to it after OOPs concepts.

Simple example of Covariant Return Type


1. class A{
2. A get(){return this;}
3. }
4.
5. class B1 extends A{
6. B1 get(){return this;}
7. void message(){System.out.println("welcome to covariant return type");}
8.
9. public static void main(String args[]){
10. new B1().get().message();
11. }
12. }
Test it Now
Output:welcome to covariant return type

As you can see in the above example, the return type of the get() method of A class is A
but the return type of the get() method of B class is B. Both methods have different return
type but it is method overriding. This is known as covariant return type.

Oncreate()
Called when the activity is first created. This is where you should do all of your normal static set
up: create views, bind data to lists, etc. This method also provides you with a Bundle containing
the activity's previously frozen state, if there was one.
Always followed by onStart().

Android Bundle

Android Bundle is used to pass data between activities. The values that are
to be passed are mapped to String keys which are later used in the next
activity to retrieve the values.
Following are the major types that are passed/retrieved to/from a Bundle.

 putInt(String key, int value), getInt(String key, int value)


 putIntArray(String key, int[] value), getStringArray(String
key, int[] value)
 putIntegerArrayList(String key, ArrayList
value), getIntegerArrayList(String key, ArrayList value value)
 putString(String key, String value), getString(String key,
String value)
 putStringArray(String key, String[]
value), getStringArray(String key, String[] value)
 putStringArrayList(String key, ArrayList
value), getStringArrayList(String key, ArrayList value value)
 putLong(String key, long value), getLong(String key, long
value)
 putLongArray(String key, long[] value), getLongArray(String
key, long[] value)
 putBoolean(String key, boolean value), getBoolean(String key,
boolean value)
 putBooleanArray(String key, boolean[]
value), getBooleanArray(String key, boolean[] value)
 putChar(String key, char value), getChar(String key, char
value)
 putCharArray(String key, char[] value), getBooleanArray(String
key, char[] value)
 putCharSequence(String key, CharSequence
value), getCharSequence(String key, CharSequence value)
 putCharSequenceArray(String key, CharSequence[]
value), getCharSequenceArray(String key, CharSequence[] value)
 putCharSequenceArrayList(String key, ArrayList
value), getCharSequenceArrayList(String key, ArrayList value
value)

Using Android Bundle

A Bundle is passed in the following way.

Intent intent = new Intent(this,SecondActivity.class);


Bundle bundle = new Bundle();
bundle.putString("key_1", "MainActivity greeted you with a
HI");
bundle.putBoolean("key_2", true);
intent.putExtras(bundle);
startActivity(intent);
Data from a Bundle is retrieved in the SecondActivity.java in the following
manner.
Bundle bundle = getIntent().getExtras();
String title = bundle.getString("key_1");
boolean b = bundle.getBoolean("key_2");

If the key doesn’t map to any value, it may lead to NullPointerException.


Hence it’s recommended to add null checks for the Bundle as well as the
retrieved values.
Alternatively, we can set a default value too in case the mapped key
doesn’t have any value.

Bundle bundle = getIntent().getExtras();


String title = bundle.getString("key_1", "Default");
boolean b = bundle.getBoolean("key_2", false);
To remove a value from the bundle the remove() method is passed with the
relevant key as shown below.
bundle.remove("key_2");
To remove all data from the Bundle, the method clear() is called on the
Bundle instance.
savedInstanceState
What is the savedInstanceState Bundle?

The savedInstanceState is a reference to a Bundle object that is passed


into the onCreate method of every Android Activity. Activities have the
ability, under special circumstances, to restore themselves to a previous
state using the data stored in this bundle. If there is no available instance
data, the savedInstanceState will be null. For example, the
savedInstanceState will always be null the first time an Activity is started,
but may be non-null if an Activity is destroyed during rotation.

When do I save things to the Bundle?

All activities have an onSaveInstanceState method that can be overridden.


When this method is called, any state-related data should be placed into
the outState Bundle. This method is called when an Activity is being
backgrounded (either after onPause() or onStop(), depending on different
factors).

What should be saved?

The savedInstanceState Bundle should only save information directly


related to the current Activity state. Examples of this include:

 User selections – A user selects a tab. In onSaveInstanceState the tab


selection gets added to the outState Bundle. During the next onCreate, the
selected tab will be available within the Bundle, and the Activity should
default to having that tab selected.
 Scroll view positions – A user scrolls half way through a ScrollView. The
current position of the ScrollView should be saved in onSaveInstanceState
then restored when the Activity is re-created.
 User-submitted data – If a user writes their username into a text box, they
would expect the username to still be present when the Activity is resumed.

What should not be saved?

In general (with few exceptions), the following kinds of data should never
be saved into the Bundle:

 Files
 Database data
 Images
 Videos
 Anything downloaded from the web (feed data)
 Models (the data kind, not the people kind)

Rather than attempting to save and recover this information from the
Bundle on rotation, the application should have caching and/or database
systems set up that are built to deal specifically with these kinds of
information.

When is the savedInstanceState useful?

There is one situation where using the savedInstanceState is almost


mandatory: when the Activity gets destroyed during rotation. One way that
Android handles rotation is to completely destroy and then re-create the
current Activity. When the Activity is being destroyed, any state related
information that is saved in onSaveInstanceState will be available when the
Activity comes back online.

Another situation is when your Activity gets backgrounded. When an


Activity is in a backgrounded state (either after onPause or onStop) it can
be destroyed at any time with no notice. In the event that the OS kills your
Activity without killing your Application, the OS will first save your outState
Bundle so you can later return to your previous state.

Super.onCreat
Every Activity you make is started through a sequence of method calls. onCreate() is the
first of these calls.
Each and every one of your Activities extends android.app.Activity either directly or by
subclassing another subclass of Activity.
In Java, when you inherit from a class, you can override its methods to run your own
code in them. A very common example of this is the overriding of the toString() method
when extending java.lang.Object.
When we override a method, we have the option of completely replacing the method in
our class, or of extending the existing parent class' method. By
calling super.onCreate(savedInstanceState);, you tell the Dalvik VM to run your code in
addition to the existing code in the onCreate() of the parent class. If you leave out this
line, then only your code is run. The existing code is ignored completely.
However, you must include this super call in your method, because if you don't then
the onCreate() code in Activity is never run, and your app will run into all sorts of
problem like having no Context assigned to the Activity (though you'll hit
a SuperNotCalledException before you have a chance to figure out that you have no
context).
In short, Android's own classes can be incredibly complex. The code in the framework
classes handles stuff like UI drawing, house cleaning and maintaining the Activity and
application lifecycles. super calls allow developers to run this complex code behind the
scenes, while still providing a good level of abstraction for our own apps.

Every Activity you make is started through a sequence of method


calls. onCreate() is the first of these calls.
Each and every one of your Activities extends android.app.Activity either directly
or by subclassing another subclass of Activity.
In Java, when you inherit from a class, you can override its methods to run your own
code in them. A very common example of this is the overriding of
the toString() method when extending java.lang.Object.
When we override a method, we have the option of completely replacing the method
in our class, or of extending the existing parent class' method. By
calling super.onCreate(savedInstanceState);, you tell the Dalvik VM to run
your code in addition to the existing code in the onCreate() of the parent class. If
you leave out this line, then only your code is run. The existing code is ignored
completely.
However, you must include this super call in your method, because if you don't then
the onCreate() code in Activity is never run, and your app will run into all sorts of
problem like having no Context assigned to the Activity (though you'll hit
a SuperNotCalledException before you have a chance to figure out that you have
no context).
In short, Android's own classes can be incredibly complex. The code in the framework
classes handles stuff like UI drawing, house cleaning and maintaining the Activity and
application lifecycles. super calls allow developers to run this complex code behind
the scenes, while still providing a good level of abstraction for our own apps.

setContentView()
setContentView() is a very important function when it comes to programming with
Android.
One has to understand its use completely to work with Android UserInterface.
Basically what this function does is display the Layout created thorugh XML or the
Dynamically created layout view in the Screen.

public DatabaseReference getReference ()

Gets a DatabaseReference for the database root node.

Returns

 A DatabaseReference pointing to the root node.

public DatabaseReference getReference (String path)

Gets a DatabaseReference for the provided path.


Parameters

Path to a location in your FirebaseDatabase.


path

Returns

 A DatabaseReference pointing to the specified path.

getInstance

public static FirebaseDatabase getInstance (String url)

Also: Google Play services

Gets a FirebaseDatabase instance for the specified URL.

Parameters

The URL to the Firebase Database instance you want to access.


url

Returns

 A FirebaseDatabase instance.

public static FirebaseDatabase getInstance ()

Also: Google Play services

Gets the default FirebaseDatabase instance.

Returns

 A FirebaseDatabase instance.
DatabaseReference
A Firebase reference represents a particular location in your Database and can be
used for reading or writing data to that Database location.

This class is the starting point for all Database operations. After you've initialized it
with a URL, you can use it to read data, write data, and to create new
DatabaseReferences.

A Reference represents a specific location in your Database and can be used


for reading or writing data to that Database location.
You can reference the root or child location in your Database by
calling firebase.database().ref() or firebase.database().ref("child/path
").

FirebaseDatabase
The entry point for accessing a Firebase Database. You can get an instance by
calling getInstance(). To access a location in the database and read or write data,
use getReference().
getInstance

Gets the default FirebaseDatabase instance.

Returns

 A FirebaseDatabase instance.

getReference

Gets a DatabaseReference for the database root node.

Returns

 A DatabaseReference pointing to the root node.

View
This class represents the basic building block for user interface components. A View
occupies a rectangular area on the screen and is responsible for drawing and event
handling. View is the base class for widgets, which are used to create interactive UI
components (buttons, text fields, etc.). The ViewGroup subclass is the base class
for layouts, which are invisible containers that hold other Views (or other
ViewGroups) and define their layout properties.

Developer Guides
For information about using this class to develop your application's user interface, read the User
Interface developer guide.

Using Views
All of the views in a window are arranged in a single tree. You can add views either
from code or by specifying a tree of views in one or more XML layout files. There are
many specialized subclasses of views that act as controls or are capable of
displaying text, images, or other content.

Once you have created a tree of views, there are typically a few types of common
operations you may wish to perform:

 Set properties: for example setting the text of a TextView. The available properties and
the methods that set them will vary among the different subclasses of views. Note that
properties that are known at build time can be set in the XML layout files.
 Set focus: The framework will handle moving focus in response to user input. To force focus
to a specific view, call requestFocus().

 Set up listeners: Views allow clients to set listeners that will be notified when something
interesting happens to the view. For example, all views will let you set a listener to be
notified when the view gains or loses focus. You can register such a listener
using setOnFocusChangeListener(android.view.View.OnFocusChangeListene
r). Other view subclasses offer more specialized listeners. For example, a Button exposes
a listener to notify clients when the button is clicked.
 Set visibility: You can hide or show views using setVisibility(int).

Note: The Android framework is responsible for measuring, laying out and drawing
views. You should not call methods that perform these actions on views yourself
unless you are actually implementing a ViewGroup.

link

https://developer.android.com/reference/android/view/View

child
 child(path: string): Reference

 Gets a Reference for the location at the specified relative path.


The relative path can either be a simple child name (for example, "ada") or a deeper slash-
separated path (for example, "ada/name/first").

Example
var usersRef = firebase.database().ref('users');
var adaRef = usersRef.child('ada');
var adaFirstNameRef = adaRef.child('name/first');
var path = adaFirstNameRef.toString();
// path is now 'https://sample-
app.firebaseio.com/users/ada/name/first'

Parameters

 path: string

A relative path from this location to the desired child location.

Returns Reference

The specified child location.

setValue

public
void setValue (Object value, Object priority, DatabaseReference.CompletionListener li
stener)

Also: Google Play services

Set the data and priority to the given values. The native types accepted by this
method for the value correspond to the JSON types:

 Boolean
 Long
 Double
 String
 Map<String, Object>
 List<Object>

In addition, you can set instances of your own class into this location, provided they satisfy
the following constraints:
1. The class must have a default constructor that takes no arguments
2. The class must define public getters for the properties to be assigned. Properties without a
public getter will be set to their default value when an instance is deserialized

Generic collections of objects that satisfy the above constraints are also permitted,
i.e. Map<String, MyPOJO>, as well as null values.

Parameters

The value to set at this location or null to delete the existing data
value

The priority to set at this location or null to clear the existing priority
priority

A listener that will be triggered with the results of the operation


listener

public void setValue (Object value, DatabaseReference.CompletionListener listener)

Also: Google Play services

Set the data at this location to the given value. Passing null to setValue() will delete
the data at the specified location. The native types accepted by this method for the
value correspond to the JSON types:

 Boolean
 Long
 Double
 String
 Map<String, Object>
 List<Object>

In addition, you can set instances of your own class into this location, provided they satisfy
the following constraints:

1. The class must have a default constructor that takes no arguments


2. The class must define public getters for the properties to be assigned. Properties without a
public getter will be set to their default value when an instance is deserialized
Generic collections of objects that satisfy the above constraints are also permitted,
i.e. Map<String, MyPOJO>, as well as null values.

Parameters

The value to set at this location or null to delete the existing data
value

A listener that will be triggered with the results of the operation


listener

public Task<Void> setValue (Object value, Object priority)

Also: Google Play services

Set the data and priority to the given values. Passing null to setValue() will delete the
data at the specified location. The native types accepted by this method for the value
correspond to the JSON types:

 Boolean
 Long
 Double
 String
 Map<String, Object>
 List<Object>

In addition, you can set instances of your own class into this location, provided they satisfy
the following constraints:

1. The class must have a default constructor that takes no arguments


2. The class must define public getters for the properties to be assigned. Properties without a
public getter will be set to their default value when an instance is deserialized

Generic collections of objects that satisfy the above constraints are also permitted,
i.e. Map<String, MyPOJO>, as well as null values.

Parameters
The value to set at this location or null to delete the existing data
value

The priority to set at this location or null to clear the existing priority
priority

Returns

 The Task for this operation.

ref.child.setValue
Basic write operations
For basic write operations, you can use setValue() to save data to a specified
reference, replacing any existing data at that path. You can use this method to:

 Pass types that correspond to the available JSON types as follows:


 String

 Long

 Double

 Boolean

 Map<String, Object>

 List<Object>

 Pass a custom Java object, if the class that defines it has a default constructor that takes no
arguments and has public getters for the properties to be assigned.

If you use a Java object, the contents of your object are automatically mapped to
child locations in a nested fashion. Using a Java object also typically makes your
code more readable and easier to maintain. For example, if you have an app with a
basic user profile, your User object might look as follows:

JavaKotlin

@IgnoreExtraProperties
public class User {

public String username;


public String email;

public User() {
// Default constructor required for calls to
DataSnapshot.getValue(User.class)
}

public User(String username, String email) {


this.username = username;
this.email = email;
}

}
User.java

You can add a user with setValue() as follows:

JavaKotlin

private void writeNewUser(String userId, String name, String email) {


User user = new User(name, email);

mDatabase.child("users").child(userId).setValue(user);
}
SignInActivity.java

Using setValue() in this way overwrites data at the specified location, including any
child nodes. However, you can still update a child without rewriting the entire object.
If you want to allow users to update their profiles you could update the username as
follows:

JavaKotlin

mDatabase.child("users").child(userId).child("username").setValue(name)
;

Get getter
Set setter
Dif --You learned from the previous chapter that private variables can only
be accessed within the same class (an outside class has no access to it).
However, it is possible to access them if we provide
public getter and setter methods

Ex 1
public class Person {
private String name; // private = restricted access

// Getter
public String getName() {
return name;
}

// Setter
public void setName(String newName) {
this.name = newName;
}
}
ex2
public class MyClass {
public static void main(String[] args) {
Person myObj = new Person();
myObj.setName("John"); // Set the value of the name variable to "John"
System.out.println(myObj.getName());
}
}

// Outputs "John"
link

https://www.youtube.com/watch?v=161zjFEbRYg

addValueEventListener
In Java and Node.js, the callback function receives a DataSnapshot, which is a
snapshot of the data. A snapshot is a picture of the data at a particular database
reference at a single point in time. Calling val() / getValue() on a snapshot
returns the a language-specific object representation of the data. If no data exists at
the reference's location, the snapshot's value is null. The get() method in Python
returns a Python representation of the data directly. The Get() function in Go
unmarshals the data into a given data structure.

Notice that we used the value event type in the example above, which reads the
entire contents of a Firebase database reference, even if only one piece of data
changed. value is one of the five different event types listed below that you can use
to read data from the database.

Ex 1 get custom list view from database


databaseTracks.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
tracks.clear();
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Track track = postSnapshot.getValue(Track.class);
tracks.add(track);
}
TrackList trackListAdapter = new TrackList(ArtistActivity.this, tracks);
listViewTracks.setAdapter(trackListAdapter);
}

@Override
public void onCancelled(DatabaseError databaseError) {

}
});

onDataChange
This method will be called with a snapshot of the data at this location. It will also be
called each time that data changes.

Parameters

The current data at the location


snapshot

DataSnapshot
A DataSnapshot instance contains data from a Firebase Database location. Any time you
read Database data, you receive the data as a DataSnapshot.

DataSnapshots are passed to the methods in listeners that you attach


with addValueEventListener(ValueEventListener), addChildEventListener(C
hildEventListener),
or addListenerForSingleValueEvent(ValueEventListener).

They are efficiently-generated immutable copies of the data at a Firebase Database location.
They can't be modified and will never change. To modify data at a location, use
a DatabaseReference reference (e.g. with setValue(Object)).

onCancelled(DatabaseError databaseError)

This method will be triggered in the event that this listener either failed at the server,
or is removed as a result of the security and Firebase Database rules. For more
information on securing your data, see: Security Quickstart

Parameters

A description of the error that occurred


error
dataSnapshot.getChildren()
Gives access to all of the immediate children of this snapshot. Can be used in native
for loops:
for (DataSnapshot child : parent.getChildren()) {
...
}

Returns

 The immediate children of this snapshot


 https://www.youtube.com/watch?v=jEmq1B1gveM&t=1s

addListenerForSingleValueEvent
ex 1

demof.child("value").addListenerForSingleValueEvent(new
ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String value = dataSnapshot.getValue(String.class);
tv.setText(value);
}

@Override
public void onCancelled(DatabaseError databaseError) {
}
});

https://www.youtube.com/watch?v=lpFDFK44pX8

Intent
An Intent is a simple message object that is used to communicate
between android components such as activities, content providers, broadcast
receivers and services. Intents are also used to transfer data between activities.
https://www.youtube.com/watch?v=FH1Ym1KjJNc

Java return Keyword


Java return keyword is used to complete the execution of a method. The return followed
by the appropriate value that is returned to the caller. This value depends on the method
return type like int method always return an integer value.

Points to remember
o It is used to exit from the method.
o It is not allowed to use return keyword in void method.
o The value passed with return keyword must match with return type of the
method.

Examples of Java return Keyword


Example 1
Let's see a simple example to return integer value.

1. public class ReturnExample1 {


2.
3. int display()
4. {
5. return 10;
6. }
7. public static void main(String[] args) {
8. ReturnExample1 e =new ReturnExample1();
9. System.out.println(e.display());
10. }
11.
12. }

Output:

10
Example 2
Let's see an example to determine whether we can use return in void method.

1. public class ReturnExample2 {


2. void display()
3. {
4. return null;
5. }
6. public static void main(String[] args) {
7. ReturnExample2 e =new ReturnExample2();
8. e.display();
9. }
10. }

Output:

Void methods cannot return a value


Example 3
Let's see an example to return string.

1. public class ReturnExample3 {


2.
3. String display()
4. {
5. return "Javatpoint";
6. }
7. public static void main(String[] args) {
8. ReturnExample3 e =new ReturnExample3();
9. System.out.println(e.display());
10. }
11.
12. }
13. </pre></div>
14. <p><strong>Output:</strong></p>
15. <div class="codeblock3"><pre>
16. Javatpoint
17. </pre></div>
18. <h2 class="h3">Example 4</h2>
19. <p>Let's see an example to return list of elements.</p>
20. <div class="codeblock"><textarea name="code" class="java">
21. import java.util.*;
22.
23. public class ReturnExample4 {
24.
25. List display()
26. {
27. List list=new ArrayList();
28. list.add("Java");
29. list.add("C++");
30. list.add("Python");
31. return list;
32. }
33. public static void main(String[] args) {
34. ReturnExample4 e =new ReturnExample4();
35. System.out.println(e.display());
36. }
37.
38. }

Output:

[Java, C++, Python]

next →← prev

Java ArrayList class

Java ArrayList class uses a dynamic array for storing the elements. It inherits AbstractList class and

The important points about Java ArrayList class are:

o Java ArrayList class can contain duplicate elements.


o Java ArrayList class maintains insertion order.
o Java ArrayList class is non synchronized.
o Java ArrayList allows random access because array works at the index basis.
o In Java ArrayList class, manipulation is slow because a lot of shifting needs to occur if any ele
array list.
Hierarchy of ArrayList class

As shown in the above diagram, Java ArrayList class extends AbstractList class which implements Lis
interface extends Collection and Iterable interfaces in hierarchical order.

ArrayList class declaration

Let's see the declaration for java.util.ArrayList class.

1. public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneab


Constructors of Java ArrayList
Constructor Description

ArrayList() It is used to build an empty array list.

ArrayList(Collection<? extends E> It is used to build an array list that is initialized with th
c) collection c.

ArrayList(int capacity) It is used to build an array list that has the specified in

Methods of Java ArrayList


Method Description

void add(int index, E element) It is used to insert the specified element at the sp

boolean add(E e) It is used to append the specified element at the

boolean addAll(Collection<? extends E> It is used to append all of the elements in the spe
c) of this list, in the order that they are returned by
iterator.

boolean addAll(int index, Collection<? It is used to append all the elements in the specif
extends E> c) the specified position of the list.

void clear() It is used to remove all of the elements from this


void ensureCapacity(int It is used to enhance the capacity of an ArrayList
requiredCapacity)

E get(int index) It is used to fetch the element from the particular

boolean isEmpty() It returns true if the list is empty, otherwise false

int lastIndexOf(Object o) It is used to return the index in this list of the las
specified element, or -1 if the list does not contai

Object[] toArray() It is used to return an array containing all of the e


correct order.

<T> T[] toArray(T[] a) It is used to return an array containing all of the e


correct order.

Object clone() It is used to return a shallow copy of an ArrayList

boolean contains(Object o) It returns true if the list contains the specified ele

int indexOf(Object o) It is used to return the index in this list of the firs
specified element, or -1 if the List does not conta

E remove(int index) It is used to remove the element present at the s

boolean remove(Object o) It is used to remove the first occurrence of the sp

boolean removeAll(Collection<?> c) It is used to remove all the elements from the list

boolean removeIf(Predicate<? super E> It is used to remove all the elements from the list
filter) predicate.

protected void removeRange(int It is used to remove all the elements lies within th
fromIndex, int toIndex)
void replaceAll(UnaryOperator<E> It is used to replace all the elements from the list
operator) element.

void retainAll(Collection<?> c) It is used to retain all the elements in the list that
specified collection.

E set(int index, E element) It is used to replace the specified element in the l


position.

void sort(Comparator<? super E> c) It is used to sort the elements of the list on the b
comparator.

Spliterator<E> spliterator() It is used to create spliterator over the elements

List<E> subList(int fromIndex, int It is used to fetch all the elements lies within the
toIndex)

int size() It is used to return the number of elements prese

void trimToSize() It is used to trim the capacity of this ArrayList ins


current size.

Java Non-generic Vs. Generic Collection


Java collection framework was non-generic before JDK 1.5. Since 1.5, it is generic.

Java new generic collection allows you to have only one type of object in a collection. Now it is type
required at runtime.

Let's see the old non-generic example of creating java collection.

1. ArrayList al=new ArrayList();//creating old non-generic arraylist

Let's see the new generic example of creating java collection.

1. ArrayList<String> al=new ArrayList<String>();//creating new generic arraylist


In a generic collection, we specify the type in angular braces. Now ArrayList is forced to have the on
in it. If you try to add another type of object, it gives compile time error.

For more information on Java generics, click here Java Generics Tutorial.

Java ArrayList Example


1. import java.util.*;
2. class ArrayList1{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();//Creating arraylist
5. list.add("Ravi");//Adding object in arraylist
6. list.add("Vijay");
7. list.add("Ravi");
8. list.add("Ajay");
9. //Invoking arraylist object
10. System.out.println(list);
11. }
12. }
13. }
[Ravi, Vijay, Ravi, Ajay]
Ways to iterate the elements of the collection in java

There are various ways to traverse the collection elements:

1. By Iterator interface.
2. By for-each loop.
3. By ListIterator interface.
4. By for loop.
5. By forEach() method.
6. By forEachRemaining() method.

Iterating Collection through Iterator interface

Let's see an example to traverse ArrayList elements using the Iterator interface.

1. import java.util.*;
2. class ArrayList2{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();//Creating arraylist
5. list.add("Ravi");//Adding object in arraylist
6. list.add("Vijay");
7. list.add("Ravi");
8. list.add("Ajay");
9. //Traversing list through Iterator
10. Iterator itr=list.iterator();
11. while(itr.hasNext()){
12. System.out.println(itr.next());
13. }
14. }
15. }
Test it Now

Ravi
Vijay
Ravi
Ajay
Iterating Collection through the for-each loop

Let's see an example to traverse the ArrayList elements using the for-each loop

1. import java.util.*;
2. class ArrayList3{
3. public static void main(String args[]){
4. ArrayList<String> al=new ArrayList<String>();
5. al.add("Ravi");
6. al.add("Vijay");
7. al.add("Ravi");
8. al.add("Ajay");
9. //Traversing list through for-each loop
10. for(String obj:al)
11. System.out.println(obj);
12. }
13. }
Ravi
Vijay
Ravi
Ajay

Iterating Collection through remaining ways

Let's see an example to traverse the ArrayList elements through other ways
1. import java.util.*;
2. class ArrayList4{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();//Creating arraylist
5. list.add("Ravi");//Adding object in arraylist
6. list.add("Vijay");
7. list.add("Ravi");
8. list.add("Ajay");
9.
10. System.out.println("Traversing list through List Iterator:");
11. //Here, element iterates in reverse order
12. ListIterator<String> list1=list.listIterator(list.size());
13. while(list1.hasPrevious())
14. {
15. String str=list1.previous();
16. System.out.println(str);
17. }
18. System.out.println("Traversing list through for loop:");
19. for(int i=0;i<list.size();i++)
20. {
21. System.out.println(list.get(i));
22. }
23.
24. System.out.println("Traversing list through forEach() method:");
25. //The forEach() method is a new feature, introduced in Java 8.
26. list.forEach(a->{ //Here, we are using lambda expression
27. System.out.println(a);
28. });
29.
30. System.out.println("Traversing list through forEachRemaining() method:");
31. Iterator<String> itr=list.iterator();
32. itr.forEachRemaining(a-> //Here, we are using lambda expression
33. {
34. System.out.println(a);
35. });
36. }
37. }
Traversing list through List Iterator:
Ajay
Ravi
Vijay
Ravi
Traversing list through for loop:
Ravi
Vijay
Ravi
Ajay
Traversing list through forEach() method:
Ravi
Vijay
Ravi
Ajay
Traversing list through forEachRemaining() method:
Ravi
Vijay
Ravi
Ajay

User-defined class objects in Java ArrayList

Let's see an example where we are storing Student class object in an array list.

1. class Student{
2. int rollno;
3. String name;
4. int age;
5. Student(int rollno,String name,int age){
6. this.rollno=rollno;
7. this.name=name;
8. this.age=age;
9. }
10. }
1. import java.util.*;
2. class ArrayList5{
3. public static void main(String args[]){
4. //Creating user-defined class objects
5. Student s1=new Student(101,"Sonoo",23);
6. Student s2=new Student(102,"Ravi",21);
7. Student s2=new Student(103,"Hanumat",25);
8. //creating arraylist
9. ArrayList<Student> al=new ArrayList<Student>();
10. al.add(s1);//adding Student class object
11. al.add(s2);
12. al.add(s3);
13. //Getting Iterator
14. Iterator itr=al.iterator();
15. //traversing elements of ArrayList object
16. while(itr.hasNext()){
17. Student st=(Student)itr.next();
18. System.out.println(st.rollno+" "+st.name+" "+st.age);
19. }
20. }
21. }
101 Sonoo 23
102 Ravi 21
103 Hanumat 25

Java ArrayList Serialization and Deserialization Example

Let's see an example to serialize an ArrayList object and then deserialize it.

1. import java.io.*;
2. import java.util.*;
3. class ArrayList6 {
4.
5. public static void main(String [] args)
6. {
7. ArrayList<String> al=new ArrayList<String>();
8. al.add("Ravi");
9. al.add("Vijay");
10. al.add("Ajay");
11.
12. try
13. {
14. //Serialization
15. FileOutputStream fos=new FileOutputStream("file");
16. ObjectOutputStream oos=new ObjectOutputStream(fos);
17. oos.writeObject(al);
18. fos.close();
19. oos.close();
20. //Deserialization
21. FileInputStream fis=new FileInputStream("file");
22. ObjectInputStream ois=new ObjectInputStream(fis);
23. ArrayList list=(ArrayList)ois.readObject();
24. System.out.println(list);
25. }catch(Exception e)
26. {
27. System.out.println(e);
28. }
29. }
30. }
[Ravi, Vijay, Ajay]

Java ArrayList example to add elements

Here, we see different ways to add an element.

1. import java.util.*;
2. class ArrayList7{
3. public static void main(String args[]){
4. ArrayList<String> al=new ArrayList<String>();
5. System.out.println("Initial list of elements: "+al);
6. //Adding elements to the end of the list
7. al.add("Ravi");
8. al.add("Vijay");
9. al.add("Ajay");
10. System.out.println("After invoking add(E e) method: "+al);
11. //Adding an element at the specific position
12. al.add(1, "Gaurav");
13. System.out.println("After invoking add(int index, E element) method: "+al);
14. ArrayList<String> al2=new ArrayList<String>();
15. al2.add("Sonoo");
16. al2.add("Hanumat");
17. //Adding second list elements to the first list
18. al.addAll(al2);
19. System.out.println("After invoking addAll(Collection<? extends E> c) method: "+al);
20. ArrayList<String> al3=new ArrayList<String>();
21. al3.add("John");
22. al3.add("Rahul");
23. //Adding second list elements to the first list at specific position
24. al.addAll(1, al3);
25. System.out.println("After invoking addAll(int index, Collection<? extends E> c) method: "+a
26.
27. }
28. }
Initial list of elements: []
After invoking add(E e) method: [Ravi, Vijay, Ajay]
After invoking add(int index, E element) method: [Ravi, Gaurav, Vijay, Ajay]
After invoking addAll(Collection<? extends E> c) method:
[Ravi, Gaurav, Vijay, Ajay, Sonoo, Hanumat]
After invoking addAll(int index, Collection<? extends E> c) method:
[Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat]

Java ArrayList example to remove elements

Here, we see different ways to remove an element.

1. import java.util.*;
2. class ArrayList8 {
3.
4. public static void main(String [] args)
5. {
6. ArrayList<String> al=new ArrayList<String>();
7. al.add("Ravi");
8. al.add("Vijay");
9. al.add("Ajay");
10. al.add("Anuj");
11. al.add("Gaurav");
12. System.out.println("An initial list of elements: "+al);
13. //Removing specific element from arraylist
14. al.remove("Vijay");
15. System.out.println("After invoking remove(object) method: "+al);
16. //Removing element on the basis of specific position
17. al.remove(0);
18. System.out.println("After invoking remove(index) method: "+al);
19.
20. //Creating another arraylist
21. ArrayList<String> al2=new ArrayList<String>();
22. al2.add("Ravi");
23. al2.add("Hanumat");
24. //Adding new elements to arraylist
25. al.addAll(al2);
26. System.out.println("Updated list : "+al);
27. //Removing all the new elements from arraylist
28. al.removeAll(al2);
29. System.out.println("After invoking removeAll() method: "+al);
30. //Removing elements on the basis of specified condition
31. al.removeIf(str -> str.contains("Ajay")); //Here, we are using Lambda expression
32. System.out.println("After invoking removeIf() method: "+al);
33. //Removing all the elements available in the list
34. al.clear();
35. System.out.println("After invoking clear() method: "+al);
36. }
37. }
An initial list of elements: [Ravi, Vijay, Ajay, Anuj, Gaurav]
After invoking remove(object) method: [Ravi, Ajay, Anuj, Gaurav]
After invoking remove(index) method: [Ajay, Anuj, Gaurav]
Updated list : [Ajay, Anuj, Gaurav, Ravi, Hanumat]
After invoking removeAll() method: [Ajay, Anuj, Gaurav]
After invoking removeIf() method: [Anuj, Gaurav]
After invoking clear() method: []

Java ArrayList example of retainAll() method


1. import java.util.*;
2. class ArrayList9{
3. public static void main(String args[]){
4. ArrayList<String> al=new ArrayList<String>();
5. al.add("Ravi");
6. al.add("Vijay");
7. al.add("Ajay");
8. ArrayList<String> al2=new ArrayList<String>();
9. al2.add("Ravi");
10. al2.add("Hanumat");
11. al.retainAll(al2);
12. System.out.println("iterating the elements after retaining the elements of al2");
13. Iterator itr=al.iterator();
14. while(itr.hasNext()){
15. System.out.println(itr.next());
16. }
17. }
18. }
iterating the elements after retaining the elements of al2
Ravi
Java ArrayList example of isEmpty() method
1. import java.util.*;
2. class ArrayList10{
3.
4. public static void main(String [] args)
5. {
6. ArrayList<String> al=new ArrayList<String>();
7. System.out.println("Is ArrayList Empty: "+al.isEmpty());
8. al.add("Ravi");
9. al.add("Vijay");
10. al.add("Ajay");
11. System.out.println("After Insertion");
12. System.out.println("Is ArrayList Empty: "+al.isEmpty());
13. }
14. }
Is ArrayList Empty: true
After Insertion
Is ArrayList Empty: false

Java ArrayList example of set() and get() method


1. import java.util.*;
2. class ArrayList11 {
3.
4. public static void main(String [] args)
5. {
6. ArrayList<String> al=new ArrayList<String>();
7. al.add("Ravi");
8. al.add("Vijay");
9. al.add("Ajay");
10. System.out.println("Before update: "+al.get(1));
11. //Updating an element at specific position
12. al.set(1,"Gaurav");
13. System.out.println("After update: "+al.get(1));
14. }
15. }
Before update: Vijay
After update: Gaurav

Java ArrayList Example: Book

Let's see an ArrayList example where we are adding books to list and printing all the books.

1. import java.util.*;
2. class Book {
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. this.id = id;
8. this.name = name;
9. this.author = author;
10. this.publisher = publisher;
11. this.quantity = quantity;
12. }
13. }
14. public class ArrayListExample {
15. public static void main(String[] args) {
16. //Creating list of Books
17. List<Book> list=new ArrayList<Book>();
18. //Creating Books
19. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
20. Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);
21. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
22. //Adding Books to list
23. list.add(b1);
24. list.add(b2);
25. list.add(b3);
26. //Traversing list
27. for(Book b:list){
28. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
29. }
30. }
31. }
Test it Now

Output:

101 Let us C Yashwant Kanetkar BPB 8


102 Data Communications & Networking Forouzan Mc Graw Hill 4
103 Operating System Galvin Wiley 6

Arrayadpter
You can use this adapter to provide views for an AdapterView, Returns a view for each object in a
you provide, and can be used with list-based user interface widgets such as ListView or Spinner

By default, the array adapter creates a view by calling Object#toString() on each data object in
and places the result in a TextView. You may also customize what type of view is used for the data
customize what type of view is used for the data object, override getView(int, android.view.V
android.view.ViewGroup) and inflate a view resource. For a code example, see the CustomCho

For an example of using an array adapter with a ListView, see the Adapter Views guide.

For an example of using an array adapter with a Spinner, see the Spinners guide.
Java StringBuilder class
Java StringBuilder class is used to create mutable (modifiable) string. The Java StringBuilder class is sa
except that it is non-synchronized. It is available since JDK 1.5.

Important Constructors of StringBuilder class


Constructor Description

StringBuilder() creates an empty string Builder with the initial capacity of 16.

StringBuilder(String str) creates a string Builder with the specified string.

StringBuilder(int length) creates an empty string Builder with the specified capacity as l

Important methods of StringBuilder class


Method Description

public StringBuilder append(String is used to append the specified string with this string. The
s) overloaded like append(char), append(boolean), append(in
append(double) etc.

public StringBuilder insert(int is used to insert the specified string with this string at the
offset, String s) insert() method is overloaded like insert(int, char), insert(i
int), insert(int, float), insert(int, double) etc.

public StringBuilder replace(int is used to replace the string from specified startIndex and
startIndex, int endIndex, String
str)

public StringBuilder delete(int is used to delete the string from specified startIndex and e
startIndex, int endIndex)

public StringBuilder reverse() is used to reverse the string.

public int capacity() is used to return the current capacity.


public void ensureCapacity(int is used to ensure the capacity at least equal to the given m
minimumCapacity)

public char charAt(int index) is used to return the character at the specified position.

public int length() is used to return the length of the string i.e. total number

public String substring(int is used to return the substring from the specified beginInd
beginIndex)

public String substring(int is used to return the substring from the specified beginInd
beginIndex, int endIndex)

Java StringBuilder Examples


Let's see the examples of different methods of StringBuilder class.

1) StringBuilder append() method


The StringBuilder append() method concatenates the given argument with this string.

1. class StringBuilderExample{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello ");
4. sb.append("Java");//now original string is changed
5. System.out.println(sb);//prints Hello Java
6. }
7. }
2) StringBuilder insert() method
The StringBuilder insert() method inserts the given string with this string at the given position.

1. class StringBuilderExample2{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello ");
4. sb.insert(1,"Java");//now original string is changed
5. System.out.println(sb);//prints HJavaello
6. }
7. }
3) StringBuilder replace() method
The StringBuilder replace() method replaces the given string from the specified beginIndex and endInde

1. class StringBuilderExample3{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello");
4. sb.replace(1,3,"Java");
5. System.out.println(sb);//prints HJavalo
6. }
7. }
4) StringBuilder delete() method
The delete() method of StringBuilder class deletes the string from the specified beginIndex to endIndex

1. class StringBuilderExample4{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello");
4. sb.delete(1,3);
5. System.out.println(sb);//prints Hlo
6. }
7. }
5) StringBuilder reverse() method
The reverse() method of StringBuilder class reverses the current string.

1. class StringBuilderExample5{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello");
4. sb.reverse();
5. System.out.println(sb);//prints olleH
6. }
7. }
6) StringBuilder capacity() method
The capacity() method of StringBuilder class returns the current capacity of the Builder. The default cap
the number of character increases from its current capacity, it increases the capacity by (oldcapacity*2
current capacity is 16, it will be (16*2)+2=34.

1. class StringBuilderExample6{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder();
4. System.out.println(sb.capacity());//default 16
5. sb.append("Hello");
6. System.out.println(sb.capacity());//now 16
7. sb.append("java is my favourite language");
8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
9. }
10. }
7) StringBuilder ensureCapacity() method
The ensureCapacity() method of StringBuilder class ensures that the given capacity is the minimum to t
greater than the current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your cu
be (16*2)+2=34.

1. class StringBuilderExample7{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder();
4. System.out.println(sb.capacity());//default 16
5. sb.append("Hello");
6. System.out.println(sb.capacity());//now 16
7. sb.append("java is my favourite language");
8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
9. sb.ensureCapacity(10);//now no change
10. System.out.println(sb.capacity());//now 34
11. sb.ensureCapacity(50);//now (34*2)+2
12. System.out.println(sb.capacity());//now 70
13. }
14. }

Java String valueOf()


The java string valueOf() method converts different types of values into string. By the help of string
convert int to string, long to string, boolean to string, character to string, float to string, double to strin
array to string.

Internal implementation
1. public static String valueOf(Object obj) {
2. return (obj == null) ? "null" : obj.toString();
3. }

Signature
The signature or syntax of string valueOf() method is given below:

1. public static String valueOf(boolean b)


2. public static String valueOf(char c)
3. public static String valueOf(char[] c)
4. public static String valueOf(int i)
5. public static String valueOf(long l)
6. public static String valueOf(float f)
7. public static String valueOf(double d)
8. public static String valueOf(Object o)

Returns
string representation of given value

Java String valueOf() method example


1. public class StringValueOfExample{
2. public static void main(String args[]){
3. int value=30;
4. String s1=String.valueOf(value);
5. System.out.println(s1+10);//concatenating string with 10
6. }}
Test it Now

Output:

3010

Java String valueOf(boolean bol) Method Example


This is a boolean version of overloaded valueOf() method. It takes boolean value and returns a string. L

1. public class StringValueOfExample2 {


2. public static void main(String[] args) {
3. // Boolean to String
4. boolean bol = true;
5. boolean bol2 = false;
6. String s1 = String.valueOf(bol);
7. String s2 = String.valueOf(bol2);
8. System.out.println(s1);
9. System.out.println(s2);
10. }
11. }
Test it Now

Output:

true
false
Java String valueOf(char ch) Method Example
This is a char version of overloaded valueOf() method. It takes char value and returns a string. Let's se

1. public class StringValueOfExample3 {


2. public static void main(String[] args) {
3. // char to String
4. char ch1 = 'A';
5. char ch2 = 'B';
6. String s1 = String.valueOf(ch1);
7. String s2 = String.valueOf(ch2);
8. System.out.println(s1);
9. System.out.println(s2);
10. }
11. }
Test it Now

Output:

A
B

Java String valueOf(float f) and valueOf(double d)


This is a float version of overloaded valueOf() method. It takes float value and returns a string. Let's se

1. public class StringValueOfExample4 {


2. public static void main(String[] args) {
3. // Float and Double to String
4. float f = 10.05f;
5. double d = 10.02;
6. String s1 = String.valueOf(f);
7. String s2 = String.valueOf(d);
8. System.out.println(s1);
9. System.out.println(s2);
10. }
11. }
Test it Now

Output:

10.05
10.02
Java String valueOf() Complete Examples
Let's see an example where we are converting all primitives and objects into strings.

1. public class StringValueOfExample5 {


2. public static void main(String[] args) {
3. boolean b1=true;
4. byte b2=11;
5. short sh = 12;
6. int i = 13;
7. long l = 14L;
8. float f = 15.5f;
9. double d = 16.5d;
10. char chr[]={'j','a','v','a'};
11. StringValueOfExample5 obj=new StringValueOfExample5();
12. String s1 = String.valueOf(b1);
13. String s2 = String.valueOf(b2);
14. String s3 = String.valueOf(sh);
15. String s4 = String.valueOf(i);
16. String s5 = String.valueOf(l);
17. String s6 = String.valueOf(f);
18. String s7 = String.valueOf(d);
19. String s8 = String.valueOf(chr);
20. String s9 = String.valueOf(obj);
21. System.out.println(s1);
22. System.out.println(s2);
23. System.out.println(s3);
24. System.out.println(s4);
25. System.out.println(s5);
26. System.out.println(s6);
27. System.out.println(s7);
28. System.out.println(s8);
29. System.out.println(s9);
30. }
31. }
Test it Now

Output:

true
11
12
13
14
15.5
16.5
java
StringValueOfExample5@2a139a55

Introduction to Activities
The Activity class is a crucial component of an Android app, and the way activities are launched
fundamental part of the platform's application model. Unlike programming paradigms in which apps
a main() method, the Android system initiates code in an Activity instance by invoking specific c
correspond to specific stages of its lifecycle.

This document introduces the concept of activities, and then provides some lightweight guidance a
them. For additional information about best practices in architecting your app, see Guide to App Ar

The concept of activities

The mobile-app experience differs from its desktop counterpart in that a user's interaction with the
in the same place. Instead, the user journey often begins non-deterministically. For instance, if you
your home screen, you might see a list of emails. By contrast, if you are using a social media app t
email app, you might go directly to the email app's screen for composing an email.

The Activity class is designed to facilitate this paradigm. When one app invokes another, the cal
in the other app, rather than the app as an atomic whole. In this way, the activity serves as the entr
interaction with the user. You implement an activity as a subclass of the Activity class.

An activity provides the window in which the app draws its UI. This window typically fills the screen
the screen and float on top of other windows. Generally, one activity implements one screen in an a
an app’s activities may implement a Preferences screen, while another activity implements a Selec

Most apps contain multiple screens, which means they comprise multiple activities. Typically, one a
specified as the main activity, which is the first screen to appear when the user launches the app. E
another activity in order to perform different actions. For example, the main activity in a simple e-m
screen that shows an e-mail inbox. From there, the main activity might launch other activities that p
like writing e-mails and opening individual e-mails.

Although activities work together to form a cohesive user experience in an app, each activity is only
activities; there are usually minimal dependencies among the activities in an app. In fact, activities
belonging to other apps. For example, a browser app might launch the Share activity of a social-me

To use activities in your app, you must register information about them in the app’s manifest, and y
lifecycles appropriately. The rest of this document introduces these subjects.

Configuring the manifest

For your app to be able to use activities, you must declare the activities, and certain of their attribut
Declare activities
To declare your activity, open your manifest file and add an <activity> element as a child of the <ap
example:

<manifest ... >


<application ... >
<activity android:name=".ExampleActivity" />
...
</application ... >
...
</manifest >

The only required attribute for this element is android:name, which specifies the class name of the
attributes that define activity characteristics such as label, icon, or UI theme. For more information
attributes, see the <activity> element reference documentation.

Note: After you publish your app, you should not change activity names. If you do, you might break some functio
For more information on changes to avoid after publishing, see Things That Cannot Change.

Declare intent filters


Intent filters are a very powerful feature of the Android platform. They provide the ability to launch a
on an explicit request, but also an implicit one. For example, an explicit request might tell the syste
activity in the Gmail app". By contrast, an implicit request tells the system to “Start a Send Email sc
can do the job." When the system UI asks a user which app to use in performing a task, that’s an in

You can take advantage of this feature by declaring an <intent-filter> attribute in the <activity> elem
element includes an <action> element and, optionally, a <category> element and/or a <data> elem
combine to specify the type of intent to which your activity can respond. For example, the following
to configure an activity that sends text data, and receives requests from other activities to do so:

<activity android:name=".ExampleActivity" android:icon="@drawable/app_icon">


<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
</activity>

In this example, the <action> element specifies that this activity sends data. Declaring the <categor
as DEFAULT enables the activity to receive launch requests. The <data> element specifies the type
can send. The following code snippet shows how to call the activity described above:
KOTLINJAVA

// Create the text message with a string


Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.setType("text/plain");
sendIntent.putExtra(Intent.EXTRA_TEXT, textMessage);
// Start the activity
startActivity(sendIntent);

If you intend for your app to be self-contained and not allow other apps to activate its activities, you don't ne
Activities that you don't want to make available to other applications should have no intent filters, and you ca
explicit intents. For more information about how your activities can respond to intents, see Intents and Inten

Declare permissions
You can use the manifest's <activity> tag to control which apps can start a particular activity. A p
launch a child activity unless both activities have the same permissions in their manifest. If you dec
permission> element for a parent activity, each child activity must have a matching <uses-permis

For example, if your app wants to use a hypothetical app named SocialApp to share a post on soci
must define the permission that an app calling it must have:

<manifest>
<activity android:name="...."
android:permission=”com.google.socialapp.permission.SHARE_POST”

/>

Then, to be allowed to call SocialApp, your app must match the permission set in SocialApp's mani

<manifest>
<uses-permission android:name="com.google.socialapp.permission.SHARE_POST" />
</manifest>

For more information on permissions and security in general, see Security and Permissions.

Managing the activity lifecycle

Over the course of its lifetime, an activity goes through a number of states. You use a series of call
between states. The following sections introduce these callbacks.
onCreate()
You must implement this callback, which fires when the system creates your activity. Your impleme
essential components of your activity: For example, your app should create views and bind data to
importantly, this is where you must call setContentView() to define the layout for the activity's use

When onCreate() finishes, the next callback is always onStart().

onStart()
As onCreate() exits, the activity enters the Started state, and the activity becomes visible to the u
what amounts to the activity’s final preparations for coming to the foreground and becoming interac

onResume()
The system invokes this callback just before the activity starts interacting with the user. At this poin
of the activity stack, and captures all user input. Most of an app’s core functionality is implemented
the onResume() method.

The onPause() callback always follows onResume().

onPause()
The system calls onPause() when the activity loses focus and enters a Paused state. This state oc
the user taps the Back or Recents button. When the system calls onPause() for your activity, it tec
activity is still partially visible, but most often is an indication that the user is leaving the activity, and
the Stopped or Resumed state.

An activity in the Paused state may continue to update the UI if the user is expecting the UI to upda
activity include one showing a navigation map screen or a media player playing. Even if such activi
expects their UI to continue updating.

You should not use onPause() to save application or user data, make network calls, or execute da
information about saving data, see Saving and restoring activity state.

Once onPause() finishes executing, the next callback is either onStop() or onResume(), dependin
the activity enters the Paused state.

onStop()
The system calls onStop() when the activity is no longer visible to the user. This may happen bec
destroyed, a new activity is starting, or an existing activity is entering a Resumed state and is cove
all of these cases, the stopped activity is no longer visible at all.

The next callback that the system calls is either onRestart(), if the activity is coming back to inter
by onDestroy() if this activity is completely terminating.

onRestart()
The system invokes this callback when an activity in the Stopped state is about to restart. onResta
the activity from the time that it was stopped.

This callback is always followed by onStart().

onDestroy()
The system invokes this callback before an activity is destroyed.

This callback is the final one that the activity receives. onDestroy() is usually implemented to ens
resources are released when the activity, or the process containing it, is destroyed.

This section provides only an introduction to this topic. For a more detailed treatment of the activity
see The Activity Lifecycle.

Handling Click events in Button | Android


There are 2 ways to handle the click event in button
 Onclick in xml layout
 Using an OnClickListener
Onclick in XML layout
When the user clicks a button, the Button object receives an on-click event.

To make click event work add android:onClick attribute to the Button element in your XML layout. Th
must be the name of the method you want to call in response to a click event. The Activity hosting
implement the corresponding method.
NOTE:
If you use this event handler in your code, make sure that you are having that button in your MainA
use this event handler in fragment because onClick attribute only works in Activity or MainActivity.
Example:
filter_none
brightness_4
<Button xmlns:android="http:// schemas.android.com/apk/res/android"
android:id="@+id/button_send"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="@string/button_send"

android:onClick="sendMessage"

/>

In MainActivity class

filter_none
brightness_4
/** Called when the user touches the button */

public void sendMessage(View view)

// Do something in response to button click

Make sure that your sendMessage method should have the following :
 Be public

 Return void

 Define a View as its only parameter (this will be the View that was clicked)
Using an OnClickListener
You can also declare the click event handler programmatically rather than in an XML layout. This e
mostly preferred because it can be used in both Activities and Fragments.
There are two ways to do this event handler programmatically :
 Implementing View.OnClickListener in your Activity or fragment.
 Creating new anonymous View.OnClickListener.
Implementing View.OnClickListener in your Activity or fragment
To implement View.OnClickListener in your Activity or Fragment, you have to override onClick method

Firstly, link the button in xml layout to java by calling findViewById() method.
R.id.button_send refers the button in XML.
mButton.setOnClickListener(this); means that you want to assign listener for your Button “on this insta
represents OnClickListener and for this reason your class have to implement that interface.
filter_none
brightness_4
<RelativeLayout

xmlns:android="http:// schemas.android.com/apk/res/android"
xmlns:app="http:// schemas.android.com/apk/res-auto"

xmlns:tools="http:// schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context="com.example.sample.MainActivity" >

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/button_send" />

</RelativeLayout>

MainActivity code:

filter_none
brightness_4
public class MainActivity extends AppCompatActivity

implements View.OnClickListener {

private Button mButton;

@Override

protected void onCreate(Bundle savedInstanceState)

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

mButton = findViewById(R.id.button_send);

mButton.setOnClickListener(this);

@Override

public void onClick(View view)

switch (view.getId()) {

case R.id.button_send:
// Do something

If you have more than one button click event, you can use switch case to identify which button is cl
Creating Anonymous View.OnClickListener
Link the button from the XML by calling findViewById() method and set the onClick listener by
using setOnClickListener() method.
MainActivity code:

filter_none
brightness_4
public class MainActivity extends AppCompatActivity {

private Button mButton;

@Override

protected void onCreate(Bundle savedInstanceState)

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

mButton = findViewById(R.id.button_send);

mButton.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View view)

// Do something

});

setOnClickListener takes an OnClickListener object as the parameter. Basically it’s creating an anonym
OnClickListener in the parameter.
It’s like the same in java when you can create a new thread with an anonymous subclass.
setOnClickListener

One of the most usable methods in android is setOnClickListener method which helps u
certain attributes.

setOnClickListener is a method in Android basically used with buttons, image buttons e


method easily like,

public void setOnClickListener(View.OnClickListner)

While invoking this method a callback function will run. One can also create a class for more
this can lead you to code reusability.

After making the class you can implement android.view.View.OnClickListener{} meth


override method inherited from super class called onClick(View v){} in which you can ea
code.

ACTION_IMAGE_CAPTURE_SECURE
Added in API level 17

public static final String ACTION_IMAGE_CAPTURE_SECURE

Intent action that can be sent to have the camera application capture an image and return it when t
with a pin, password, pattern, or face unlock). Applications responding to this intent must not expos
like existing photos or videos on the device. The applications should be careful not to share any ph
applications or Internet. The activity should use Activity#setShowWhenLocked to display on top o
secured. There is no activity stack when this flag is used, so launching more than one activity is str

The caller may pass an extra EXTRA_OUTPUT to control where this image will be written. If the EX
present, then a small sized image is returned as a Bitmap object in the extra field. This is useful for
need a small image. If the EXTRA_OUTPUT is present, then the full-sized image will be written to t
EXTRA_OUTPUT. As of Build.VERSION_CODES.LOLLIPOP, this uri can also be supplied
through Intent.setClipData(ClipData). If using this approach, you still must supply the uri thro
field for compatibility with old applications. If you don't set a ClipData, it will be copied there for you
calling Context#startActivity(Intent).

See also:

 ACTION_IMAGE_CAPTURE

 EXTRA_OUTPUT

Constant Value: "android.media.action.IMAGE_CAPTURE_SECURE"


Android StartActivityForResult Example
By the help of android startActivityForResult() method, we can get result from another activity.

By the help of android startActivityForResult() method, we can send information from one activity to an
android startActivityForResult method, requires a result from the second activity (activity to be invok

In such case, we need to override the onActivityResult method that is invoked automatically when se

String. parseXxx()

Description
This method is used to get the primitive data type of a certain String. parseXxx() is a
static method and can have one argument or two.

Syntax
Following are all the variants of this method −
static int parseInt(String s)
static int parseInt(String s, int radix)
Parameters
Here is the detail of parameters −
 s − This is a string representation of decimal.
 radix − This would be used to convert String s into integer.

Return Value
 parseInt(String s) − This returns an integer (decimal only).
 parseInt(int i) − This returns an integer, given a string representation of decimal, binary,
octal, or hexadecimal (radix equals 10, 2, 8, or 16 respectively) numbers as input.

Example
Live Demo

public class Test {

public static void main(String args[]) {


int x =Integer.parseInt("9");
double c = Double.parseDouble("5");
int b = Integer.parseInt("444",16);

System.out.println(x);
System.out.println(c);
System.out.println(b);
}
}
This will produce the following result −

Output
9
5.0
1092

this keyword in java


There can be a lot of usage of java this keyword. In java, this is a reference
variable that refers to the current object.

Usage of java this keyword


Here is given the 6 usage of java this keyword.

1. this can be used to refer current class instance variable.


2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.

Suggestion: If you are beginner to java, lookup only three usage of this keyword.
1) this: to refer current class instance variable
The this keyword can be used to refer current class instance variable. If there is
ambiguity between the instance variables and parameters, this keyword resolves the
problem of ambiguity.

Understanding the problem without this keyword


Let's understand the problem if we don't use this keyword by the example given below:

1. class Student{
2. int rollno;
3. String name;
4. float fee;
5. Student(int rollno,String name,float fee){
6. rollno=rollno;
7. name=name;
8. fee=fee;
9. }
10. void display(){System.out.println(rollno+" "+name+" "+fee);}
11. }
12. class TestThis1{
13. public static void main(String args[]){
14. Student s1=new Student(111,"ankit",5000f);
15. Student s2=new Student(112,"sumit",6000f);
16. s1.display();
17. s2.display();
18. }}
Test it Now

Output:

0 null 0.0
0 null 0.0

In the above example, parameters (formal arguments) and instance variables are same.
So, we are using this keyword to distinguish local variable and instance variable.

Solution of the above problem by this keyword


1. class Student{
2. int rollno;
3. String name;
4. float fee;
5. Student(int rollno,String name,float fee){
6. this.rollno=rollno;
7. this.name=name;
8. this.fee=fee;
9. }
10. void display(){System.out.println(rollno+" "+name+" "+fee);}
11. }
12.
13. class TestThis2{
14. public static void main(String args[]){
15. Student s1=new Student(111,"ankit",5000f);
16. Student s2=new Student(112,"sumit",6000f);
17. s1.display();
18. s2.display();
19. }}
Test it Now
Output:

111 ankit 5000


112 sumit 6000

If local variables(formal arguments) and instance variables are different, there is no


need to use this keyword like in the following program:

Program where this keyword is not required


1. class Student{
2. int rollno;
3. String name;
4. float fee;
5. Student(int r,String n,float f){
6. rollno=r;
7. name=n;
8. fee=f;
9. }
10. void display(){System.out.println(rollno+" "+name+" "+fee);}
11. }
12.
13. class TestThis3{
14. public static void main(String args[]){
15. Student s1=new Student(111,"ankit",5000f);
16. Student s2=new Student(112,"sumit",6000f);
17. s1.display();
18. s2.display();
19. }}
Test it Now

Output:

111 ankit 5000


112 sumit 6000

It is better approach to use meaningful names for variables. So we use same name
for instance variables and parameters in real time, and always use this keyword.

2) this: to invoke current class method


You may invoke the method of the current class by using the this keyword. If you don't
use the this keyword, compiler automatically adds this keyword while invoking the
method. Let's see the example
1. class A{
2. void m(){System.out.println("hello m");}
3. void n(){
4. System.out.println("hello n");
5. //m();//same as this.m()
6. this.m();
7. }
8. }
9. class TestThis4{
10. public static void main(String args[]){
11. A a=new A();
12. a.n();
13. }}
Test it Now

Output:

hello n
hello m
3) this() : to invoke current class constructor
The this() constructor call can be used to invoke the current class constructor. It is used
to reuse the constructor. In other words, it is used for constructor chaining.

Calling default constructor from parameterized constructor:

1. class A{
2. A(){System.out.println("hello a");}
3. A(int x){
4. this();
5. System.out.println(x);
6. }
7. }
8. class TestThis5{
9. public static void main(String args[]){
10. A a=new A(10);
11. }}
Test it Now

Output:

hello a
10

Calling parameterized constructor from default constructor:

1. class A{
2. A(){
3. this(5);
4. System.out.println("hello a");
5. }
6. A(int x){
7. System.out.println(x);
8. }
9. }
10. class TestThis6{
11. public static void main(String args[]){
12. A a=new A();
13. }}
Test it Now

Output:

5
hello a
Real usage of this() constructor call
The this() constructor call should be used to reuse the constructor from the constructor.
It maintains the chain between the constructors i.e. it is used for constructor chaining.
Let's see the example given below that displays the actual use of this keyword.

1. class Student{
2. int rollno;
3. String name,course;
4. float fee;
5. Student(int rollno,String name,String course){
6. this.rollno=rollno;
7. this.name=name;
8. this.course=course;
9. }
10. Student(int rollno,String name,String course,float fee){
11. this(rollno,name,course);//reusing constructor
12. this.fee=fee;
13. }
14. void display(){System.out.println(rollno+" "+name+" "+course+" "+fee);}
15. }
16. class TestThis7{
17. public static void main(String args[]){
18. Student s1=new Student(111,"ankit","java");
19. Student s2=new Student(112,"sumit","java",6000f);
20. s1.display();
21. s2.display();
22. }}
Test it Now

Output:

111 ankit java null


112 sumit java 6000

Rule: Call to this() must be the first statement in constructor.

1. class Student{
2. int rollno;
3. String name,course;
4. float fee;
5. Student(int rollno,String name,String course){
6. this.rollno=rollno;
7. this.name=name;
8. this.course=course;
9. }
10. Student(int rollno,String name,String course,float fee){
11. this.fee=fee;
12. this(rollno,name,course);//C.T.Error
13. }
14. void display(){System.out.println(rollno+" "+name+" "+course+" "+fee);}
15. }
16. class TestThis8{
17. public static void main(String args[]){
18. Student s1=new Student(111,"ankit","java");
19. Student s2=new Student(112,"sumit","java",6000f);
20. s1.display();
21. s2.display();
22. }}
Test it Now
Compile Time Error: Call to this must be first statement in constructor
4) this: to pass as an argument in the method
The this keyword can also be passed as an argument in the method. It is mainly used in
the event handling. Let's see the example:

1. class S2{
2. void m(S2 obj){
3. System.out.println("method is invoked");
4. }
5. void p(){
6. m(this);
7. }
8. public static void main(String args[]){
9. S2 s1 = new S2();
10. s1.p();
11. }
12. }
Test it Now

Output:

method is invoked
Application of this that can be passed as an argument:

In event handling (or) in a situation where we have to provide reference of a class to


another one. It is used to reuse one object in many methods.

5) this: to pass as argument in the constructor call


We can pass the this keyword in the constructor also. It is useful if we have to use one
object in multiple classes. Let's see the example:

1. class B{
2. A4 obj;
3. B(A4 obj){
4. this.obj=obj;
5. }
6. void display(){
7. System.out.println(obj.data);//using data member of A4 class
8. }
9. }
10.
11. class A4{
12. int data=10;
13. A4(){
14. B b=new B(this);
15. b.display();
16. }
17. public static void main(String args[]){
18. A4 a=new A4();
19. }
20. }
Test it Now
Output:10

6) this keyword can be used to return current class


instance
We can return this keyword as an statement from the method. In such case, return type
of the method must be the class type (non-primitive). Let's see the example:

Syntax of this that can be returned as a statement


1. return_type method_name(){
2. return this;
3. }

Example of this keyword that you return as a


statement from the method
1. class A{
2. A getA(){
3. return this;
4. }
5. void msg(){System.out.println("Hello java");}
6. }
7. class Test1{
8. public static void main(String args[]){
9. new A().getA().msg();
10. }
11. }
Test it Now

Output:

Hello java
Proving this keyword
Let's prove that this keyword refers to the current class instance variable. In this program, we are pr
variable and this, output of both variables are same.
1. class A5{
2. void m(){
3. System.out.println(this);//prints same reference ID
4. }
5. public static void main(String args[]){
6. A5 obj=new A5();
7. System.out.println(obj);//prints the reference ID
8. obj.m();
9. }
10. }
Test it Now

Output:

A5@22b3ea59
A5@22b3ea59

Java new Keyword


The Java new keyword is used to create an instance of the class. In other words, it
instantiates a class by allocating memory for a new object and returning a reference to
that memory. We can also use the new keyword to create the array object.

Syntax
1. NewExample obj=new NewExample();

Points to remember
o It is used to create the object.
o It allocates the memory at runtime.
o All objects occupy memory in the heap area.
o It invokes the object constructor.
o It requires a single, postfix argument to call the constructor

Examples of Java new Keyword


Example 1
Let's see a simple example to create an object using new keyword and invoking the
method using the corresponding object reference.

1. public class NewExample1 {


2.
3. void display()
4. {
5. System.out.println("Invoking Method");
6. }
7.
8. public static void main(String[] args) {
9. NewExample1 obj=new NewExample1();
10. obj.display();
11. }
12.
13. }

Output:

Invoking Method
Example 2
Let's see a simple example to create an object using new keyword and invoking the
constructor using the corresponding object reference.

1. public class NewExample2 {


2.
3. NewExample2()
4. {
5. System.out.println("Invoking Constructor");
6. }
7.
8. public static void main(String[] args) {
9. NewExample2 obj=new NewExample2();
10.
11. }
12.
13. }

Output:

Invoking Constructor
Example 3
Here, we create an object using new keyword and invoke the parameterized constructor.

1. public class NewExample3 {


2.
3. int a,b;
4. NewExample3(int a,int b)
5. {
6. this.a=a;
7. this.b=b;
8. }
9.
10. void display()
11. {
12. System.out.println(a+b);
13. }
14.
15. public static void main(String[] args) {
16. NewExample3 obj=new NewExample3(10,20);
17. obj.display();
18. }
19.
20. }

Output:

30
Example 4
Let's see an example to create an array object using the new keyword.

1. public class NewExample4 {


2.
3. static int arr[]=new int[3];
4.
5.
6. public static void main(String[] args) {
7. System.out.println("Array length: "+arr.length);
8. }
9.
10. }

Output:

Array length: 3
Example 5
Let's see an example to use new keywords in Java collections.

1. import java.util.*;
2.
3. public class NewExample5 {
4.
5. public static void main(String[] args) {
6. List obj=new ArrayList();
7. obj.add("Java");
8. obj.add("C++");
9. obj.add("Python");
10. System.out.println(obj);
11. }
12.
13. }

Output:

[Java, C++, Python]

ArrayAdapter
Syntax

ArrayAdapter(Context context, int resource, int textViewResourceId, T[] objects)

An adapter is a bridge between UI component and data source that helps us to fill
data in UI component. It holds the data and send the data to adapter view then view
can takes the data from the adapterview and shows the data on different views
like listview, gridview, spinner etc. ArrayAdapter is more simple and commonly used
Adapter in android.
Ex 1 list view
public class MainActivity extends AppCompatActivity {
// Array of strings...
ListView simpleList;
String animalList[] = {"Lion","Tiger","Monkey","Elephant","Dog","Cat","Camel"}
;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
simpleList = (ListView) findViewById(R.id.simpleListView);

ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, R.layou


t.activity_list_view, R.id.textView, animalList);
simpleList.setAdapter(arrayAdapter);
}

}
}

Ex 2 using spinner

public class MainActivity extends Activity implements


AdapterView.OnItemSelectedListener {
// Array of strings...
String animalList[] = {"Lion", "Tiger", "Monkey", "Elephant", "Dog", "Cat", "C
amel"};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Getting the instance of Spinner and applying OnItemSelectedListener on i
t
Spinner spin = (Spinner) findViewById(R.id.animalNamesSpinner);
spin.setOnItemSelectedListener(this);

//Creating the ArrayAdapter instance having the animal name's list


ArrayAdapter aa = new ArrayAdapter(this, android.R.layout.simple_spinner_i
tem, animalList);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Setting the ArrayAdapter data on the Spinner
spin.setAdapter(aa);
}

//Performing action onItemSelected and onNothing selected


@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long
id) {
Toast.makeText(getApplicationContext(), animalList[position], Toast.LENGTH
_LONG).show();
}

@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub

}
}

https://www.youtube.com/watch?v=iES7i17TEGM
https://www.youtube.com/watch?v=iES7i17TEGM
https://www.youtube.com/watch?v=iES7i17TEGM

context
Interface to global information about an application environment. This is an abstract class
whose implementation is provided by the Android system. It allows access to application-
specific resources and classes, as well as up-calls for application-level operations such as
launching activities, broadcasting and receiving intents, etc.

https://www.youtube.com/watch?v=89H-FHFyXaA

getView
public abstract View getView (int position,

View convertView,

ViewGroup parent)

Get a View that displays the data at the specified position in the data set. You can
either create a View manually or inflate it from an XML layout file. When the View is
inflated, the parent View (GridView, ListView...) will apply default layout parameters
unless you use LayoutInflater.inflate(int, android.view.ViewGroup,
boolean) to specify a root view and to prevent attachment to the root.

Parameters

position int: The position of the item within the adapter's data set of the item whose view we want.

convertView View: The old view to reuse, if possible. Note: You should check that this view is non-null and
appropriate type before using. If it is not possible to convert this view to display the correct data
can create a new view. Heterogeneous lists can specify their number of view types, so that this
always of the right type (see getViewTypeCount() and getItemViewType(int)).

parent ViewGroup: The parent that this view will eventually be attached to

Returns

View A View corresponding to the data at the specified position.

https://www.youtube.com/watch?v=ka5Tk7J9rG0
LayoutInflater
Instantiates a layout XML file into its corresponding View objects. It is never used
directly. Instead,
useActivity.getLayoutInflater() or Context#getSystemService to retrieve a
standard LayoutInflater instance that is already hooked up to the current context and
correctly configured for the device you are running on.

To create a new LayoutInflater with an additional Factory for your own views, you
can use cloneInContext(Context) to clone an existing ViewFactory, and then
call setFactory(LayoutInflater.Factory) on it to include your Factory.

For performance reasons, view inflation relies heavily on pre-processing of XML files
that is done at build time. Therefore, it is not currently possible to use LayoutInflater
with an XmlPullParser over a plain XML file at runtime; it only works with an
XmlPullParser returned from a compiled resource (R.something file.)

https://www.youtube.com/watch?v=Fr8aHku9aqk
public static final
final indicates that the value of the variable won't change - in other words, a variable
whose value can't be modified after it is declared.
Use public final static String when you want to create a String that:
1. belongs to the class (static: no instance necessary to use it), and that
2. won't change (final), for instance when you want to define a String constant that will
be available to all instances of the class, and to other objects using the class.

setOnItemClickListener
This is the most simple way to get position of an item within a ListView. In most of the case,
users click on an item with a ListView, this event will be triggered and it will call
onListItemClick listener by passing four parameters:

 The ListView where the click happened


 The view that was clicked within the ListView
 The position of the view in the list
 The row id of the item that was clicked
First, we set the listener on the listview.

1 listView.setOnItemClickListener(onItemClickListener);
Then, we define the listener. Here is the example source code:

private OnItemClickListener onItemClickListener


1
= new OnItemClickListener() {
2
3 @Override
4 public void onItemClick(AdapterView<?> arg0, View arg1, int position,
5 long arg3) {
6 // TODO Auto-generated method stub
7 //do your job here, position is the item position in ListView
8 }
9 };

https://www.youtube.com/watch?v=26ywswJSkuY

setOnItemLongClickListener
The XML for each item in the list (should you use a custom XML) must
have android:longClickable="true" as well (or you can use the convenience
method lv.setLongClickable(true);). This way you can have a list with only some items
responding to longclick.
showUpdateDeleteDialog—updateArtist--deleteArtist

private void showUpdateDeleteDialog(final String artistId, String artistName) {

AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);


LayoutInflater inflater = getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.update_dialog, null);
dialogBuilder.setView(dialogView);

final EditText editTextName = (EditText) dialogView.findViewById(R.id.editTextName);


final Spinner spinnerGenre = (Spinner) dialogView.findViewById(R.id.spinnerGenres);
final Button buttonUpdate = (Button) dialogView.findViewById(R.id.buttonUpdateArtist);
final Button buttonDelete = (Button) dialogView.findViewById(R.id.buttonDeleteArtist);

dialogBuilder.setTitle(artistName);
final AlertDialog b = dialogBuilder.create();
b.show();

buttonUpdate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String name = editTextName.getText().toString().trim();
String genre = spinnerGenre.getSelectedItem().toString();
if (!TextUtils.isEmpty(name)) {
updateArtist(artistId, name, genre);
b.dismiss();
}
}
});

buttonDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
/*
* we will code this method to delete the artist
* */

}
});
}

https://www.youtube.com/watch?v=afVQ04EnX6w

RESULT_CANCELED
Added in API level 1

public static final int RESULT_CANCELED

Standard activity result: operation canceled.


Constant Value: 0 (0x00000000)

RESULT_FIRST_USER
Added in API level 1

public static final int RESULT_FIRST_USER

Start of user-defined activity results.

Constant Value: 1 (0x00000001)

RESULT_OK
Added in API level 1

public static final int RESULT_OK

Standard activity result: operation succeeded.

Constant Value: -1 (0xffffffff)

getExtras
Added in API level 1

public Bundle getExtras ()

Retrieves a map of extended data from the intent.

Returns

Bundle the map of all extras previously added with putExtra(), or null if none have been added.

Put extra
Intent putExtra(String name, Parcelable value)

Add extended data to the intent.

Intent putExtra(String name, long[] value)

Add extended data to the intent.

Intent putExtra(String name, byte value)

Add extended data to the intent.

Intent putExtra(String name, double[] value)

Add extended data to the intent.

Intent putExtra(String name, CharSequence value)

Add extended data to the intent.

Intent putExtra(String name, boolean[] value)

Add extended data to the intent.

Intent putExtra(String name, int value)

Add extended data to the intent.

Intent putExtra(String name, char[] value)

Add extended data to the intent.

Intent putExtra(String name, byte[] value)

Add extended data to the intent.

Intent putExtra(String name, Parcelable[] value)

Add extended data to the intent.

Intent putExtra(String name, Bundle value)

Add extended data to the intent.

Intent putExtra(String name, CharSequence[] value)

Add extended data to the intent.

Intent putExtra(String name, float[] value)

Add extended data to the intent.


Intent putExtra(String name, double value)

Add extended data to the intent.

Intent putExtra(String name, int[] value)

Add extended data to the intent.

Intent putExtra(String name, String[] value)

Add extended data to the intent.

Intent putExtra(String name, short[] value)

Add extended data to the intent.

Intent putExtra(String name, boolean value)

Add extended data to the intent.

Intent putExtra(String name, String value)

Add extended data to the intent.

Intent putExtra(String name, long value)

Add extended data to the intent.

Intent putExtra(String name, char value)

Add extended data to the intent.

Intent putExtra(String name, Serializable value)

Add extended data to the intent.

Intent putExtra(String name, float value)

Add extended data to the intent.

Intent putExtra(String name, short value)

Add extended data to the intent.

Intent putExtras(Intent src)

Copy all extras in 'src' in to this intent.

Intent putExtras(Bundle extras)

Add a set of extended data to the intent.


Handling bitmaps
There are a number of reasons why loading bitmaps in your Android app is tricky:

 Bitmaps can very easily exhaust an app's memory budget. For example, the camera on
the Pixel phone takes photos of up to 4048x3036 pixels (12 megapixels). If the bitmap
configuration used is ARGB_8888, the default for Android 2.3 (API level 9) and higher,
loading a single photo into memory takes about 48MB of memory (4048*3036*4 bytes).
Such a large memory demand can immediately use up all the memory available to the app.
 Loading bitmaps on the UI thread can degrade your app's performance, causing slow
responsiveness or even ANR messages. It is therefore important to manage threading
appropriately when working with bitmaps.
 If your app is loading multiple bitmaps into memory, you need to skillfully manage memory
and disk caching. Otherwise, the responsiveness and fluidity of your app's UI may suffer.

For most cases, we recommend that you use the Glide library to fetch, decode, and
display bitmaps in your app. Glide abstracts out most of the complexity in handling
these and other tasks related to working with bitmaps and other images on Android.
For information about using and downloading Glide, visit the Glide repository on
GitHub.

You can also opt to work directly with the lower-level APIs built into the Android
framework. For more information on doing so, refer to Loading Large Bitmaps
Efficiently, Caching Bitmaps, and Managing Bitmap Memory.

setImageBitmap
Added in API level 1

public void setImageBitmap (Bitmap bm)

Sets a Bitmap as the content of this ImageView.

Parameters

bm Bitmap: The bitmap to set


BaseAdapter
Before we share BaseAdapter it is first important to revise Adapter. In android,
an adapter is a bridge between UI component and data source that helps us to fill data
in the UI component. It holds the data and send the data to adapter view then view
can takes the data from the adapter view and shows the data on different views like
as list view, grid view, spinner etc. For more customization of views we uses the base
adapter. Now lets discuss BaseAdapter class.

 BaseAdapter is a common base class of a general implementation of an Adapter


that can be used in ListView, GridView, Spinner etc.
 Whenever you need a customized list in a ListView or customized grids in
a GridView you create your own adapter and extend base adapter in that.
 Base Adapter can be extended to create a custom Adapter for displaying a
custom list item.

Important Note: ArrayAdapter is also an implementation of BaseAdapter.

SimpleAdapter
An easy adapter to map static data to views defined in an XML file. You can specify
the data backing the list as an ArrayList of Maps. Each entry in the ArrayList
corresponds to one row in the list. The Maps contain the data for each row. You also
specify an XML file that defines the views used to display the row, and a mapping
from keys in the Map to specific views. Binding data to views occurs in two phases.
First, if a SimpleAdapter.ViewBinder is
available, ViewBinder#setViewValue(android.view.View, Object, String) is
invoked. If the returned value is true, binding has occurred. If the returned value is
false, the following views are then tried in order:

 A view that implements Checkable (e.g. CheckBox). The expected bind value is a boolean.
 TextView. The expected bind value is a string
and setViewText(android.widget.TextView, java.lang.String) is invoked.

 ImageView. The expected bind value is a resource id or a string


and setViewImage(android.widget.ImageView,
int) or setViewImage(android.widget.ImageView, java.lang.String) is
invoked.

If no appropriate binding can be found, an IllegalStateException is thrown.


getReference

public DatabaseReference getReference ()

Also: Google Play services

Gets a DatabaseReference for the database root node.

Returns

 A DatabaseReference pointing to the root node.

public DatabaseReference getReference (String path)

Also: Google Play services

Gets a DatabaseReference for the provided path.

Parameters

Path to a location in your FirebaseDatabase.


path

Returns

 A DatabaseReference pointing to the specified path.

You might also like