Share your knowledge

Monday, 9 January 2017

Dfferences between ACCESS_FINE_LOCATION and ACCESS_COARSE_LOCATION

  
Difference Between Fine and Coarse Locations

Fine Location: Provides better and accurate locations.

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
  

It gives permissions to work with GPS Provider and Network Provider: 

Coarse Location: Provides less accurate locations

 
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

It gives permissions to work with only Network Provider.

Friday, 6 January 2017

Xml Basics to create a layout in Android

XML - eXtensible Markup Language:

Markup Language: Every opening tag will have it's corresponding closed tag.

Ex:
      <TextView>
  
      </TextView>

It can also be written as
  
 <TextView/> (Opening and closing tag are at one line)


XML Namespaces: XML Namespaces provide a method to avoid element name conflicts.

Ex:

     Below xml is used to store Suresh information

      <user>
     <name>Suresh</name>
     <city>Palasa</city>
     <phoneNumber>9898989898</address>
      </user>

      <user>
     <address>Srikakulam,Palasa</name>
     <age>23</age>
      </user>

Note: If these XML fragments were added together, there would be a name conflict. Both contain a <user> element, but the elements have different content and meaning. A user or an XML application will not know how to handle these differences.

Solving the name conflict using Prefix:

      <a:user>
     <a:name>Suresh</a:name>
     <a:city>Palasa</a:city>
     <a:phoneNumber>9898989898</a:phoneNumber>
      </a:user>

      <b:user>
     <b:address>Srikakulam,Palasa</b:name>
     <b:age>23</b:age>
      </b:user>

In the example above, there will be no conflict because the two <user> elements have different names.


XML Namespaces - The xmlns Attribute:

When using prefixes in XML, a namespace for the prefix must be defined.
The namespace can be defined by an xmlns attribute in the start tag of an element.

The namespace declaration has the following syntax.

xmlns:prefix="URI"

     <root>
      <a:user xmlns:a="http://schemas.android.com/apk/res/android/">
     <a:name>Suresh</a:name>
     <a:city>Palasa</a:city>
     <a:phoneNumber>9898989898</a:phoneNumber>
      </a:user>

      <b:user xmlns:b="http://schemas.android.com/apk/res-auto">
     <b:address>Srikakulam,Palasa</b:name>
     <b:age>23</b:age>
     </b:user>
      </root>


In the example above:

The xmlns attribute in the first <user> element gives the a: prefix a qualified namespace.

The xmlns attribute in the second <user> element gives the b: prefix a qualified namespace.

When a namespace is defined for an element, all child elements with the same prefix are associated with the same namespace.

Namespaces can also be declared in the XML root element as below:

     <root
          xmlns:a="http://schemas.android.com/apk/res/android/"
            xmlns:b="http://schemas.android.com/apk/res-auto">


      <a:user xmlns:a="http://schemas.android.com/apk/res/android/">
     <a:name>Suresh</a:name>
     <a:city>Palasa</a:city>
     <a:phoneNumber>9898989898</a:phoneNumber>
      </a:user>

      <b:user xmlns:b="http://schemas.android.com/apk/res-auto">
     <b:address>Srikakulam,Palasa</b:name>
     <b:age>23</b:age>
     </b:user>
      </root>

The purpose of using an URI is to give the namespace a unique name. However, companies often use the namespace as a pointer to a web page containing namespace information.


User Interface In Android





Java Basics to work with Android Projects

Java Basics:
  
Class: Class is a blueprint / template to create an object.

Object: Object is a real world thing, it can be anything ex: phone, file, bottle, bag, dog etc.

Which is first class or object?

Ans: Many people will think that class is first as objects are created from class but class will be created once we imagine an object so object is first in my point of view.

Why should i create a class/ object: Well, Programming languages are used to simplify or beautify our life by making the complex problems simpler. Suppose you have a laundry shop where people were used to come to get their cloths washed and iron.

Now, you want to maintain the book with list of people who come to your laundry shop. which may looks like below.




This record contains 6 columns/fields Name, No. of Shirts, No. of Pants, Advance paid, Laundry completed?, Address and Delivered?

Name: Name of the people who come for laundering
No. of Shirts: Number of shirts given for laundering.
No. of Pants: Number of pants given for laundering.

Total Amount: Total amount for laundering
Advance Paid: Advance paid
Laundry completed: Is the laundering completed or not?
Address: Delivery address
Delivered: Is the delivery completed or not?

Disadvantages of maintaining a book like above:

1. You may lost your book at any time.
2. Becomes complex in calculating total amount when number of shirts and pants were more
3. Becomes difficult to modify the values in case of address change etc.
4. Maintaining large number of people need lot of books and in turn paper wastage.


To overcome all these problems programming languages were introduced which makes complex problems simpler.

Our next goal is to tell the computer to do all these things(Maintaining a book like above). Unfortunately computer doesn't understands human language so there should be someone who can make computer understand these, he is non other than a programming language.

Let's consider that programming language as Java.

As we heard lot of times that Java is object oriented programming language. 

What is object oriented programming language?: 

Ans: A language which deals with objects( real world entities ) is called Object Oriented Programming language(OOP).

Here in our case Object(real world thing) is a User who comes for the laundry.

Let's create a template(class) which describes this object(entity)
here is
Creating class:
Syntax:

 // ClassName is the name of the class, you can give any name based on your //need

class ClassName{

//it may contain some properties(fields)
//it may contain some functionality(methods)

}

Declaring Variables:

DataType: Name itself suggests that it is "type of data we are working with", it can be an integer type, string type, floating value type or anything.

Ex: int , String, float, double etc...

Declaring varibles/properties:

int amount;

String name;

String address;

Note: If you are very beginner in java and if you are getting confused then go through some other tutorials to learn basics of java first.

Declaring Methods/Function:

Method: Methods are written do some functionality, for example it may be used to calculate total amount to be paid for 2 shirts and 3 pants.

Method Declaration: 

Syntax:

Method without Parameters:


return type is nothing but data type, so it can be either int , long, double etc...

use-case: (understanding how methods can be created)

1. My friend asked me what is your father name? I replied that my father name was Anjaneyulu. Here i am replying(returning) to my friend by saying my father name. So, return value is father name(String)

         String whatIsFatherName(){

              return "Anjaneyulu";
          
               }


2. Now, My friend asked me to keep switch on the light, i switched it on.
Here i am not replying anything to my friend, once i switched on light my task is done. So, here i am returning nothing which we used to call as void.

       void switchOnLight(){


                   
                            }

Method with Parameters:


         

Note: Suppose one shirt cost for laundering is 20 and one pant cost for laundering is 30, then total amount to be paid by suresh(row 1 in the top table) is:

2 shirts * 20 = 40
2 pants * 30 = 60
Total = 100;

So, we will pass number of shirts and number of shirts to totalAmount(int shirts, int pants) method as above.


Note: Class can also be called as collection of properties and functions.

Lets create class for a user who comes for laundering.


public class User {

    //properties

    //name of the user 
 String name_of_user;

    //number of shirts 
 int number_of_shirts_of_user;

    //number of pants 
 int number_of_pants_of_user;

    //total amount to be paid 
 int total_amount_to_be_paid;

    //advance paid 
 int advance_paid_by_user;

    //is laundry completed? 
 boolean is_laundry_completed;

    //is cloths delivered to the address 
 boolean is_delivered;

    //address of the user 
 String address_of_user;


    //methods/ functionalities
 
    //to get the name of the user, since it is returning data of type String , return type is String 
 
 public String getName() {
        return name_of_user;
    }

    //setting the name of the user, here, we are just setting the name user but we are not getting anything back from this method, so the return type is void.     
 
public void setName(String name) {
        name_of_user = name;
    } 
 
 public int getNumber_of_shirts() {
        return number_of_shirts_of_user;
    } 
 
 //Other below methods are declared for purpose as above
 
 
  public void setNumber_of_shirts(int number_of_shirts) {
        number_of_shirts_of_user = number_of_shirts;
    }

    public int getNumber_of_pants() {
        return number_of_pants_of_user;
    }

    public void setNumber_of_pants(int number_of_pants) {
        number_of_pants_of_user = number_of_pants;
    }

    public int getTotal_amount() {
        return total_amount_to_be_paid;
    }

    public void setTotal_amount(int total_amount) {
        total_amount_to_be_paid = total_amount;
    }

    public int getAdvance_paid() {
        return advance_paid_by_user;
    }

    public void setAdvance_paid(int advance_paid) {
        advance_paid_by_user = advance_paid;
    }

    public boolean isLaundry_completed() {
        return is_laundry_completed;
    }

    public void setLaundry_completed(boolean laundry_completed) {
        is_laundry_completed = laundry_completed;
    }

    public boolean isDelivered() {
        return is_delivered;
    }

    public void setDelivered(boolean delivered) {
        is_delivered = delivered;
    }

    public String getAddress() {
        return address_of_user;
    }

    public void setAddress(String address) {
        address_of_user = address;
    }
}
 
 




Now, We are familiar with Class, let's create object.

Object: (real world entity)

1. Objects are created from a class(template).
2. Syntax of creating object:

ClassName refVariable = new ClassName();

Creating object of User class.

//this is just like creating one row for suresh(as shown in the top image)

User suresh = new User();

Below image will depict what definitely will happen when we write above line.



As we can see fields will be initialized with default values.

To change those default values (just like updating suresh row with new values like No. of Shirts-2, No. of Pants-2, Total amount-100, Advance paid -50, laundry completed -no, address- palasa, delivered - no.

User the reference memory locatoin (suresh) and update with new values as below.

User suresh = new User();

suresh.name_of_user="Suresh";
suresh.number_of_shirts_of_user =2;
suresh.number_of_pants_of_user=2;
suresh.total_amount_to_be_paid=100;
suresh.advance_paid_by_user=50;
suresh.is_laundry_completed=false;
suresh.address="palasa";
suresh.is_delivered=false;

After two days you want to update suresh record as laudry is delivered, then we can call a method and update as below.

//calling method

suresh.setLaundry_completed(true);

Updating suresh record as delivered.

suresh.setDelivered(true);

Creating objects for Hareesh and Aravind.

User harresh = new User();
User aravind = new User();

Task for you: Now, update the hareesh and aravind records as shown the book above.

Inheritance: Acquiring properties and behavior of one object by another object.

Use: Reduces time in creating a new class

use-case: Designing a website will take less time if you already have a template, but it will take more time if you don't have a template.

Inheritance: You are using features of template and adding few more functionalities and requirement to that template.

Note: Similarly in java, we can create another class from an existing class.

For example i have a class named Bag:

class Bag{

String name;

int weight;

int color;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public int getWeight() {
    return weight;
}

public void setWeight(int weight) {
    this.weight = weight;
}

public int getColor() {
    return color;
}

public void setColor(int color) {
    this.color = color;
}

}


Creating WildCraftBag class from Bag class:

Here i am acquiring properties of Bag in WildCraftBag and adding someother properties.

class WildCraftBag extends Bag{

//default constructor

public WildCraftBag(){

}

//this is new features i am adding.

int number_of_pockets;
 
}

If we create object of WildCraftBag we can access(only in some cases) properties and functionalities of Bag as WildCraftBag is child class of Bag.

Creating object of WildCraftBag:

WildCraftBag wildcraft = new WildCraftBag();
//accessing properties of Bag class

wildcraft.name="WildCraft";
wildcraft.setWeight(1);//i mean 1kg weight

Note: We will discuss about Inheritance very detail in later chapters.

Note: We will discuss about other important concepts in detail later on...

Let's discuss few things in xml


Friday, 30 December 2016

Structure of Android Application

Below is the structure of an Android Project in Studio




 



































1. MyFirstApplication: This is the project name we gave in the initial stage of creation.

2. Icon: The icon pointing in the second arrow is used to filter the project with different modules as below.
  • Project
  • Packages
  • Scratches
  • Android
  • Project Files
  • Problems
  • Production
  • Tests
  • Android Instrumentation Tests
3. AndroidManifest.xml: This file is located under manifests folder, every application must have an AndroidManifest.xml file (With the same name) in it's root directory. This file provides essential information about your app to the Android System, which the system must have before it can run any of the
application code.
  • Contains all the application components(Activities, Services, Broadcast Receivers, Content Providers etc.) 
  • Contains information of the package
  • It declares which permissions the application must have.
4. Java Folder: All the java files will present inside this folder. By default it contains three packages with the same name you specified while creating the project.

5. MainActivity: This is the Activity you specified while creating project. You can find this Activity inside AndroidManifest.xml.


Below code can be found inside AndroidManifest.xml

 
 
<activity android:name=".MainActivity">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>
 
 
 
We will discuss it briefly in the later sections.

6. (androidTest) and (test) packages: All the unit test related code will be present inside these packages.

7.res Folder: All the xml files will present inside this folder. By default few of the essential folders(drawable, layout, mipmap, values) and xml(activity_main, colors.xml, dimens.xml, strings.xml,styles.xml) files will be created.

8. drawable folder: Images you want to use in your application need to be placed here. we will discuss about it briefly later on.

9. layout folder: layouts will decide how our application user interface should look like, all the layouts will be created under this folder.

10. activity_main.xml: This is the file which decides how a screen(activity) should look like. An Activity with user interface should have a java file(in this case MainActivity.java) and an xml file(activity_main.xml).

11. mipmap folder: Here also we will keep images used in the application.
then, how are these mipmap images different from drawable images?
There are two cases you deal with when working with images in Android:
  1. If you want to load an image for your device density and if you are going to use it "as is", without changing its actual size, then you should work with drawables.
  2. If you want to load an image for your device density, but the image should to be scaled up or down. For instance this is needed when you want to show a bigger launcher icon, or you have an animation, which increases image's size. In such cases, to ensure best image quality, you should put your image into mipmap folder. What Android will do is, it will try to pick up the image from a higher density bucket instead of scaling it up. This will increase sharpness (quality) of the image.
    Note:
  • Launcher icons always go into mipmap folder.
  • Images, which are often scaled up (or extremely scaled down) and whose quality is critical for the app, go into mipmap folder as well.
  • All other images are usual drawables.
12. values folder: This folder contains other various XML files that contain a collection of resources, such as strings, colors, styles, dimensions etc

13.build.gradle: This is an auto generated file which contains compileSdkVersion, buildToolsVersion, applicationId, minSdkVersion, targetSdkVersion, versionCode and versionName, dependencies, etc. We will discuss about all of these in brief in later lessons.

 Few Java Basics Must know before starting to write something. 




Building Your First Application

Once Android setup is done, open android studio and follow below steps to create your first android Application.

1. Click on File -> New -> New Project as show below























Create New Project window will open now.

2. Configure your new project:

Enter Application name, Company Domain, Package name, Check include C++ support if you want to develop applications using C++, and select location where you want to save your project.

Application name: Enter name of your application

1. Name should not start with lowercase































2. Name can start with special symbols like ; , $, @ etc. as shown below

































If we create project with this application name, then application will run and the name of the application will looks like below.








































3. Name can consists of white spaces

4. No other project with same name should present in the same location.
 
Note: Enter Application name as "My First Application"

Company Domain: The domain name is used by Android Studio to generate a package name. Give whatever name you like to include in package.

1. It cannot start with special symbols
2. It can start with any letter ( either lower or upper case)
3. As we discussed domain name is used by Android studio to generate package name, what will happen if we enter some java keyword as domain name for example "super" or "case" etc ?
      Ans: As the package name should not contain java keywords, studio will automatically change package name to some other by adding some character. If we give super as domain name, then the package name will change to "asuper.myfirstapplication" as shown below.






























Note: Keep "com" as Company Domain name for now

Package name: It is just a unique identifier for your application in the Google Play Store. It can be anything you want as long as it is unique. Generally, we use reverse domain names like com.something. or org.something.

1. We can edit package name using edit option in the right, once done click on done.

Include C++ Support: If you want to develop application in C++ then check it

Project Location: Choose a location where you want to put your applications.

1. Path of the location should not contain any white spaces.

 Click Next.

3. Select the form factors your will run on:

1. We can develop applications for
  • Phone and Tablet
  • Wear
  • TV
  • Android Auto
  • Glass
2. Check Phone and Tablet as we want to develop phone applications.

3. Minimum SDK - Lower API  levels target more devices, but have fewer features available. If you select API Level 18, the apps will not run on mobiles with lower API Levels.

Choose API 13: Android 3.2 ( Honeycomb ) for now.

Click Next

























 4. Add an Activity to Mobile: We can select different Activities based on your application need.

Choose Empty Activity for now, click Next.































5. Customize the Activity: Enter Activity name and layout name.

Activity Name:  Enter name of the Activity, it should not start with special symbols and numbers.

Layout Name: Enter name of the layout, it should not start with special symbols, numbers and Uppercase letter.

Click on Finish































Once the Gradle build is done your project will open as below
























Now Connect Mobile device to your system via USB.

Connecting mobile device to studio.

1. Connect Mobile and System with usb cable as shown below.
























2. In the notifications we can see Connected as camera/Connected as Media, click on this notification

3. Select Camera and select USB debugging enabled













































































4. Now you can find your device connected in studio.  
 
Then click on on Run button in the top as shown below.






























Hey.....Your first application on your/friend's mobile......Congrates....







































Structure of Android Project:




Application Components





Application components are the essential building blocks of an Android application. These components are loosely coupled by the application manifest file AndroidManifest.xml that describes each component of the application and their interaction.

Four main Components are:

1. Activity
2. Service
3. Broadcast Receiver
4. Content Provider


Let's see simple and short descriptions of main components.



Activity: An activity represents a single screen with a user interface, Lets take an example of contact application, one screen will show all the contacts(Activity -1), clicking on  New contact will show another screen to add contact(Activity -2).

Activity -1























Activity -2 























Note: Activity serve as the entry point for a user's interaction with an app.

An Activity is implemented as a subclass of Activity class as below...

public class MainActivity extends Activity {
System.out.println("Building Activity");
}

Service: A service runs in the background to perform long-running operations. which doesn't contain any user interface. For example, a service might play music in the background while the user is in a different application.

other examples include: fetching wifi status, network status in the background.

A service is implemented as a subclass of Service class as below...


public class MyService extends Service {
System.out.println("Building Service");
}



Broadcast Receivers: These are registered for system announcements.
Ex: 1. When you plug-in a headset, headset icon will come in the status bar as below.























Mobile without headset connected
























Mobile with headset connected

2. when you plug-in a charger, charger symbol will come
3. when you click on volume button to increase/decrease volume, how volume will get change?
























Everything is done by Broadcast Receivers.

Note: It provides communication between android os and applications.

A broadcast receiver is implemented as a subclass of BroadcastReceiver class and each message is broadcaster as an Intent object.
  

public class MyReceiver  extends  BroadcastReceiver {
   public void onReceive(context,intent){}
}



Content Providers: A content provider supplies data from one application to other application on request. Such requests are handled by the methods of the ContentResolver class. It's not possible to share data from one application to another application without Content Resolvers.

use-case:  Getting all the contacts information from contacts application to What's app application.

A content provider is implemented as a subclass of ContentProvider class and must implement a standard set of APIs that enable other applications to perform transactions.


public class MyContentProvider extends  ContentProvider {
   public void onCreate(){}
}




We will check these components and other components in detail in their individual chapters.

 Let's build your first application



Advantages of Android


 

Advantages for developer:

1. Android is open source - source code is exposed to public

2. Application Framework ( Developer heart ) provides built in classes(Wifi
Manager, Location Manger)

3. DVM is optimized for mobile devices

4. SQLite Database is used to maintain structured data etc......

Advantages to mobile users/developers:

1. Biggest advantage is Android is from Google, the name Google provides lot of trust for users to buy android device.

2. Android is the most used mobile operating systems. It is used by more than billion people

3. Users can do lots of tasks at once - multitasking

4. Android Widgets makes the user experience much better and helps in doing multitasking.


Note:

1. Advantage for developer/ Disadvantage for user: Lot of advertisements in the applications

2. Disadvantage for developer and user: There are plenty of process running in the background which results in the quick draining of the battery. It is hard to stop these applications as the majority of them are system applications.

Application Components