Senin, 07 Desember 2009

Sample Android Activity,Service ( 1 )

An activity is the equivalent of a Frame/Window in GUI toolkits. It takes up the entire drawable area of the screen. An activity is what gets bound to the AndroidManifest.xml as the main entry point into an application. For long running tasks, it’s best to use a service that talks to this activity.

Service : Activities are meant to display the UI and get input from the user. Services on the other hand keep running for the duration of the user’s ‘session’ on the device.


Activity Navigation:
This has done by the following two ways.
1. Fire and forget – create an event (Intent) and fire it
2. Async callback – create an event (Intent), fire it, and wait for it’s response in a callback method (of the calling-Activity).

Activity history stack
Please note that Android maintains a history stack of all the Activities that have been spawned in an application’s Linux process. In the sample code above, the calling-Activity simply provides the class name of the sub-Activity. When the sub-Activity finishes, it puts it’s result code and any data back on the stack and finishes itself. Since Android maintains the stack, it knows which calling Activity to pass the result back to. The calling-Activity has an onActivityResult method that handles all the callbacks from the sub-Activities. This is pretty confusing at first, since to keep it all straight we have to use CorrelationIds (more on that below).

Example : User wants to navigate Talk application to Browser Application. Using the Browser application wants to serach some photos and saved his local memory. After that he shares the photo with his friend via email application and finally he will come back to the talk application.

Firstly, as the user is talking to his friend, a specific Talk application is opened, which contains the activity manager. System Creates two processes, the main system process and Talk application process. Moreover, before going to Web Browser application, the system saves a Talk state T in order to remember that process. At this point, as a user holds a talk and opens a web browser, the system creates a new process and new web browser activity is launched in it. Again, the state of the last activity is saved.After that, the user browses the internet, finds his picture in Picasa album and saves it to particular folder. He does not close a web browser, instead he opens a folder to find saved picture. The folder activity is launched in particular process.  At this point, the user finds his saved picture in the folder and he creates a request to open an Email application. The last state F is saved. Now assume that the mobile phone is out of the memory and there is no room to create a new process for Email application. Therefore, Android looks to kill a process. It can not destroy Folder process, as it was used previously and could be reused again, so it kills Web Browser process as it is not useful anymore and locates a new Email process instead. The user opens Email application and sends a picture to his friend via email. Now he wants to go back to the Talk application and to resume a talk to his friend. Because of the previously saved states, this work is done fast and easily. In this example, Email application is popped out and the user sees a previous Folder application.Next, the user goes back to Web Browser application. Unfortunately, web browser
process was killed previously so the system has to kill another process (in our case it is Email application process, which is not used anymore) in order to locate Web Browser process and manage the stack memory. Now the user comes back to the Talk application and resumes his talk with his friend. Because of the saved states, going back procedure is fast and useful, because it remembers previous activities and its views.
This example shows, that it does not matter how many applications and processes are active or how much available memory is left, Android it manages fast and without a user interaction.

Fire and forget
For this method we just calls the child activity and flow the process. we are not getting any return value from the child activity. Here intent is just an event. It can have a target of an activity calss along with some date that's passed in via a Bundle.
refer : http://about-android.blogspot.com/2009/12/passing-data-or-parameter-to-another_02.html


1. Create a two Activity [MainActivity & ChildActivity]

Activity : 1 -  MainActivity
 public class MainActivity extends Activity {
     /** Called when the activity is first created. */
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);
     }
}
 
 Activity : 2 - ChildActivity
 public class ChildActivity extends Activity {
     /**
      * @see android.app.Activity#onCreate(Bundle)
      */
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         // TODO Put your code here
     }
 }
 

2.  Define Your Shared collection
    Bundle bundle = new Bundle();
    bundle.putString("sample", "this is the test commands");

3. Call the child Activity from mainactivity with the bundle
    startActivity(new Intent(this, ChildActivity.class).putExtras(bundle));
 
4. Get the Value from MainActivity in ChildActivity
     this.getIntent().getExtras().getString("sample")

5. Toast the Message
    Toast.makeText(this, this.getIntent().getExtras().getString("sample"),
            Toast.LENGTH_LONG).show();



Full Source :MainActivity.java
 
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Bundle bundle = new Bundle();
        bundle.putString("sample", "this is the test commands");
        bundle.putString("sample1", "this is the test commands1");
        startActivity(new Intent(this, ChildActivity.class).putExtras(bundle));
    }
}

-------ChildActivity.java----------
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Toast;

public class ChildActivity extends Activity {
    /**
     * @see android.app.Activity#onCreate(Bundle)
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Toast.makeText(this, this.getIntent().getExtras().getString("sample"),
                Toast.LENGTH_LONG).show();
        Toast.makeText(this, this.getIntent().getExtras().getString("sample1"),
                Toast.LENGTH_LONG).show();
    }
}   
 

Async callback, and correlationId
The calling-Activity has to provide a correlationId/request code to the Intent/event, before firing/raising it. This is then used by the sub-Activity to report it’s results back to the calling-Activity when it’s ready. The calling-Activity does not stop when it spawns the sub-Activity.

Please note that this sub-Activity is not "modal", that is, the calling Activity does not block, when startSubActivity() is called. So if you’re thinking that this is like a modal dialog box, where the calling-Activity will wait for the sub-Activity to produce a result, then you have to think of it differently.


1. Create a two Activity [MainActivity & ChildActivity]

Activity : 1 -  MainActivity
 public class MainActivity extends Activity {
     /** Called when the activity is first created. */
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);
     }
}
 
 Activity : 2 - ChildActivity
 public class ChildActivity extends Activity {
     /**
      * @see android.app.Activity#onCreate(Bundle)
      */
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         // TODO Put your code here
     }
 }
 

2. Call the child Activity from mainactivity with the bundle
    Intent i = new Intent(this, ChildActivity.class);
    startActivityForResult(i, 1);
 
4. Set the Value from ChildActivity To  MainActivity
    setResult(RESULT_OK, new Intent().putExtra("result", "value from Child Activity"));
    finish();

5. Receive the value from ChildActiivity and Print the Message in onActivityResult Method
    if (resultCode == RESULT_OK) {
        String name = data.getStringExtra("result");
        Toast.makeText(this, "You have chosen the City: " + " " + name,
                Toast.LENGTH_LONG).show();
    }

Source Code

MainActivity.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Intent i = new Intent(this, ChildActivity.class);
        startActivityForResult(i, 1);
    }
   
    protected void start(Intent intent) {
        this.startActivityForResult(intent, 1);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
       
               
        if (resultCode == RESULT_OK) {
            String name = data.getStringExtra("result");
            Toast.makeText(this, "You have chosen the Value: " + " " + name,
                    Toast.LENGTH_LONG).show();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

}

ChildActivity.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

public class ChildActivity extends Activity {
    /**
     * @see android.app.Activity#onCreate(Bundle)
     */
    @Override protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Toast.makeText(this, "Child Activity", Toast.LENGTH_LONG).show();       
        setResult(RESULT_OK, new Intent().putExtra("result", "value from Child Activity"));
        finish();
    }
}


Kamis, 03 Desember 2009

Working with Alert / Log / Notification in Android

Here we are discussing about the some essential Source which is helps to track or use the inbuild system call.
1. Toast
    Toast notification are holdes alert message to the user. It does not accept the interaction events. It automatically fades in and out.

System Toast Notification
Activity : 1 -  MainActivity
 public class MainActivity extends Activity {
     /** Called when the activity is first created. */
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);
     }
}
 

2.  Define Toast Object and Message
    // One-line Toast Notification Implementation
    Toast.makeText(this, "Demo Toast", Toast.LENGTH_LONG).show();

    // Change the Notification Position
    Toast myToast = Toast.makeText(this, "Demo Toast", Toast.LENGTH_LONG);
    myToast.setGravity(Gravity.TOP, 100, 100);
    myToast.show();

3. Save and run the Project.

Custom Toast Notification
Activity : 1 -  MainActivity
 public class MainActivity extends Activity {
     /** Called when the activity is first created. */
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);
     }
}


2. Layout : Create a custom Layout with some icon and text message

<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout android:id="@+id/AbsoluteLayout01" android:layout_width="fill_parent" android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
    <ImageView android:id="@+id/ImageView01" android:layout_height="wrap_content"
    android:layout_width="wrap_content" android:layout_y="161dip" android:layout_x="45dip"
    android:background="@drawable/icon"></ImageView>
    <TextView android:layout_width="wrap_content" android:layout_x="131dip"
    android:layout_height="wrap_content" android:layout_y="163dip" android:id="@+id/TextView01"
    android:text="Custom Message"></TextView>
</AbsoluteLayout>

3. Get the Layout View using the LayoutInflator in Activity Class
    LayoutInflater inflater = getLayoutInflater();
    View layout = inflater.inflate(R.layout.custommessage,
        (ViewGroup) findViewById(R.id.AbsoluteLayout01));

4. Define the Toast object with the custom message.
        Toast toast = new Toast(getApplicationContext());
        toast.setDuration(Toast.LENGTH_LONG);
        toast.setGravity(Gravity.TOP | Gravity.LEFT, 100, 100);
        toast.setView(layout);
        toast.show();

5. Save and run the Project.

Full Source
custommessage.xml - Layout
    <?xml version="1.0" encoding="utf-8"?>
    <AbsoluteLayout android:id="@+id/AbsoluteLayout01" android:layout_width="fill_parent" android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">
        <ImageView android:id="@+id/ImageView01" android:layout_height="wrap_content"
        android:layout_width="wrap_content" android:layout_y="161dip" android:layout_x="45dip"
        android:background="@drawable/icon"></ImageView>
        <TextView android:layout_width="wrap_content" android:layout_x="131dip"
        android:layout_height="wrap_content" android:layout_y="163dip" android:id="@+id/TextView01"
        android:text="Custom Message"></TextView>
    </AbsoluteLayout>
    
    
    
MainActivity.java

import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        // One-line Toast Notification Implementation
        Toast.makeText(this, "Demo Toast", Toast.LENGTH_LONG).show();

        // Change the Notification Position
        Toast myToast = Toast.makeText(this, "Demo Toast", Toast.LENGTH_LONG);
        myToast.setGravity(Gravity.TOP, 100, 100);
        myToast.show();

        // Custom Notification
        LayoutInflater inflater = getLayoutInflater();
        View layout = inflater.inflate(R.layout.custommessage,
                (ViewGroup) findViewById(R.id.AbsoluteLayout01));
        Toast toast = new Toast(getApplicationContext());
        toast.setDuration(Toast.LENGTH_LONG);
        toast.setGravity(Gravity.TOP | Gravity.LEFT, 100, 100);
        toast.setView(layout);
        toast.show();

    }
}


Log -
Log Class provides to create a log statement with Key Value Pair.
You can create Log statement using the following steps.
1. Create a Project -> Activity
public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
    }
}
2. Call the d() with Key value pair. ->
    Log.d("@G MYLOG","Sample Log Message");
    Key -> @G MYLOG
    Value->Sample Log Message
    
3. Run and Check the Log.
    Go to Window->Show View -> Android -> Log Cat


    

Source :
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Log.d("@G MYLOG","Sample Log Message");
    }
}


Rabu, 02 Desember 2009

Database Programming in android

Android provides four ways to achieve the persistence.
Preferences - Basically used for storing user preferences for a single application or across applications for a mobile. This is typically name-value pairs accessible to the context.
Databases - Android supports creating of databases based on SQLite db. Each database is private to the applications that creates it
Files - Files can be directly stored on the mobile or on to an extended storage medium. By default other applications cannot access it.
Network - Data can be stored and retrieved from the network too depending on the availability.    

Preference :
Preferences are typically name value pairs. They can be stored as “Shared Preferences” across various activities in an application (note currently it cannot be shared across processes). First we need to put our value in to the context. And the context object lets you retrieve SharedPreferences through the method Context.getSharedPreferences().

1. Make a Shared Preference Collection
2. Retrieve Shared Preference Collection

Make a Shared Preference Collection
    SharedPreferences myPrefs = this.getSharedPreferences("contact", MODE_WORLD_READABLE);
    SharedPreferences.Editor prefsEditor = myPrefs.edit();
    prefsEditor.putString("sample", "this is test commands");
    prefsEditor.commit();


Retrieve Shared Preference Collection
    SharedPreferences myPrefs = this.getSharedPreferences("contact", MODE_WORLD_READABLE);
    prefsEditor.getString("sample", "DEFAULT VALUE")
;


Creating and Using Databases in Android
Every application uses data, and Android applications are no exception. Android uses the open-source, stand-alone SQL database, SQLite. Learn how to create and manipulate a SQLite database for your Android app.

Android uses the SQLite database system, which is an open-source, stand-alone SQL database, widely used by many popular applications.

In Android, the database that you create for an application is only accessible to itself; other applications will not be able to access it. Once created, the SQLite database is stored in the /data/data//databases folder of an Android device. In this article, you will learn how to create and use a SQLite database in Android.

Here we are going to introduce two new class for database programming.
Class 1. Create a SQLiteFactoryManager which is provide the database.
Class 2. Create a DAOHelper which provides CRUD Operation.


Create a SQLiteFactoryManager which is provide the database.
SQLiteFactoryManager is used to create a database and tables
Step 1: Create a SQLConnectionFactory class which extends the SQLiteOpenHelper
        public class SQLConnectionFactory extends SQLiteOpenHelper {

Step 2: Create a database using the SQLiteOpenHelper constructor
        public SQLConnectionFactory(Context context) {
            super(context, DATABASENAME, null, 1);   
        }


Step 3: Create Tables
    db.execSQL(CREATE_USERTABLE);
   

SAMPLE SOURCE   

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.Toast;

public class SQLConnectionFactory extends SQLiteOpenHelper {

    private static final String DATABASENAME = "BIRTHDAY";
    private static final String CREATE_USERTABLE = "CREATE TABLE BIRTHDAY(ID INTEGER NOT NULL CONSTRAINT USER_PK PRIMARY KEY AUTOINCREMENT,NAME TEXT,CATEGORY TEXT,DOB DATE,AGE INTEGER)";
   
    public SQLConnectionFactory(Context context) {
        super(context, DATABASENAME, null, 1);   
    }
   
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_USERTABLE);
        Log.d("@G SQLConnectionFactory", " CREATE_USERTABLE Table ");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }
}


Create a DAOHelper which provides CRUD Operation.
Step1: Get the Factory Object from SQLConnectionFactory.
        factoryObj = new SQLConnectionFactory(c);

Step2: Get the readable/writeable database object using the Factory Object.
        public static SQLiteDatabase getReadableDataBase(Context c) {
            return factoryObj.getReadableDatabase();
        }

        public static SQLiteDatabase getWriteableDataBase(Context c) {
            return factoryObj.getReadableDatabase();
        }


Step 3: Perform the CRUD operation using SQLite query. insertData,removeData,getData.

Sample Code

import java.util.ArrayList;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;
import android.widget.ArrayAdapter;

public class DAOHelper {

    static SQLConnectionFactory factoryObj;
    static SQLiteDatabase database;

    public DAOHelper(Context c) {
        factoryObj = new SQLConnectionFactory(c);
    }

    public static SQLiteDatabase getReadableDataBase(Context c) {
        return factoryObj.getReadableDatabase();
    }

    public static SQLiteDatabase getWriteableDataBase(Context c) {
        return factoryObj.getWriteableDatabase();
    }

    public void insertData(Context c, Object bindValue[]) {
        database = getWriteableDataBase(c);
        SQLiteStatement statement = database
                .compileStatement("SELECT MAX(ID) + 1 FROM BIRTHDAY");
        long taskId = statement.simpleQueryForLong();
        if (taskId <= 0) {
            taskId = 1;
        }
        database.execSQL(
                "INSERT INTO BIRTHDAY(NAME,CATEGORY,DOB) VALUES(?,?,?)",
                bindValue);
    }

    public ArrayList getData(Context c, Object bindValue[]) {
        ArrayList taskNameList = new ArrayList();
        try {
            database = database = getReadableDataBase(c);
            Cursor results = database.rawQuery("SELECT * FROM BIRTHDAY", null);
            if (results.moveToFirst()) {
                for (; !results.isAfterLast(); results.moveToNext()) {
                    taskNameList.add(results.getString(1) + " - "
                            + results.getString(3));
                }
            }
        } catch (Exception e) {
            Log.e("Tasks App", "Unable to to refresh tasks.", e);
        } finally {
            return taskNameList;
        }
    }

    public boolean removeData(Context c, Object bindValue[]) {
        try {
            database = database = getReadableDataBase(c);
            database.execSQL("DELETE FROM BIRTHDAY WHERE ID in (?)", bindValue);
        } catch (Exception e) {
            Log.e("Remove Data", "Unable to to DELETE id.", e);
        } finally {
            return true;
        }
    }

}

Hope this is helpful for you



Passing data or parameter to another Activity Android - 2

Passing data or parameter to another Activity Android - using Bundle
This following step helps to share the content using bundle.
 1. Create a two Activity [MainActivity & ChildActivity]

Activity : 1 -  MainActivity
 public class MainActivity extends Activity {
     /** Called when the activity is first created. */
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);
     }
}

 
 Activity : 2 - ChildActivity
 public class ChildActivity extends Activity {
     /**
      * @see android.app.Activity#onCreate(Bundle)
      */
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         // TODO Put your code here
     }
 }

 

2.  Define Your Shared collection
    Bundle bundle = new Bundle();
    bundle.putString("sample", "this is the test commands");
    bundle.putString("sample1", "this is the test commands1");



3. Call the child Activity from mainactivity with the bundle
    startActivity(new Intent(this, ChildActivity.class).putExtras(bundle));
 
4. Get the Value from MainActivity in ChildActivity
     this.getIntent().getExtras().getString("sample")

5. Toast the Message
    Toast.makeText(this, this.getIntent().getExtras().getString("sample"),
            Toast.LENGTH_LONG).show();
    Toast.makeText(this, this.getIntent().getExtras().getString("sample1"),
        Toast.LENGTH_LONG).show();
 

 
 Full Source :MainActivity.java
 
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Bundle bundle = new Bundle();
        bundle.putString("sample", "this is the test commands");
        bundle.putString("sample1", "this is the test commands1");
        startActivity(new Intent(this, ChildActivity.class).putExtras(bundle));
    }
}

-------ChildActivity.java----------
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Toast;

public class ChildActivity extends Activity {
    /**
     * @see android.app.Activity#onCreate(Bundle)
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Toast.makeText(this, this.getIntent().getExtras().getString("sample"),
                Toast.LENGTH_LONG).show();
        Toast.makeText(this, this.getIntent().getExtras().getString("sample1"),
                Toast.LENGTH_LONG).show();
    }
}

Passing data or parameter to another Activity Android

In this blog we have discussed shared preference and bundle collection. We can pass the value from parent activity to child activity using the bundled collection and shared preference.
1. Shared Preference
2. Bundle Collection

Shared Preference
Preferences are typically name value pairs. They can be stored as “Shared Preferences” across various activities in an application (note currently it cannot be shared across processes). First we need to put our value in to the context. And the context object lets you retrieve SharedPreferences through the method Context.getSharedPreferences().

1. Make a Shared Preference Collection
2. Retrieve Shared Preference Collection

Make a Shared Preference Collection
    SharedPreferences myPrefs = this.getSharedPreferences("contact", MODE_WORLD_READABLE);
    SharedPreferences.Editor prefsEditor = myPrefs.edit();
    prefsEditor.putString("sample", "this is test commands");
    prefsEditor.commit();

Retrieve Shared Preference Collection
    SharedPreferences myPrefs = this.getSharedPreferences("contact", MODE_WORLD_READABLE);
    prefsEditor.getString("sample", "DEFAULT VALUE");


 1. Create a two Activity [MainActivity & ChildActivity]
 
Activity : 1 -  MainActivity
 public class MainActivity extends Activity {
     /** Called when the activity is first created. */
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);
     }
}

 
 Activity : 2 - ChildActivity
 
public class ChildActivity extends Activity {
     /**
      * @see android.app.Activity#onCreate(Bundle)
      */
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         // TODO Put your code here
     }
 }

 

2.  Define Your Shared collection
    SharedPreferences myPrefs = this.getSharedPreferences("contact", MODE_WORLD_READABLE);
        SharedPreferences.Editor prefsEditor = myPrefs.edit();
        prefsEditor.putString("sample", "this is test commands");
        prefsEditor.commit();   
   

3. Call the child Activity from mainactivity
   
startActivity(new Intent(this,ChildActivity.class));
 
4. Get the Value from MainActivity in ChildActivity
 
    SharedPreferences myPrefs = this.getSharedPreferences("contact", MODE_WORLD_READABLE);

5. Toast the Message
  
  Toast.makeText(this, myPrefs.getString("sample", "DEFAULT VALUE"), Toast.LENGTH_LONG).show();   
 
 
 Full Source :MainActivity.java
 
 import android.app.Activity;
 import android.content.Intent;
 import android.content.SharedPreferences;
 import android.os.Bundle;
 
 public class MainActivity extends Activity {
     /** Called when the activity is first created. */
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);
         SharedPreferences myPrefs = this.getSharedPreferences("contact", MODE_WORLD_READABLE);
         SharedPreferences.Editor prefsEditor = myPrefs.edit();
         prefsEditor.putString("sample", "this is test commands");
         prefsEditor.commit();       
         startActivity(new Intent(this,ChildActivity.class));
     }
}

-------ChildActivity.java----------
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Toast;

public class ChildActivity extends Activity {
    /**
     * @see android.app.Activity#onCreate(Bundle)
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        SharedPreferences myPrefs = this.getSharedPreferences("contact", MODE_WORLD_READABLE);
        Toast.makeText(this, myPrefs.getString("sample", "DEFAULT VALUE"), Toast.LENGTH_LONG).show();       
    }
}