Davide
Davide

Reputation: 17808

How to communicate between activities in Android

I am new to Android (but not to java) and I am confused with Services, ViewModel, Broadcast things and other alternatives used to communicate between Activities. My communication needs are extremely basic.

Consider Midiscope's MainActivity. I want to do something like that, but with the Spinner to select the source on a different Activity. Basically one Activity for the Spinner (call it "SettingsActivity" but obviously cannot be a true Settings for reasons too long for this margin) and another Activity for the UI with the TextView, call it TextViewActivity. I am somewhat able to make it work if I share static variables to access the TextViewActivity from the Settings, so that I can create LoggingReceiver from the Settings but binding it to the TextViewActivity instead of Settings (this). Obviously this is not right (TM), so I attempted all the options I could google to no avail. What it the simplest way to accomplish this?

Upvotes: 0

Views: 1483

Answers (2)

Davide
Davide

Reputation: 17808

The problem is that I was thinking in the "Desktop" mode of developing java (e.g. with Swing) in which the windows are persistent objects, unlike in Android where Activities come and go at all the time.

My solution is to make the LoggingReceiver constructor private and to make LoggingReceiver its own factory with a singleton pattern (i.e. with a getInstance() method returning the sole static instance in existence). Then both the SettingsActivity and the TextViewActivity can access it. The former to do its business of linking the receiver to the right MIDI source, the latter to register itself as the ScopeLogger. Obviously I need also a setScopeLogger() (called by TextViewActivity in its onCreate()) and some null checks in the LoggingReceiver.onSend() if mLogger is not set, since the original code assumed that would happen in the constructor. But this part "business as usual" in java.

Upvotes: 0

Biscuit
Biscuit

Reputation: 5247

If you want to pass some basic data from one activity to another you should use Intent

How to use it:

Activity1 (Sending data to Activity2):

Intent intent = new Intent(context, TextViewActivity.class);
intent.putExtra("EXTRA_SESSION_ID", sessionId);
startActivity(intent);

Activity2 (Receiving data from Activity1):

String sessionId = getIntent().getStringExtra("EXTRA_SESSION_ID");

Upvotes: 1

Related Questions