JustcallmeDrago
JustcallmeDrago

Reputation: 1883

Sending Bundle to Main/Launcher Activity BEFORE it's created?

Bundles can be easily passed to new activities with intents:

Intent intent = new Intent(this, DisplayMessageActivity.class);
Bundle b = new Bundle();
// add extras...
intent.putExtras(b);
startActivity(intent);

Is it possible use Bundles (or similar) to send data to the main activity?

The Application class is created before any activity and I would like to use it to send data to the main activity. I do not want to have the data accessible globally or use static methods on the main activity to pass data to it.

Upvotes: 1

Views: 758

Answers (2)

jimbob
jimbob

Reputation: 3298

Have you considered temporarily using SharedPreferences and then deleting the SharedPreferences data in the onCreate of the new activity.

some example code:

Activity1:

SharedPreferences prefs = getSharedPreferences("mydata", 0);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString("secretstring", "asdasdasdqwerty");
        editor.commit();

Activity2:

SharedPreferences prefs = getSharedPreferences("mydata", 0);
String savedString = prefs.getString("secretstring", "");

SharedPreferences prefs = getSharedPreferences("mydata", 0);
            SharedPreferences.Editor editor = prefs.edit();
            editor.putString("secretstring", "nope");
            editor.commit();

A second possibility is to use getters and setters for public variables but only return the correct variable to your main class by checking what class is asking for it.

Hope this helped :).

Upvotes: 1

cgcarter1
cgcarter1

Reputation: 327

Since you already have a handle on the application, I would just use it to create an application variable -

public class MyApplication extends Application {

    private String someVariable;

    public String getSomeVariable() {
        return someVariable;
    }

    public void setSomeVariable(String someVariable) {
        this.someVariable = someVariable;
    }
}

You have to declare the class in your manifest like so:

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

And then in the receiver Activity:

// set
((MyApplication) this.getApplication()).setSomeVariable("foo");

// get
String s = ((MyApplication) this.getApplication()).getSomeVariable();

As explained by Jeff Gilfelt here: Android global variable

Upvotes: 1

Related Questions