Category Archives: Courses

Auto-complete Text View

Auto-complete text view is an edit text that shows a list of suggestions automatically when the user is typing the list of suggestions is displayed in a drop-down menu, the user can choose an item from the drop-down list to replace the content of auto-complete text view.

followings are the attributes of Auto-complete text view:-

  1. android:completionHint :- this defines the hint which is to be displayed in the drop-down menu.
  2. android:completionHintView:– this defines the hint view displays in the drop-down menu.
  3. android:completionThreshhold:- this defines the number of characters that the user must type before completion suggestions are displayed in the drop-down menu.
  4. android:dropDownAnchor:- this is the view to anchor the auto-complete drop-down tool.
  5. android:dropDownHeight:- this specifies basic height of drop-down menu.
  6. android:dropDownHorizontaloffset:- this specifies the amount of pixels by which the drop-down should be off set horizontally.
  7. android:dropDownselector:- this specifies a selector in a drop down list.
  8. android:dropDownVerticaloffset:- this specifies the amount of pixels by off set vertically.
  9. android:dropDownWIdth:- this specifies the basic width of the drop down.
  10. android:popupBackground:- this sets the background of the pop-up.

example of auto-complete text view:-

  .xml file :- 

RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" >

<TextView android:id="@+id/textView1" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:layout_alignParentLeft="true" 
android:layout_alignParentTop="true" 
android:layout_marginTop="15dp" 
android:layout_marginLeft="36dp" 
android:text="what is your favourite programming language" /> 

<AutoCompleteTextView android:id="@+id/autoCompleteTextView1" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:layout_alignParentLeft="true" 
android:layout_below="@+id/textView1" 
android:layout_marginLeft="36dp" 
android:layout_marginTop="17dp" 
android:ems="10" 
android:text=""> 

<requestFocus /> 
</AutoCompleteTextView>

</RelativeLayout>

   .java file:- 

package com.coreprogrammers.autocompletetextviewdemo;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;


public class MainActivity extends Activity 
{

String[] language ={"C","C++","Java",".NET","iPhone","Android","ASP.NET","PHP","Matlab","R Programming","oracle","My Sql"}; 
@Override 
protected void onCreate(Bundle savedInstanceState) 
{ 
super.onCreate(savedInstanceState); 
setContentView(R.layout.activity_main); 

//Creating the instance of ArrayAdapter containing list of language names 
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.select_dialog_item,language); 


//Getting the instance of AutoCompleteTextView 
AutoCompleteTextView autoCompleteTextView1= (AutoCompleteTextView)findViewById(R.id.autoCompleteTextView1); 

autoCompleteTextView1.setThreshold(2);//will start working from first character 
autoCompleteTextView1.setAdapter(adapter);//setting the adapter data into the AutoCompleteTextView 

autoCompleteTextView1.setTextColor(Color.RED); 
}
}

 

 

 

Sound Programming with PC Speaker Using C Language

If we connect a timer with PC speaker, it will produce sound. We can connect PIT with
PC speakers to get the required sound. The output port of speaker is 61h. bit0 of port 61h is used
to enable timer to supply clock signal to speaker i.e. connects PIT with speaker.

Now let’s write our own sound( ) and nosound( ) function to produce sound.

#define ON
#define OFF
(1)
(0)
/*------------------------------------------------
ChangeSpeaker - Turn speaker on or off.
*/
void ChangeSpeaker( int status )
{
int portval;
portval = inportb( 0x61 );
if ( status==ON )
portval |= 0x03;

else
portval &=~ 0x03;
outportb( 0x61, portval );
} /*--ChangeSpeaker( )----------*/
void Sound( int hertz )
{
unsigned divisor = 1193180L / hertz;

ChangeSpeaker( ON );
outportb(
outportb(
outportb(
} /*--Sound(
0x43, 0xB6 );
0x42, divisor & 0xFF ) ;
0x42, divisor >> 8 ) ;
)-----*/
void NoSound( void )
{
ChangeSpeaker( OFF );
} /*--NoSound( )------*/

int main( void )
{
Sound( 355 );
delay( 1000 );
Sound( 733 );
delay( 1000 );
NoSound( );
return(0);
} /*--main( )-------*/

 

Flowchart to check whether the input no is Prime or Not

flowchartprimeornot

Flowchart’s Symbol

1. Terminal:-

terminal1terminal2

This Symbol represents the beginning (Start) and ending (Stop) in the Program Logic flow.

2. Input/Output:-

inputoutput

 

 

 

 

This Symbol denotes any function of Input/Output device in the program. Any Instruction which is input from keyboard,CD etc, is shown in this symbol. Any output instruction sending result to printer,mointor is shown in this box.

3. Process:-

process

This is used to represent airthmetic and data movement instructions. Operations like addition, subtraction etc is shown in this box. The logical process of moving data from one memory location to another is also shown here.

4. Decision:-

decision

This indicates a point where a decision has to be made.

5. Connector:-

connector

If flowchart becomes very long and the flow lines start crossing with each other,this symbol is used to avoid confusion.

6. Flow-Lines:-

flowlines

Arrow-headed lines indicate the flow of operation. It represents the sequence in which the instructions are to be executed.

List of screen resolutions for all Android based phones and tablets

These are the sizes. Try to take a look in Supporting Mutiple Screens

320dp: a typical phone screen (240×320 ldpi,320×480 mdpi,480×800 hdpi, etc).480dp: a tweener tablet like the Streak(480×800 mdpi).600dp: a 7” tablet (600×1024 mdpi).720dp: a 10” tablet (720×1280 mdpi,800×1280 mdpi, etc).

Some times developers use this to make more than one layout:
res/layout/main_activity.xml # For handsets (smaller than 600dp available width)
res
/layoutsw600dp/main_activity.xml # For 7” tablets (600dp wide and bigger)
res
/layoutsw720dp/main_activity.xml # For 10” tablets (720dp wide and bigger)

 

The success of Android as a mobile device Operating System (OS) has resulted in a large variety of screen sizes and resolutions. Here is provided a list of example devices to show that variation.

 

phoneportraitvlandscape

In the following table we try to show each and every  resolution for Android Devices . As such the width in pixels is the X-axis and the length or height in pixels is the Y-axis. Obviously that swaps when the device is held in landscape orientation. Android has support for both orientations so that a correctly programmed App will work no matter which way you hold the device.  The total number of pixels in a screen is the number in the x-axis multiplied by the number in the y-axis. The more pixels for each square inch (or centimetre) of display the sharper any images will be displayed (provided those images are at a high resolution).

The Size column next to each device is the diagonal measurement for the device screen in inches. This table illustrates that screens with the same resolution can be different sizes.

 

Device Inches ResolutionPX Density OR Acronym DPI ResolutionDP AspectRatios SysNavYorN ContentResolutionDP
——————————— ——————————— ——————————— ——————————— ——————————— ——————————— ——————————— ——————————— ———————————
Galaxy Y 320 x 240 ldpi   0.75 120 427 x 320 4:3   1.3333 427 x 320
? 400 x 240 ldpi   0.75 120 533 x 320 5:3   1.6667 533 x 320
? 432 x 240 ldpi   0.75 120 576 x 320 9:5   1.8000 576 x 320
Galaxy Ace 480 x 320 mdpi   1 160 480 x 320 3:2   1.5000 480 x 320
Nexus S 800 x 480 hdpi   1.5 240 533 x 320 5:3   1.6667 533 x 320
“Galaxy SIII Mini” 800 x 480 hdpi   1.5 240 533 x 320 5:3   1.6667 533 x 320
? 854 x 480 hdpi   1.5 240 569 x 320 427:240   1.7792 569 x 320
Galaxy SIII 1280 x 720 xhdpi   2 320 640 x 360 16:9   1.7778 640 x 360
Galaxy Nexus 1280 x 720 xhdpi   2 320 640 x 360 16:9   1.7778 640 x 360
HTC One X 4.7″ 1280 x 720 xhdpi   2 320 640 x 360 16:9   1.7778 640 x 360
Nexus 5 5″ 1920 x 1080 xxhdpi   3 480 640 x 360 16:9   1.7778 YES 592 x 360
Galaxy S4 5″ 1920 x 1080 xxhdpi   3 480 640 x 360 16:9   1.7778 640 x 360
HTC One 5″ 1920 x 1080 xxhdpi   3 480 640 x 360 16:9   1.7778 640 x 360
Galaxy Note III 5.7″ 1920 x 1080 xxhdpi   3 480 640 x 360 16:9   1.7778 640 x 360
HTC One Max 5.9″ 1920 x 1080 xxhdpi   3 480 640 x 360 16:9   1.7778 640 x 360
Galaxy Note II 5.6″ 1280 x 720 xhdpi   2 320 640 x 360 16:9   1.7778 640 x 360
Nexus 4 4.4″ 1200 x 768 xhdpi   2 320 600 x 384 25:16   1.5625 YES 552 x 384
——————————— ——————————— ——————————— ——————————— ——————————— ——————————— ——————————— ——————————— ———————————
Device Inches ResolutionPX Density DPI ResolutionDP AspectRatios SysNavYorN ContentResolutionDP
——————————— ——————————— ——————————— ——————————— ——————————— ——————————— ——————————— ——————————— ———————————
? 800 x 480 mdpi   1 160 800 x 480 5:3   1.6667 800 x 480
? 854 x 480 mdpi   1 160 854 x 480 427:240   1.7792 854 x 480
Galaxy Mega 6.3″ 1280 x 720 hdpi   1.5 240 853 x 480 16:9   1.7778 853 x 480
Kindle Fire HD 7″ 1280 x 800 hdpi   1.5 240 853 x 533 8:5   1.6000 853 x 533
Galaxy Mega 5.8″ 960 x 540 tvdpi   1.33333 213.333 720 x 405 16:9   1.7778 720 x 405
Sony Xperia Z Ultra 6.4″ 1920 x 1080 xhdpi   2 320 960 x 540 16:9   1.7778 960 x 540
Kindle Fire (1st & 2nd gen) 7″ 1024 x 600 mdpi   1 160 1024 x 600 128:75   1.7067 1024 x 600
Tesco Hudl 7″ 1400 x 900 hdpi   1.5 240 933 x 600 14:9   1.5556 933 x 600
Nexus 7 (1st gen/2012) 7″ 1280 x 800 tvdpi   1.33333 213.333 960 x 600 8:5   1.6000 YES 912 x 600
Nexus 7 (2nd gen/2013) 7″ 1824 x 1200 xhdpi   2 320 912 x 600 38:25   1.5200 YES 864 x 600
Kindle Fire HDX 7″ 1920 x 1200 xhdpi   2 320 960 x 600 8:5   1.6000 960 x 600
? 800 x 480 ldpi   0.75 120 1067 x 640 5:3   1.6667 1067 x 640
? 854 x 480 ldpi   0.75 120 1139 x 640 427:240   1.7792 1139 x 640
Kindle Fire HD 8.9″ 1920 x 1200 hdpi   1.5 240 1280 x 800 8:5   1.6000 1280 x 800
Kindle Fire HDX 8.9″ 2560 x 1600 xhdpi   2 320 1280 x 800 8:5   1.6000 1280 x 800
Galaxy Tab 2 10″ 1280 x 800 mdpi   1 160 1280 x 800 8:5   1.6000 1280 x 800
Galaxy Tab 3 10″ 1280 x 800 mdpi   1 160 1280 x 800 8:5   1.6000 1280 x 800
ASUS Transformer 10″ 1280 x 800 mdpi   1 160 1280 x 800 8:5   1.6000 1280 x 800
ASUS Transformer 2 10″ 1920 x 1200 hdpi   1.5 240 1280 x 800 8:5   1.6000 1280 x 800
Nexus 10 10″ 2560 x 1600 xhdpi   2 320 1280 x 800 8:5   1.6000 1280 x 800
Galaxy Note 10.1 10″ 2560 x 1600 xhdpi   2 320 1280 x 800 8:5   1.6000 1280 x 800
Dell Aero 3.5″ 360 X 640 nHD   —
Motorola Pro+ MB632 3.1″ 480 X 640 VGA   —
——————————— ——————————— ——————————— ——————————— ——————————— ——————————— ——————————— ——————————— ———————————
Device Inches ResolutionPX Density DPI ResolutionDP AspectRatios SysNavYorN ContentResolutionDP

Android Global Variables/Application Context Variable

In this example we are going to learn to define variables in application context and we can use this variables as a Global variable. We can set values in this variables  and get values on any activity / broadcast recieiver / service in application context(environment).

The challenge is how to save values across several Activities and all parts of your application context. We can achieve this by creating static variable but it is not a good way as it will causes memory leaks. The solution for this in Android is to associate your variable with the Application context.

Every Application has a context, and Android guarantees that Application context will exist as a instance across your application.

The way to do this is to create a class and extends with android.app.Application, and specify your class in the application tag in your AndroidManifest.xml file. Android will create an instance of that class and make it available for your entire application context. We can get object of our class on any activity / broadcast reciever / service in application context(environment) by Context.getApplicationContext() method.

Now lets create a project to understand variables under Application Context:-

Create a class named AuthenticationDetails.java and extent it with ‘Application’ our custom class should be subclass of android.app.Application class. We will use this class as global class for your Application environment(Conext).

AuthenticationDetails.java

package com.coreprogrammers.model;

import android.app.Application;

public class AuthenticationDetails extends Application
{
	private String id;
	private String name;
	private String company;
	private String username;
	private String password;
	private String s3_key;
	private String s3_secret;
	private String api_key;
	private String license;
	private String timezone;
	private String tied_to;
	private String app;
	private String paypal;
	private String cron;
	private String cron_ares;
	private String send_rate;
	private String language;
	private String cron_csv;
	private String login_in;

	public void setid(String strid) 
	{
		this.id = strid;
	}

	public String getid() 
	{
		return id;
	}

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

	public String getname() 
	{
		return name;
	}

	public void setcompany(String strcompany) 
	{
		this.company = strcompany;
	}

	public String getcompany() 
	{
		return company;
	}

	public void setusername(String strusername) 
	{
		this.username = strusername;
	}

	public String getusername() 
	{
		return username;
	}

	public void setpassword(String strpassword) 
	{
		this.password = strpassword;
	}

	public String getpassword() 
	{
		return password;
	}

	public void sets3_key(String strs3_key) 
	{
		this.s3_key = strs3_key;
	}

	public String gets3_key() 
	{
		return s3_key;
	}

	public void sets3_secret(String strs3_secret) 
	{
		this.s3_secret = strs3_secret;
	}

	public String gets3_secret() 
	{
		return s3_secret;
	}

	public void setapi_key(String strapi_key) 
	{
		this.api_key = strapi_key;
	}

	public String getapi_key() 
	{
		return api_key;
	}

	public void setlicense(String strlicense) 
	{
		this.license = strlicense;
	}

	public String getlicense() 
	{
		return license;
	}

	public void settimezone(String strtimezone) 
	{
		this.timezone = strtimezone;
	}

	public String gettimezone() 
	{
		return timezone;
	}

	public void settied_to(String strtied_to) 
	{
		this.tied_to = strtied_to;
	}

	public String gettied_to() 
	{
		return tied_to;
	}

	public void setapp(String strapp) 
	{
		this.app = strapp;
	}

	public String getapp() 
	{
		return app;
	}

	public void setpaypal(String strpaypal) 
	{
		this.paypal = strpaypal;
	}

	public String getpaypal() 
	{
		return paypal;
	}

	public void setcron(String strcron) 
	{
		this.cron = strcron;
	}

	public String getcron() 
	{
		return cron;
	}

	public void setcron_ares(String strcron_ares) 
	{
		this.cron_ares = strcron_ares;
	}

	public String getcron_ares() 
	{
		return cron_ares;
	}

	public void setsend_rate(String strsend_rate) 
	{
		this.send_rate = strsend_rate;
	}

	public String getsend_rate() 
	{
		return send_rate;
	}

	public void setlanguage(String strlanguage) 
	{
		this.language = strlanguage;
	}

	public String getlanguage() 
	{
		return language;
	}

	public void setcron_csv(String strcron_csv) 
	{
		this.cron_csv = strcron_csv;
	}

	public String getcron_csv() 
	{
		return cron_csv;
	}

	public void setlogin_in(String strlogin_in) 
	{
		this.login_in = strlogin_in;
	}

	public String getlogin_in() 
	{
		return login_in;
	}	
}

 

Now We are going to create  AndroidManifest.xml.

In AndroidManifest file we will Assign AuthenticationDetails.java in application tag, see this line in application tag android:name=”com.coreprogrammers.model.AuthenticationDetails” . After assign we can get AuthenticationDetails.java instance on any activity / broadcast reciever / service in application context.

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

    <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="19" />

    <application
        android:name="com.coreprogrammers.model.AuthenticationDetails"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.coreprogrammers.model.FirstScreen"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

        </activity>

        <activity android:name="com.coreprogrammers.model.SecondScreen" ></activity>  
        <activity android:name="com.coreprogrammers.model.ThirdScreen" ></activity>
    </application>

</manifest>

Now we will show how to use the global variables across three activities

1) FirstScreen.java

getApplicationContext() method of Context will give AuthenticationDetails.java instance and set id/name values and maintain state of AuthenticationDetails.java instance.

package com.coreprogrammers.model;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.app.Activity;
import android.content.Intent;

public class FirstScreen extends Activity 
{

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

        final Button secondBtn = (Button) findViewById(R.id.second);

        // Calling Application class (see application tag in AndroidManifest.xml)
        final AuthenticationDetails _objAuthenticationDetails = (AuthenticationDetails) getApplicationContext();

        //Set name and id in global/application context
        _objAuthenticationDetails.setname("Coreprogrammers");
        _objAuthenticationDetails.setid("Rocks");

        secondBtn.setOnClickListener(new OnClickListener() 
        {
            public void onClick(View v) 
            {
                Intent i = new Intent(getBaseContext(), SecondScreen.class);
                startActivity(i);
            }
        }); 
    }   
}

 

2) SecondScreen.java

We have to Call getApplicationContext() method of Context and get AuthenticationDetails.java instance , By AuthenticationDetails.java instance we can get set values for name/id variables.

package com.coreprogrammers.model;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class SecondScreen extends Activity 
{

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.secondscreen); 

        TextView showGlobal = (TextView) findViewById(R.id.showGlobal);
        final Button thirdBtn = (Button) findViewById(R.id.third);

        // Calling Application class (see application tag in AndroidManifest.xml)
        final AuthenticationDetails _objAuthenticationDetails = (AuthenticationDetails) getApplicationContext();

        // Get name and id from global/application context
        final String name  = _objAuthenticationDetails.getname();
        final String id = _objAuthenticationDetails.getid();

        String showString = "Name= : "+ name + "ID : "+ id;

        // Show name/email values in TextView
        showGlobal.setText(showString);

        thirdBtn.setOnClickListener(new OnClickListener()
        {
            public void onClick(View v) 
            {
                Intent i = new Intent(getBaseContext(), ThirdScreen.class);
                startActivity(i);
            }
        });

    } 

    @Override
    protected void onDestroy() 
    {
        super.onDestroy();
    }
}

 

3) ThirdScreen.java

Now we will call getApplicationContext() method of Context and get AuthenticationDetails.java instance , By AuthenticationDetails.java instance we can get and set values for name/id variables.

package com.coreprogrammers.model;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class ThirdScreen extends Activity 
{

    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.thirdscreen); 

        TextView showGlobal = (TextView) findViewById(R.id.showGlobal);

        // Calling Application class (see application tag in AndroidManifest.xml)
        final AuthenticationDetails _objAuthenticationDetails = (AuthenticationDetails) getApplicationContext();

        // Get name and email from global/application context
        final String name  = _objAuthenticationDetails.getname();
        final String id = _objAuthenticationDetails.getid();

        String showString = "Name= "+ name +" "+ "ID= "+ id;

        // Show name/id values in TextView
        showGlobal.setText(showString);

    } 
}

Happy Programming :-)

 

Android Fragments Part-3 (Adding a user interface)

A fragment is usually used as part of an activity’s user interface and contributes its own layout to the activity.

To provide a layout for a fragment, we must implement the onCreateView() callback method, which the Android system calls when it’s time for the fragment to draw its layout. Our implementation of this method must return a View  that is the root of our fragment’s layout.

Note: If the fragment is a subclass of ListFragment, the default implementation returns a ListView from onCreateView(), so we don’t need to implement it.

To return a layout from onCreateView(), we can inflate it from a layout resource defined in XML. To help you do so, onCreateView() provides a LayoutInflater object.

For example, here’s a subclass of Fragment that loads a layout from the fragment_example.xml file:-

public static class FragmentExample extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_example, container, false);
    }
}

How to Create a layout

In the sample above,R.layout.fragment_example is a reference to a layout resource named fragment_example.xml saved in the application resources.

Explanation:-

The container parameter passed to onCreateView() is the parent ViewGroup (from the activity’s layout) in which your fragment layout will be inserted. The savedInstanceState parameter is a Bundle that provides data about the previous instance of the fragment, if the fragment is being resumed .

The inflate() method takes three arguments:

  • The resource ID of the layout you want to inflate.
  • The ViewGroup to be the parent of the inflated layout. Passing the container is important in order for the system to apply layout parameters to the root view of the inflated layout, specified by the parent view in which it’s going.
  • A boolean indicating whether the inflated layout should be attached to the ViewGroup (the second parameter) during inflation. (In this case, this is false because the system is already inserting the inflated layout into the container—passing true would create a redundant view group in the final layout.)

Now we’ve seen how to create a fragment that provides a layout. Next, we now need to add the fragment to our activity. We will learn to add the fragment to the activity in our next Tutorial  Android Fragments Part-4

Android Fragments Part-2 (Types Of Fragments)

There are some few subclasses that you might want to extend, instead of the base Fragment class:

DialogFragment
Displays a floating dialog. Using this class to create a dialog is a good alternative to using the dialog helper methods in the Activity class, because you can incorporate a fragment dialog into the back stack of fragments managed by the activity, allowing the user to return to a dismissed fragment.
ListFragment
Displays a list of items that are managed by an adapter (such as a SimpleCursorAdapter), similar to ListActivity. It provides several methods for managing a list view, such as the onListItemClick() callback to handle click events.
PreferenceFragment
Displays a hierarchy of Preference objects as a list, similar to PreferenceActivity. This is useful when creating a “settings” activity for your application.

Android Fragments Part-1

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. You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own input events, and which you can add or remove while the activity is running (sort of like a “sub activity” that you can reuse in different activities).

A fragment must always be embedded in an activity and the fragment’s lifecycle is directly affected by the host activity’s lifecycle. For example, when the activity is paused, so are all fragments in it, and when the activity is destroyed, so are all fragments. However, while an activity is running (it is in the resumed lifecycle state), you can manipulate each fragment independently, such as add or remove them. When you perform such a fragment transaction, you can also add it to a back stack that’s managed by the activity—each back stack entry in the activity is a record of the fragment transaction that occurred. The back stack allows the user to reverse a fragment transaction (navigate backwards), by pressing the Back button.

When you add a fragment as a part of your activity layout, it lives in a ViewGroup inside the activity’s view hierarchy and the fragment defines its own view layout. 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. However, a fragment is not required to be a part of the activity layout; you may also use a fragment without its own UI as an invisible worker for the activity.

This document describes how to build your application to use fragments, including how fragments can maintain their state when added to the activity’s back stack, share events with the activity and other fragments in the activity, contribute to the activity’s action bar, and more.

 

Fragment Design

Android introduced fragments in Android 3.0 (API level 11), primarily to support more dynamic and flexible UI designs on large screens, such as tablets. Because a tablet’s screen is much larger than that of a handset, there’s more room to combine and interchange UI components. Fragments allow such designs without the need for you to manage complex changes to the view hierarchy. By dividing the layout of an activity into fragments, you become able to modify the activity’s appearance at runtime and preserve those changes in a back stack that’s managed by the activity.

For example, a news application can use one fragment to show a list of articles on the left and another fragment to display an article on the right—both fragments appear in one activity, side by side, and each fragment has its own set of lifecycle callback methods and handle their own user input events. Thus, instead of using one activity to select an article and another activity to read the article, the user can select an article and read it all within the same activity, as illustrated in the tablet layout in figure 1.

You should design each fragment as a modular and reusable activity component. That is, because each fragment defines its own layout and its own behavior with its own lifecycle callbacks, you can include one fragment in multiple activities, so you should design for reuse and avoid directly manipulating one fragment from another fragment. This is especially important because a modular fragment allows you to change your fragment combinations for different screen sizes. When designing your application to support both tablets and handsets, you can reuse your fragments in different layout configurations to optimize the user experience based on the available screen space. For example, on a handset, it might be necessary to separate fragments to provide a single-pane UI when more than one cannot fit within the same activity.

fragments    This Figure shows an example of how two UI modules defined by fragments can be combined into one activity for a tablet design, but separated for a handset design.

Fragment Life-Cycle

fragment_lifecycle

The life-cycle of a fragment is connected to the life-cycle of its hosting activity.

To create a fragment, you must create a subclass of Fragment (or an existing subclass of it). The Fragment class has code that looks a lot like an Activity. It contains callback methods similar to an activity, such as onCreate(), onStart(), onPause(), and onStop(). In fact, if you’re converting an existing Android application to use fragments, you might simply move code from your activity’s callback methods into the respective callback methods of your fragment.

Usually, you should implement at least the following lifecycle methods:

onCreate()
The system calls this when creating the fragment. Within your implementation, you should initialize essential components of the fragment that you want to retain when the fragment is paused or stopped, then resumed.
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. You can return null if the fragment does not provide a UI.
onPause()
The system calls this method as the first indication that the user is leaving the fragment (though it does not always mean the fragment is being destroyed). This is usually where you should commit any changes that should be persisted beyond the current user session (because the user might not come back).

Most applications should implement at least these three methods for every fragment, but there are several other callback methods you should also use to handle various stages of the fragment lifecycle. We will discuss more about Fragments in our Next(Android Fragments Part-2) Tutorial.

 

Happy Programming :-)

 

 

Windows Azure Blob storage

What is Blob Storage

Windows Azure Blob storage is a service for storing large amounts of unstructured data that can be accessed from anywhere in the world via HTTP or HTTPS. A single blob can be hundreds of gigabytes in size, and a single storage account can contain up to 200TB of blobs if it was created on June 8th, 2012, or later; storage accounts created prior to that date can contain up to 100TB of blobs.

Common uses of Blob storage include:

  • Serving images or documents directly to a browser
  • Storing files for distributed access
  • Streaming video and audio
  • Performing secure backup and disaster recovery
  • Storing data for analysis by an on-premises or Windows Azure-hosted service

You can use Blob storage to expose data publicly to the world or privately for internal application storage.

Concepts

The Blob service contains the following components:

Blob1

  • Storage Account: All access to Windows Azure Storage is done through a storage account.
  • Container: A container provides a grouping of a set of blobs. All blobs must be in a container. An account can contain an unlimited number of containers. A container can store an unlimited number of blobs.
  • Blob: A file of any type and size. There are two types of blobs that can be stored in Windows Azure Storage: block and page blobs. Most files are block blobs. A single block blob can be up to 200GB in size.
  • URL format: Blobs are addressable using the following URL format:
  • http://<storage account>.blob.core.windows.net/<container>/<blob>
  • The following example URL could be used to address one of the blobs in the diagram above:
    http://coreprogrammers.blob.core.windows.net/images/image1.jpg
Skip to toolbar