Skip to content Skip to sidebar Skip to footer

Passing Variables From One Class To Another Wiithout Using The Intent Get Extra

I'm doing some android code today and now the problem is I need to get the variables passed. The scene is that I need to login first to facebook then fetch my information. afterwar

Solution 1:

You can use the android.app.Application class for this purpose.

Steps to creating & using the Application class:

  1. Create your Application class. An example is shown below:

    publicclassApplicationControllerextendsApplication {
    
    //Application wide instance variables//Preferable to expose them via getter/setter methods@OverridepublicvoidonCreate() {
        super.onCreate();
        //Do Application initialization over here
    }
    
    //Appplication wide methods//Getter/Setter methods
    }
    
  2. Specify your Application class in AndroidManifest.xml

    <application android:icon="@drawable/icon" android:label="@string/app_name" android:name=".ApplicationController">

  3. Get the instance of the Application Class instance and call various methods:

    ApplicationController AC = (ApplicationController)getApplicationContext();

Hope this helps.

Solution 2:

Define Variable as Public Static or another option is store variable's value into Shared Preferences and retrieve value of preferences in next activity and refer below links for more information.

Shared Preferences

Solution 3:

Use public static variables in Main Screen for this. Or you can use Application class also for this purpose. other option is SharedPreferences.

For Application class global variables look at this SO question How to declare global variables in Android?

Solution 4:

Simplest way to do this is, you can use a data Class with static variables to use it everywhere. Something like this.

publicclassUser{

    publicstaticString name;
    publicstaticString email;
        .....

}

and then, after receiving data from Facebook, you can fill this and can access it everywhere.

Another ways to perform required task are SharedPreferences and Application Object of your class. You can read about them here and here.

Solution 5:

You may use SharedPreferences to pass value like this:

//for write id one ActivitySharedPreferencesspre= context.getSharedPreferences("Your prefName",
        Context.MODE_PRIVATE);
SharedPreferences.EditorprefEditor= spre.edit();
prefEditor.putString("key", value);
prefEditor.commit();


// for get id  second ActivitySharedPreferencesspre= context.getSharedPreferences("Your prefName",
        Context.MODE_PRIVATE);
String mystring=  spre.getString("key","");

Post a Comment for "Passing Variables From One Class To Another Wiithout Using The Intent Get Extra"