Monday, September 2, 2013

VideoView Part2


MainActivity.Java


package com.example.videoview;

import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.widget.MediaController;
import android.widget.VideoView;

public class MainActivity extends Activity {

VideoView videoView;
String videoUrl;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);  
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,   
                                WindowManager.LayoutParams.FLAG_FULLSCREEN);  
setContentView(R.layout.activity_main);
videoView = (VideoView)findViewById(R.id.videoView);
/* String SrcPath = "rtsp://v5.cache1.c.youtube.com/CjYLENy73wIaLQnhycnrJQ8qmRMYESARFEIJbXYtZ29vZ2xlSARSBXdhdGNoYPj_hYjnq6uUTQw=/0/0/0/video.3gp";

videoView.setVideoURI(Uri.parse(SrcPath));
      videoView.setMediaController(new MediaController(this));
      videoView.requestFocus();
      videoView.start();*/
new YourAsyncTask().execute();
}

private class YourAsyncTask extends AsyncTask<Void, Void, Void>
    {
        ProgressDialog progressDialog;

        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
            progressDialog = ProgressDialog.show(MainActivity.this, "", "Loading Video wait...", true);
        }

        @Override
        protected Void doInBackground(Void... params)
        {
            try
            {
                String url = "http://www.youtube.com/watch?v=OtLa7wDpuOU";
                videoUrl = getUrlVideoRTSP(url);
                Log.e("Video url for playing=========>>>>>", videoUrl);
            }
            catch (Exception e)
            {
                Log.e("Login Soap Calling in Exception", e.toString());
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result)
        {
            super.onPostExecute(result);
            progressDialog.dismiss();
/*
            videoView.setVideoURI(Uri.parse("rtsp://v4.cache1.c.youtube.com/CiILENy73wIaGQk4RDShYkdS1BMYDSANFEgGUgZ2aWRlb3MM/0/0/0/video.3gp"));
            videoView.setMediaController(new MediaController(AlertDetail.this));
            videoView.requestFocus();
            videoView.start();*/            
            videoView.setVideoURI(Uri.parse(videoUrl));
            MediaController mc = new MediaController(MainActivity.this);
            videoView.setMediaController(mc);
            videoView.requestFocus();
            videoView.start();          
            mc.show();
        }

    }

public static String getUrlVideoRTSP(String urlYoutube)
    {
        try
        {
            String gdy = "http://gdata.youtube.com/feeds/api/videos/";
            DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            String id = extractYoutubeId(urlYoutube);
            URL url = new URL(gdy + id);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            Document doc = documentBuilder.parse(connection.getInputStream());
            Element el = doc.getDocumentElement();
            NodeList list = el.getElementsByTagName("media:content");///media:content
            String cursor = urlYoutube;
            for (int i = 0; i < list.getLength(); i++)
            {
                Node node = list.item(i);
                if (node != null)
                {
                    NamedNodeMap nodeMap = node.getAttributes();
                    HashMap<String, String> maps = new HashMap<String, String>();
                    for (int j = 0; j < nodeMap.getLength(); j++)
                    {
                        Attr att = (Attr) nodeMap.item(j);
                        maps.put(att.getName(), att.getValue());
                    }
                    if (maps.containsKey("yt:format"))
                    {
                        String f = maps.get("yt:format");
                        if (maps.containsKey("url"))
                        {
                            cursor = maps.get("url");
                        }
                        if (f.equals("1"))
                            return cursor;
                    }
                }
            }
            return cursor;
        }
        catch (Exception ex)
        {
            Log.e("Get Url Video RTSP Exception======>>", ex.toString());
        }
        return urlYoutube;

    }

protected static String extractYoutubeId(String url) throws MalformedURLException
    {
        String id = null;
        try
        {
            String query = new URL(url).getQuery();
            if (query != null)
            {
                String[] param = query.split("&");
                for (String row : param)
                {
                    String[] param1 = row.split("=");
                    if (param1[0].equals("v"))
                    {
                        id = param1[1];
                    }
                }
            }
            else
            {
                if (url.contains("embed"))
                {
                    id = url.substring(url.lastIndexOf("/") + 1);
                }
            }
        }
        catch (Exception ex)
        {
            Log.e("Exception", ex.toString());
        }
        return id;
    }
public void onPause ()
{
super.onPause();
videoView.stopPlayback();
}
}


Get Full Source Code: Here


Play sound in android example

You can play sound file in your android application.You need MP3 file which you want to play.
Here is full description and only one method you need to apply in your code.


  • First create folder in res named raw.Copy MP3 file in it (in raw folder).
  • Generate MediaPlayer Object in Activity class.Make the changes as shown in BOLD.


                                    public class MainActivity extends Activity {

                                 MediaPlayer mp;
                                    @Override
                                public void onCreate(Bundle savedInstanceState) {
                        super.onCreate(savedInstanceState);
                       setContentView(R.layout.activity_main);
                          
}
                                     }


  • Create one method playSound() in your activity class and add following code:

               
 
                 private void playSound() {
mp = MediaPlayer.create(MultiActivity.this, R.raw.sound_file);
        mp.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
}
});
mp.start();
}


  • Add setOnClickListener() method of button and only call this playSound() method.
            
                 playButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
playSound();
}
});


  • For Big MP3 file you can create one button to stop sound.Just put mp.release(); and mp.stop(); code in it.
      •  

Sunday, September 1, 2013

GridView Example


GridView is a 2 - Dimensional display of your content. It is mainly useful to show icons or images.
Take a look of GridView.



Example:
  • First Create project named "GridView_Example".
  • Download some images/photos you would like to set in GridView and save it in res/drawable/ directory.
  • Open activity_main.xml file and add following code:

activity_main.xml



<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/gridview"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"
    android:columnWidth="90dp"
    android:numColumns="auto_fit"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    android:stretchMode="columnWidth"
    android:gravity="center"
/>


  • Open the MainActivity.java file and add following code:

MainActivity.java



public void onCreate(Bundle savedInstanceState) 
{
   super.onCreate(savedInstanceState);
   setContentView(R.layout.main);

   GridView gridview = (GridView) findViewById(R.id.gridview);
   gridview.setAdapter(new ImageAdapter(this));

   gridview.setOnItemClickListener(new OnItemClickListener() {
       public void onItemClick(AdapterView<?> parent, View v, int position, long id) 
       {
           Toast.makeText(HelloGridView.this, "" + position, Toast.LENGTH_SHORT).show();
       }
   });
}


  • Now You get some error in MainActivity.java file,but ignore it.Create New Class file (File - New - Class) named it ImageAdapter.java.
  • Insert following code in ImageAdapter.java file. 

ImageAdapter.java



public class ImageAdapter extends BaseAdapter
{
private Context mContext;

    public ImageAdapter(Context c) 
    {
        mContext = c;
    }

    public int getCount() 
    {
        return mThumbIds.length;
    }

    public Object getItem(int position) 
    {
        return null;
    }

    public long getItemId(int position) 
    {
        return 0;
    }

    // create a new ImageView for each item referenced by the Adapter
    public View getView(int position, View convertView, ViewGroup parent) 
    {
        ImageView imageView;
        if (convertView == null) 
        {  // if it's not recycled, initialize some attributes
            imageView = new ImageView(mContext);
            imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setPadding(8, 8, 8, 8);
        } 
        else 
        {
            imageView = (ImageView) convertView;
        }

        imageView.setImageResource(mThumbIds[position]);
        return imageView;
    }

    // references to our images
    private Integer[] mThumbIds = {
            R.drawable.cat, R.drawable.dog,
            R.drawable.cat_two, R.drawable.dog_two,
            R.drawable.dog_three, R.drawable.doglast,
            R.drawable.cat, R.drawable.dog,
            R.drawable.cat_two, R.drawable.dog_two,
            R.drawable.dog_three, R.drawable.doglast,
            R.drawable.cat, R.drawable.dog,
            R.drawable.cat_two, R.drawable.dog_two,
            R.drawable.dog_three, R.drawable.doglast,
            R.drawable.cat, R.drawable.dog,
            R.drawable.cat_two, R.drawable.dog_two,
            R.drawable.dog_three, R.drawable.doglast,
    };

}

  • Note that, here you have to change names in mThumbIds integer array as per your image names.
  • Done, Now run the project and get output like above image.  


Monday, August 26, 2013

Custom ListView Example

This is a tutorial about customizing listview with and image and text.

Download Source Code for FREE:Here


Creating New Project

  • Create New Project in Eclipse. File => New Project.
  • Create New folder in res named drawable.
  • Create New gradient_bg.xml file in drawable directory and fill with following code. It is used to set gradient background in listView.

gradient_bg.xml


<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
  <gradient
      android:startColor="#424242"
      android:centerColor="#585858"
      android:endColor="#6E6E6E"
      android:angle="270" />
</shape>


  • Create New gradient_bg_hover.xml file in drawable directory and fill with following code. It is used to set gradient background when listView item is pressed.

 gradient_bg_hover.xml


<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
  <gradient
      android:startColor="#8A0808"
      android:centerColor="#610B0B"
      android:endColor="#B40404"
      android:angle="270" />
</shape>

  • Create New list_main.xml file in drawable directory and fill with following code. It is used to integrate above files into listView..

list_main.xml


<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
     android:state_selected="false"
        android:state_pressed="false"
        android:drawable="@drawable/gradient_bg" />
    <item android:state_pressed="true"
        android:drawable="@drawable/gradient_bg_hover" />
    <item android:state_selected="true"
     android:state_pressed="false"
        android:drawable="@drawable/gradient_bg_hover" />
</selector>

  • Now add following code into activity_main.xml file.

activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
    <ListView
        android:id="@+id/listView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:divider="#2A0A12"
        android:dividerHeight="2dp"
        android:listSelector="@drawable/list_main" />
</LinearLayout>

  • Next step is to design single row of listView. Create New xml file in layout directory and name it as row_layout.xml.

row_layout.xml


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/list_main"
    android:orientation="horizontal"
    android:padding="5dip" >


    <LinearLayout
        android:id="@+id/thumbnail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_marginRight="5dip"
        android:padding="3dip" >

        <ImageView
            android:id="@+id/list_image"
            android:layout_width="50dip"
            android:layout_height="50dip"
            android:src="@drawable/ic_launcher" />
    </LinearLayout>

   

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_toRightOf="@+id/thumbnail"
        android:text="Country name"
        android:textColor="#FFFFFF"
        android:textSize="15dip"
        android:textStyle="bold"
        android:typeface="sans" />

</RelativeLayout>

  • Until now we completed designing part of the listView. Next step is to add content in listview with different images. Add following code in MainActivity.java file. 

MainActivity.java



public class MainActivity extends Activity {


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

String listArray[] = new String[] { "India", "England", "Canada",
"New zealand", "South Africa", "Pakistan", "West indies" };
int icon[] = new int[] { R.drawable.india, R.drawable.england,
R.drawable.canada, R.drawable.new_zealand,
R.drawable.south_africa, R.drawable.pakistan,
R.drawable.west_indies };

ListView listView = (ListView) findViewById(R.id.listView);
List<HashMap<String, String>> aList = new ArrayList<HashMap<String, String>>();

for (int i = 0; i <= listArray.length - 1; i++) {

HashMap<String, String> hm = new HashMap<String, String>();
hm.put("title", listArray[i]);
hm.put("icon", Integer.toString(icon[i]));
aList.add(hm);
}

String[] sfrm = { "title", "icon" };
int[] sto = { R.id.title, R.id.list_image };

SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList,
R.layout.row_layout, sfrm, sto);

listView.setAdapter(adapter);

listView.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> arg0, View view,
int position, long id) {

switch (position) {

case 0:
Toast.makeText(getApplicationContext(), "India",
Toast.LENGTH_SHORT).show();
break;
case 1:
Toast.makeText(getApplicationContext(), "England",
Toast.LENGTH_SHORT).show();
break;
case 2:
Toast.makeText(getApplicationContext(), "Canada",
Toast.LENGTH_SHORT).show();
break;
case 3:
Toast.makeText(getApplicationContext(), "New zealand",
Toast.LENGTH_SHORT).show();
break;
case 4:
Toast.makeText(getApplicationContext(), "South Africa",
Toast.LENGTH_SHORT).show();
break;
case 5:
Toast.makeText(getApplicationContext(), "Pakistan",
Toast.LENGTH_SHORT).show();
break;
case 6:
Toast.makeText(getApplicationContext(), "West Indies",
Toast.LENGTH_SHORT).show();
break;

}

}
});
}
}

  • Done !

Download Source Code for FREE:Here



Wednesday, August 21, 2013

Rating Bar Full Example

activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    
    <RatingBar android:id="@+id/rating_1"
    android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:numStars="3"
        android:rating="2.5">
    </RatingBar>
    
    <RatingBar android:id="@+id/rating_2"
    android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:numStars="5"
        android:rating="2.25">
    </RatingBar>
    
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dip">
    
<TextView  
android:id="@+id/rating"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
   
    <RatingBar android:id="@+id/small_ratingbar"
            style="?android:attr/ratingBarStyleSmall"
            android:layout_marginLeft="5dip"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical" />
    </LinearLayout>
    
    <RatingBar android:id="@+id/indicator_ratingbar"
        style="?android:attr/ratingBarStyleIndicator"
        android:layout_marginLeft="5dip"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical" 
        />
        
</LinearLayout>



MainActivity.java



public class MainActivity extends Activity implements RatingBar.OnRatingBarChangeListener
{
RatingBar mSmallRatingBar;
RatingBar mIndicatingRatingBar;
TextView mRatingText;
    /** Called when the activity is first created. */
   
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        mRatingText=(TextView)findViewById(R.id.rating);
        
        mSmallRatingBar=(RatingBar)findViewById(R.id.small_ratingbar);
        mIndicatingRatingBar=(RatingBar)findViewById(R.id.indicator_ratingbar);
        
        ((RatingBar)findViewById(R.id.rating_1)).setOnRatingBarChangeListener(this);
        ((RatingBar)findViewById(R.id.rating_2)).setOnRatingBarChangeListener(this);
    }
    
   
    public void onRatingChanged(RatingBar ratingBar,float rating,boolean fromTouch)
    {
    final int numStars=ratingBar.getNumStars();
   
    mRatingText.setText(getString(R.string.ratingbar_rating)+" "+rating+" / "+numStars);
   
    if(mIndicatingRatingBar.getNumStars()!=numStars)
    {
    mIndicatingRatingBar.setNumStars(numStars);
    mSmallRatingBar.setNumStars(numStars);
    }
   
    if(mIndicatingRatingBar.getRating()!=rating)
    {
    mIndicatingRatingBar.setRating(rating);
    mSmallRatingBar.setRating(rating);
    }
   
    final float ratingBarStepSize=ratingBar.getStepSize();
   
    if(mIndicatingRatingBar.getStepSize()!=ratingBarStepSize)
    {
    mIndicatingRatingBar.setStepSize(ratingBarStepSize);
    mSmallRatingBar.setStepSize(ratingBarStepSize);
    }
    }

}



Drag and Drop Example

Drag and Drop is useful in canvas or drawing application.Here is full description,just follow it.


  • Modify the code in activity_main.xml file.

activity_main.xml



<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/LinearLayout01"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center" >

    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Drag Me" >
    </Button>

</FrameLayout>


  • Add below code in MainActivity.java file.

MainActivity.java



public class Home extends Activity implements OnTouchListener {


private final static int START_DRAGGING = 0;
private final static int STOP_DRAGGING = 1;

private Button btn;
private FrameLayout layout;
private int status;
private LayoutParams params;

private ImageView image;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

layout = (FrameLayout) findViewById(R.id.LinearLayout01);
// layout.setOnTouchListener(this);

btn = (Button) findViewById(R.id.btn);
btn.setDrawingCacheEnabled(true);
btn.setOnTouchListener(this);

params = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);

}

@Override
public boolean onTouch(View view, MotionEvent me) 
{
if (me.getAction() == MotionEvent.ACTION_DOWN) {
status = START_DRAGGING;
image = new ImageView(this);
image.setImageBitmap(btn.getDrawingCache());
layout.addView(image, params);
}
if (me.getAction() == MotionEvent.ACTION_UP) {
status = STOP_DRAGGING;
Log.i("Drag", "Stopped Dragging");
} else if (me.getAction() == MotionEvent.ACTION_MOVE) {
if (status == START_DRAGGING) {
System.out.println("Dragging");
image.setPadding((int) me.getRawX(), (int) me.getRawY(), 0, 0);
image.invalidate();
}
}
return false;
}
}

  • Done ! Now Run the Project.Try to drag button.

Friday, August 16, 2013

Shared Preference Example

Shared preference is used to store data globally and use it to anywhere in application. Two way we can use it.One is define global variable and other is shared preference.The main problem with global variable is data will be lost when user closes the application.To resolve this problem we can use shared preference.It maintains the data even user closes the app.


Initialization


Initialization of shared preference is given below.

SharedPreferences sp = this.getSharedPreferences("data",Activity.MODE_PRIVATE);
SharedPreferences.Editor edit = sp.edit();

Here,Editor is used to edit data of Shared Preference.

Store Data

Using Editor, you can store data into Shared Preference.We can use data types like boolean, string, int,float, long.Code is given below for all data types.

edit.putBoolean("enter_name",true);
edit.putString("enter_name","string_value");
edit.putInt("enter_name","int_value");
edit.putFloat("enter_name","float_value");
edit.putLong("enter_name","long_value");

edit.commit();    // Apply to store data.Don't forget to write it.

NOTE: edit.commit(); is the most important line.It is used to apply changes in shared preference.


Retrieve Data


You can retrieve Shared preference data through getString() method and so on.First of all you need to define Shared preference with same name.like:

 SharedPreferences sp = this.getSharedPreferences("data",Context.MODE_PRIVATE);

sp.getString("enter_name","default_string");
sp.getInt("enter_name",1);
sp.getBoolean("enter_name",true);
sp.getFloat("enter_name",null);
sp.getLong("enter_name",null);


Sample Code:

  • First Create 2 activities - 1. MainActivity.java    2. GetActivity.java.
  • MainActivity.java - Store data into Shared Preference.
  • GetActivity.java - Retrieve stored data.

MainActivity.java


public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final SharedPreferences sp = this.getSharedPreferences("abc",Activity.MODE_PRIVATE);
final SharedPreferences.Editor edit = sp.edit();
final EditText name = (EditText)findViewById(R.id.name);
final EditText pass = (EditText)findViewById(R.id.pass);
Button save = (Button) findViewById(R.id.save);
save.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String sname =  name.getText().toString();
   String spass = pass.getText().toString();
  edit.putString("username", sname);
  edit.putString("password", spass);
  edit.commit();
}
});
Button retrive = (Button) findViewById(R.id.retrive);
retrive.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,GetActivity.class);
startActivity(intent);
}
});
}
}

activity_main.xml


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Name:" />

    <EditText
        android:id="@+id/name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

    <EditText
        android:id="@+id/pass"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPassword" />

    <Button
        android:id="@+id/save"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="SAVE" />

    <Button
        android:id="@+id/retrive"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Retrive Information" />

</LinearLayout>


GetActivity.java



public class GetActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get);
TextView usertv =(TextView)findViewById(R.id.usertext);
TextView passtv =(TextView)findViewById(R.id.passtext);
SharedPreferences sp = this.getSharedPreferences("abc",Context.MODE_PRIVATE);

 usertv.setText(sp.getString("username","" ));
passtv.setText(sp.getString("password", ""));
}
}


activity_get.xml


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".GetActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Get Data" />

    <TextView
        android:id="@+id/usertext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="25dp"
        android:text="Username" />

    <TextView
        android:id="@+id/passtext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="25dp"
        android:text="Password" />

</LinearLayout>



Download Full Source Code:  Here