Passing data between activities


There is multiple way to share Data Between Activity

Singleton class
Intents
Shared Preferences
Database


Singleton class:  Create a Singleton class



package com.example.util;

public class Singleton {
    private static Singleton mInstance = null;
 
    private String mString;
 
    private Singleton(){
        mString = "www.er-android.blogspot.in";
    }
 
    public static Singleton getInstance(){
        if(mInstance == null)
        {
            mInstance = new Singleton();
        }
        return mInstance;
    }
 
    public String getString(){
        return this.mString;
    }
 
    public void setString(String value){
        mString = value;
    }
}

Set Datain Singleton class



Singleton.getInstance().setString("welcome to the www.er-android.blogspot.in blog");

Get Data from  Singleton class

Singleton.getInstance().getString()


Intents: Set Data 



         Intent i= new Intent(A.this,B.class);
    		i.putExtra("Location", strlocation);
    		startActivity(i);


Get Data from Bundle



        Bundle bundle=getIntent().getExtras();
		if(bundle != null)
		{
		
		String strLoc= bundle.getString("Location");
	
		}

Shared Preferences: Create and set value in  Shared Prefernces


 SharedPreferences preferences=getSharedPreferences("LoginActivity", MODE_PRIVATE);	
   		 SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
   		 editor.clear().commit();
   		 editor.putString("USERNAME", "username");
   		 editor.putString("PASSWORD", "password");
   		 editor.commit();

Get value from Shared Preferences


  SharedPreferences preferences=getSharedPreferences("LoginActivity", MODE_PRIVATE);
	       if(preferences!=null)
		{
		 String strpassword=preferences.getString("PASSWORD", "");
		 String struser=preferences.getString("USER", ""));
		}






0 comments:

Post a Comment