Sunday, 4 October 2015

Fragments

Fragments
  • A Fragment represents a behavior or a portion of user interface in an Activity.
  • You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities.
  • A fragment must always be embedded in an activity and the fragment's lifecycle is directly affected by the host activity's lifecycle.
  • For example, when the activity is paused, so are all fragments in it, and when the activity is destroyed, so are all fragments.
  • You can insert a fragment into your activity layout by declaring the fragment in the activity's layout file, as a <fragment> element, or from your application code by adding it to an existing ViewGroup.

    Example For Fragment



    Fragment Lifecycle


    onAttach():
  • Called when a fragment is first attached to its context.
onCreate():
OnCreateView():
  • The system calls this when it's time for the fragment to draw its user interface for the first time.

  • To draw a UI for your fragment, you must return a View from this method that is the root of your fragment's layout.
    onStart ():
  • Called when the Fragment is visible to the user. This is generally tied to Activity.onStart of the containing Activity's lifecycle.
onResume():
  • The fragment is visible in the running activity.
onPause():
  • Another activity is in the foreground and has focus, but the activity in which this fragment lives is still visible (the foreground activity is partially transparent or doesn't cover the entire screen).
onStop():
  • The fragment is not visible. Either the host activity has been stopped or the fragment has been removed from the activity but added to the back stack. A stopped fragment is still alive (all state and member information is retained by the system). However, it is no longer visible to the user and will be killed if the activity is killed.

    Adding a fragment to an activity
    Usually, a fragment contributes a portion of UI to the host activity, which is embedded as a part of the activity's overall view hierarchy. There are two ways you can add a fragment to the activity layout:

    1. Static Fragment
    2. Dynamic Fragment
      Static Fragment:
      • The android:name attribute in the <fragment> specifies the Fragment class to instantiate in the layout.
      • When the system creates this activity layout, it instantiates each fragment specified in the layout and calls the onCreateView() method for each one, to retrieve each fragment's layout.
      • The system inserts the View returned by the fragment directly in place of the <fragment> element.

      Dynamic Fragment:
      1. At any time while your activity is running, you can add fragments to your activity layout. You simply need to specify a ViewGroup in which to place the fragment.
      2. To make fragment transactions in your activity (such as add, remove, or replace a fragment), you must use APIs from FragmentTransaction.
      3. You can get an instance of FragmentTransaction from your Activity like this:
                       FragmentManager fragmentManager = getFragmentManager();
                       FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
      You can then add a fragment using the add() method, specifying the fragment to add and the    view in which to insert it. For example:

                               ExampleFragment fragment = new ExampleFragment();
                               fragmentTransaction.add(R.id.fragment_container, fragment);
                               fragmentTransaction.commit();

      4.     Once you've made your changes with FragmentTransaction, you must call commit() for the changes to take effect.

       Adding a fragment:
      Add a fragment to the activity state. This fragment may optionally also have its view (if Fragment.onCreateView returns non-null) inserted into a container view of the activity.
      public abstract FragmentTransaction add (int containerViewId, Fragment fragment)
      Parameters:
      containerViewId     Optional identifier of the container this fragment is   to be placed in. If 0, it will not be placed   
                                      in a container.
      fragment                 The fragment to be added. This fragment must not already be added to the activity.
      Returns :
      Returns the same FragmentTransaction instance.

       Committing the fragment transaction:

      1. Schedules a commit of this transaction. The commit does not happen immediately; it will be scheduled as work on the main thread to be done the next time that thread is ready.
      2. A transaction can only be committed with this method prior to its containing activity saving its state.
      3. If the commit is attempted after that point, an exception will be thrown. This is because the state after the commit can be lost if the activity needs to be restored from its state. See commitAllowingStateLoss() for situations where it may be okay to lose the commit.
      4. public abstract int commit ()
      Returns:
      Returns the identifier of this transaction's back stack entry, if addToBackStack(String) had been called. Otherwise, returns a negative number.

       
     
     

Saturday, 3 October 2015

Sending Data to Another Activity


      
In this Post we are going to see how to send the data from one Activity to Another Activity. We have seen how to call another activity in Starting Another Activity and same way we have to create intent object here and
  •    send the data through intent  using putExtra() method.
  •     We can set all primitive data types and non-primitive data types in the intent.
Example:

        Intent intent = new Intent(MainActivity.this, SecActivity.class);
        intent.putExtra(“key”, ”value”);
        intent.putExtra(“int_key”, 45);
        startActivity(intent);

  •     to get the data in second activity we need the same intent object which is used to start the second activity.
  •     To get the intent object we need to call getIntent() which is belongs to Activity class.
  •     to get the data getStringExtra()  method should be called.
  •     Key should be passed as a parameter to get the value for this method.
    Example:

         Intent intent = getIntent();
         String value = getStringExtra(“key”);


This method return the value of an item that previously added with putExtra() or null if no String value was found.


Getting Data From Called Activity:

  •     startActivityForResult() method should be used instead of startActivity() method.
  •     For this method we need to pass two parameter, Intent object and requstcode as integer.
  •     Parameters:
              intent              The intent to start.
  
              requestCode    If >= 0, this code will be returned in onActivityResult(),when  the activity
                                      exits.

    Throws:

              android.content.ActivityNotFoundException

    Example:

       Intent intent = new Intent(MainActivity.this, SecActivity.class);
       startActivityForResult( intent, 1);

  •     In second Activity setResult() method should be called to set the result for the first activity.
  •     Intent object and resultCode as integer should be passed as a parameters.
  •     Parameters
                        resultCode    The result code to propagate back to the originating
                                                activity, often RESULT_CANCELED or RESULT_OK   
                        data               The data to propagate back to the originating activity.   

    Example:
                 
          Intent intent = new Intent();
          intent.putExtra(“name”,”kumar”);
          setResult(RESULT_OK, intent);

  •     To get the data back in the first activity onActivityResult() method should be override.
  •     You will receive this call immediately before onResume() when your activity is re-starting.
  •     This method will have three parameters
      protected void onActivityResult(int requestCode,int resultCode,Intent data)
  •     This method is never invoked if your activity sets noHistory to true in AndroidManifest.xml for the activity tag.
  •     Parameters:
                     requestCode      The integer request code originally supplied to
                                                startActivityForResult(), allowing you to identify who this
                                                result came from.   
                     resultCode         The integer result code returned by the child activity
                                                through its setResult().   
                     data                   An Intent, which can return result data to the caller
                                               (various data can be attached to Intent "extras").
Example:

     @Override
     protected void onActivityResult(int requestCode, int resultCode, Intent data)     

     {
       if (requestCode == 2) {
        if (resultCode == RESULT_OK) {
                  String name = data.getStringExtra( “name” );
        }

       }
     }


Starting other Apps Activity
  • There are two primary forms of intents you will use.   
  • Explicit Intents have specified a component , which provides the exact class to be run. Often these will not include any other information, simply being a way for an application to launch various internal activities it has as the user interacts with the application.
  • Implicit Intents have not specified a component; instead, they must include enough information for the system to determine which of the available components is best to run for that intent. Implicit intents do not declare the class name of the component to start, but instead declare an action to perform.
    Example :
          Intent intent = new Intent( Intent.ACTION_SEND);
          intent.setType(“text/plain”);
          startActivity(intent);


Allowing Other Apps to Start Your Activity
  • To allow other apps to start your activity, you need to add an <intent-filter> element in your manifest file for the corresponding <activity> element.
  • When your app is installed on a device, the system identifies your intent filters and adds the information to an internal catalog of intents supported by all installed apps.
  • When an app calls startActivity() or startActivityForResult() , with an implicit intent, the system finds which activity (or activities) can respond to the intent.
  • The system may send a given Intent to an activity if that activity has an intent filter fulfills the following criteria of the Intent object.
    Action <action> – action to be performed.
    Data <data>        -- A description of the data associated with the intent.

    Example :

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

Friday, 2 October 2015

Java Literals

Literals in Java

A literal is the source code representation of a fixed value.


Literals in Java are a sequence of characters (digits, letters, and other   characters) that represent constant values to be stored in variables .

Java language specifies five major types of literals:

Integer literals

Floating literals

Character literals

String literals

Boolean literals

Literals can be any number, text, or other information that represents a value.  

Integer literals:

Integer data types consist of the following primitive data types: int,long, byte, and short. byte, int, long, and short can be expressed in decimal(base10), hexadecimal(base 16) or octal(base 8) number systems as well.Prefix 0 is used to indicate octal and prefix 0x indicates hexadecimal when using these number systems for literals. 

 
Examples:


int decimal = 100;

int octal = 0144;
int hexa =  0x64;
 

Floating-point literals:

Floating-point numbers are like real numbers in mathematics, for example, 4.13179, -0.000001. Java has two kinds of floating-point numbers: float and double.The default type when you write a floating-point literal is double, but you can designate it explicitly by appending the D (or d) suffix. However, the suffix F (or f) is appended to designate the data type of a floating-point literal as float.

0.0314 *10² (i.e 3.14).
6.5E+32 (or 6.5E32) Double-precision floating-point literal
7D Double-precision floating-point literal
.01f Floating-point literal

Character literals:


char data type is a single 16-bit Unicode character. We can specify a character literal as a single printable character in a pair of single quote characters such as 'a', '#', and '3'. You must know about the ASCII character set. The ASCII character set includes 128 characters including letters, numerals, punctuation etc. Below table shows a set of these special characters.

 Escape  Meaning
 \n  New line
 \t  Tab
 \b  Backspace
 \r  Carriage return
 \f  Formfeed
 \\  Backslash
 \'  Single quotation mark
 \"  Double quotation mark
 \d  Octal
 \xd  Hexadecimal
 \ud  Unicode character



String Literals:

The set of characters in represented as String literals in Java. Always use "double quotes" for String literals. There are few methods provided in Java to combine strings, modify strings and to know whether to strings have the same values.

 ""  The empty string
 "\""  A string containing
 "This is a string"  A string containing 16 characters
 "This is a " + "two-line string"  actually a string-valued constant expression, formed from two string literals

Boolean Literals:

The values true and false are treated as literals in Java programming. When we assign a value to a boolean variable, we can only use these two values.  we can't presume that the value of 1 is equivalent to true and 0 is equivalent to false in Java. We have to use the values true and false to represent a Boolean value. 

Example:
 
boolean chosen = true;
 
* Remember that the literal true is not represented by the quotation marks around it. The Java compiler will take it as a string of characters, if its in quotation marks.





  

 
 
 

 

  

  

Thursday, 1 October 2015

Primitive Data Types

Primitive Data Types

The Java programming language is statically-typed, which means that all variables must first be declared before they can be used. This involves stating the variable's type and name

 int gear = 1;

Doing so tells your program that a field named "gear" exists, holds numerical data, and has an initial value of "1". A variable's data type determines the values it may contain, plus the operations that may be performed on it. In addition to int, the Java programming language supports seven other primitive data types. A primitive type is predefined by the language and is named by a reserved keyword. Primitive values do not share state with other primitive values. The eight primitive data types supported by the Java programming language are: 

  • byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place of int where their limits help to clarify your code; the fact that a variable's range is limited can serve as a form of documentation. 

  • short: The short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive) .
    you can use a short to save memory in large arrays, in situations where the memory savings actually matters. 

     int: By default, the int data type is a 32-bit signed two's complement integer, which has a minimum value of -231 and a maximum value of 231.int data type to represent an unsigned 32-bit integer, which has a minimum value of 0 and a maximum value of 232-1. Use the Integer class to use int data type as an unsigned integer. 

    long: The long data type is a 64-bit two's complement integer. The signed long has a minimum value of -263 and a maximum value of 263-1.long data type to represent an unsigned 64-bit long, which has a minimum value of 0 and a maximum value of 264-1.

    float: The float data type is a single-precision 32-bit .

    double: The double data type is a double-precision 64-bit .

    boolean: The boolean data type has only two possible values: true and false.

    char: The char data type is a single 16-bit Unicode character.  

    In addition to the eight primitive data types listed above, the Java programming language also provides special support for character strings via the java.lang.String class. Enclosing your character string within double quotes will automatically create a new String object; for example, String s = "this is a string";. String objects are immutable, which means that once created, their values cannot be changed. The String class is not technically a primitive data type, but considering the special support given to it by the language, you'll probably tend to think of it as such. 

    Default Values:

    It's not always necessary to assign a value when a field is declared. Fields that are declared but not initialized will be set to a reasonable default by the compiler. this default will be zero or null, depending on the data type.

    The following chart summarizes the default values for the above data types:

    Data Type Default Value (for fields)
    byte 0
    short 0
    int 0
    long 0L
    float 0.0f
    double 0.0d
    char '\u0000'
    String (or any object)   null
    boolean false

    Local variables are slightly different; the compiler never assigns a default value to an uninitialized local variable. If you cannot initialize your local variable where it is declared, make sure to assign it a value before you attempt to use it. Accessing an uninitialized local variable will result in a compile-time error. 

    Difference between datatypes and literals:

    Data types :

    Primitive types are special data types built into the language; they are not objects created from a class 

    Literal : 

    A Literal is the source code representation of a fixed value; literals are represented directly in your code without requiring computation 

    Example: 

    boolean result = true;

    boolean - is data type
    true - is literal

    Next we are going to discuss about Literal .