Share your knowledge

Friday 13 January 2017

Android Studio Shortcut keys - Very Important




1. Save all ( CTRL+S )
 
2. Maximize / minimize ( CTRL+SHIFT+F12 )  
 
3. Inspect current file with current profile (ALT+SHIFT+I) 
 
4. Quick switch scheme (CTRL+`
 
5. Open project structure (CTRL+ALT+SHIFT+S)



6. Search every where (Double Shift)

7. Find (CTRL+F)

8. Find next (F3)

9. Find previous (SHIFT+F3)

10. Replace (CTRL+SHIFT+R)

11. Find class (CTRL+N)

12. Find file (CTRL+SHIFT+N)

13. Find in path (CTRL+SHIFT+F)




14. Open file structure popup (CTRL+F12)

15. Navigate between open editor tabs (ALT+LEFT/RIGHT ARROWS)

16. Open Current editor tab in new window (SHIFT+F4)

17. Recently edited files (CTRL +SHIFT+E)

18. Go to last edit locatoin (CTRL+SHIFT+BACKSPACE)

19. Close active editor tab (CTRL + F4)

20. Return to editor window from tool window (ESC)

21. Go to line (CTRL+G)




22. Generate code (getters, setters, constructors etc) (ALT+INSERT)

23. Override methods (CTRL+O)

24. Collapse or expand current code block (CTRL+ PLUS/MINUS)

25. Duplicate current line or selection (CTRL+D)

26. Quick documentation lookup (CTRL+Q)

27. Show parameters for selected method (CTRL+P)

28. Go to declaration - (CTRL+CLICK)

29. Open quick definition lookup (CTRL+SHIFT+I)

30. Comment /uncomment with line comment (CTRL+/)

31. Comment /uncomment with block comment (CTRL+SHIFT+/)

32. Select successively increasing code block (CTRL+W)

33. Decrease current selection to previous state (CTRL+SHIFT+W)

34. Move to code block start (CTRL+[)

35. Move to code block end (CTRL+])

36. Select to the code block start (CTRL+SHIFT+[)

37. Select to the code block end (CTRL+SHIFT+])




38. Make project (build) - (CTRL+F9)

39. Build and run (SHIFT+F10)

40. Copy (F5)

41. Move (F6)

42. Delete (DELETE)

43. Rename (SHIFT+F6)















Tuesday 10 January 2017

Location can be determined in Android Application By Two Ways:

 Location can be determined in Android Applications by two ways:
  1. Using NETWORK_PROVIDER
  2. Using GPS_PROVIDER
Using Network Provider: The network provider determines the location of the users using cell towers, wifi points and etc. This location provider is faster in response. This is mostly used to get location inside rooms or buildings.

Permissions required to use Network Provider are either,

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

Using Gps Provider: The GPS Provider determines the location of the users using satellites. The GPS receiver in the mobile receives the signals from satellites and process to determine exact locations, but it takes more time for response and causes delay. It works better in outdoors.

Permission required to use Gps Provider is,

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> 
 
 
 
sources from:
 
http://vastinfos.com/2016/07/difference-between-fine-and-coarse-locations-android-gps/

Getting Current Location Using Fused Location API

Let us develop an application to get the current location(last known location) address using Fused Location API Service from Google Play services.


Our Final Output looks like below:



Download code from here


Here we will use Google play services Location APIs (Fused Location Provider) to get the exact last known location(which is nothing but current location) of the device.

Set up Google Play Services: To develop an application using Google Play services APIs, you need to first set up your project with Google Services SDK.
If you haven't installed the Google Play services SDK yet, then follow below steps:

1. Click on SDK Manager icon as shown below




2. Click on Launch Standalone SDK Manager as shown in below figure.



3. Expand Extras and install Google Repository as shown below



4. Add Dependencies to make your app work with Google Play services APIs, and Click on Sync Now after adding dependency.



dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.android.support:appcompat-v7:24.2.1'
    testCompile 'junit:junit:4.12'

    compile 'com.google.android.gms:play-services-location:10.0.1'

}

Note: Be sure you update this version number(10.0.1) each time Google Play services is updated, while posting this blog it is 10.0.1.

You can now begin developing features with Google Play services APIs. 

Selectively compiling APIs: Before 6.5 versions of Google Play services you should compile entire package of
APIs (compile 'com.google.android.gms:play services:10.0.1')into your application. Doing so is difficult to keep the number of methods under 65,536 limit. But you can now include selective api (based on your need).

If you want to work with wearable watches then you can only include wearable related api instead of entire package.

compile 'com.google.android.gms:play-services-wearable:10.0.1'
 
Some of other Individual Google Play services APIs:

1. Google+ :  com.google.android.gms:play-services-plus:10.0.1
2. Google Account Login: com.google.android.gms:play-services-auth:10.0.1

3. Google Actions, Base Client Library:com.google.android.gms:play-services-base:10.0.1
 
4.Google Address API: com.google.android.gms:play-services-identity:10.0.1

5.Firebase App Indexing: com.google.firebase:firebase-appindexing:10.0.1

6. Google Analytics : com.google.android.gms:play-services-analytics:10.0.1

and more....

5. Specifying App Permissions:  Application that needs location services must include either Fine Location or Coarse location permission based on your need.


Note: 

1. See the differences between ACCESS_FINE_LOCATION and ACCESS_COARSE_LOCATION.

2. Location can be determined by two ways:
  1. Using NETWORK_PROVIDER
  2. Using GPS_PROVIDER
follow this for more details.

Let's Create Android Project:


1. Create a new project in Android Studio from File => New =>New Project and fill details.


2. Open Manifest.xml and add below code



<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.currentlocation">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

2. Open values => strings.xml and add the below string values.



<resources>

    <string name="app_name">CurrentLocation</string>
    <string name="latitude">Latitude:</string>
    <string name="longitude">Longitude:</string>

</resources>

3. Open values => colors.xml and add the below code



<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>

    <color name="black">#000000</color>
</resources>

4. add below code under activity_main.xml



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.currentlocation.MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center|start"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/latitude"
            android:textColor="@color/black"
            android:textSize="20dp" />

        <TextView
            android:id="@+id/latitude"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_marginLeft="10dp"
            android:textSize="20dp" />


    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="20dp"
        android:gravity="center|start"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/longitude"
            android:textColor="@color/black"
            android:textSize="20dp" />

        <TextView
            android:id="@+id/longitude"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/latitude"
            android:layout_centerHorizontal="true"
            android:textSize="20dp" />

    </LinearLayout>

</LinearLayout>


5. open MainActivity.java and paste below code:



package com.currentlocation;

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;

public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, ActivityCompat.OnRequestPermissionsResultCallback {

    private GoogleApiClient mGoogleApiClient;
    private Location mLastLocation;
    private TextView latitude, longitude;
    private final int LOCATION_REQUEST_CODE = 100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        latitude = (TextView) findViewById(R.id.latitude);
        longitude = (TextView) findViewById(R.id.longitude);

        //checking runtime permissions

        if (Build.VERSION.SDK_INT > 22) {

            //check run time permssion
            if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

                //PERMISSION IS NOT GRANTED
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_REQUEST_CODE);

                return;
            } else {
                buildGoogleApiClient();
            }

        } else {
            buildGoogleApiClient();
        }
    }

    private void buildGoogleApiClient() {

        // Create an instance of GoogleAPIClient.
        if (mGoogleApiClient == null) {
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .enableAutoManage(this, 0, this)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API) //adding location Service
                    .build();

            mGoogleApiClient.connect();
        }
    }


    @Override
    protected void onStart() {
        super.onStart();
        if (mGoogleApiClient != null) {
            mGoogleApiClient.connect();
        }

    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mGoogleApiClient != null)
            mGoogleApiClient.disconnect();

    }


    @Override
    public void onConnected(@Nullable Bundle bundle) {

        try {
            mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
                    mGoogleApiClient);

            if (mLastLocation != null) {
                latitude.setText(String.valueOf(mLastLocation.getLatitude()));
                longitude.setText(String.valueOf(mLastLocation.getLongitude()));
            }
        } catch (SecurityException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onConnectionSuspended(int i) {

        mGoogleApiClient.connect();
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        switch (requestCode) {

            case LOCATION_REQUEST_CODE:

                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    buildGoogleApiClient();

                } else {

                    if (!ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)) {

                        ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_REQUEST_CODE);
                    }
                }
                break;
        }
    }
}

6. If you run the project, you can see latitude and longitude as shown in the below image.



6. Follow this tutorial to get address using AsyncTask


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