Notes and
Notes and
Notes and
Example
Import the Scanner class from the Java API:
import java.util.Scanner;
class MyClass {
System.out.println("Enter 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:
*/
class MyClass {
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
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.
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.
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...
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.
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
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
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?
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.
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.
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.
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.
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.
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.
Returns
Returns
getInstance
Parameters
Returns
A 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.
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
Returns
A FirebaseDatabase instance.
getReference
Returns
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
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
Returns Reference
setValue
public
void setValue (Object value, Object priority, DatabaseReference.CompletionListener li
stener)
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
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:
Parameters
The value to set at this location or null to delete the existing data
value
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:
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
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:
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 User() {
// Default constructor required for calls to
DataSnapshot.getValue(User.class)
}
}
User.java
JavaKotlin
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.
@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
DataSnapshot
A DataSnapshot instance contains data from a Firebase Database location. Any time you
read Database data, you receive the data as a DataSnapshot.
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
Returns
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
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.
Output:
10
Example 2
Let's see an example to determine whether we can use return in void method.
Output:
Output:
next →← prev
Java ArrayList class uses a dynamic array for storing the elements. It inherits AbstractList class and
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(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
void add(int index, E element) It is used to insert the specified element at the sp
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.
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
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
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.
void sort(Comparator<? super E> c) It is used to sort the elements of the list on the b
comparator.
List<E> subList(int fromIndex, int It is used to fetch all the elements lies within the
toIndex)
Java new generic collection allows you to have only one type of object in a collection. Now it is type
required at runtime.
For more information on Java generics, click here Java Generics Tutorial.
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.
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
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
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
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]
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]
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: []
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:
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.
StringBuilder() creates an empty string Builder with the initial capacity of 16.
StringBuilder(int length) creates an empty string Builder with the specified capacity as l
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 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)
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. }
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:
Returns
string representation of given value
Output:
3010
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
Output:
A
B
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.
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 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.
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:
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.
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:
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
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.
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
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.
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.
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.
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 */
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 {
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton = findViewById(R.id.button_send);
mButton.setOnClickListener(this);
@Override
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 {
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton = findViewById(R.id.button_send);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
// 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.
While invoking this method a callback function will run. One can also create a class for more
this can lead you to code reusability.
ACTION_IMAGE_CAPTURE_SECURE
Added in API level 17
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
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
System.out.println(x);
System.out.println(c);
System.out.println(b);
}
}
This will produce the following result −
Output
9
5.0
1092
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.
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.
Output:
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.
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.
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
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:
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:
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
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
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
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.
Output:
Invoking Constructor
Example 3
Here, we create an object using new keyword and invoke the parameterized constructor.
Output:
30
Example 4
Let's see an example to create an array object using the new keyword.
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:
ArrayAdapter
Syntax
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);
}
}
Ex 2 using spinner
@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);
@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
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:
1 listView.setOnItemClickListener(onItemClickListener);
Then, we define the listener. Here is the example source code:
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
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
RESULT_FIRST_USER
Added in API level 1
RESULT_OK
Added in API level 1
getExtras
Added in API level 1
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)
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
Parameters
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.
Returns
Parameters
Returns