Actually the standard way of passing parameters to child activities and fragments is through Intents
. You can pass any primitive value, any array[] of primitive objects, some ArrayLists<>, and even any Parcelable
object,
I use the following routine in my code:
public static void runChildActivity(@NonNull Activity context, int code, @NonNull Class<? extends Activity> activityClass, @Nullable Bundle parameters) {
Intent intent = new Intent(context, activityClass);
if (parameters != null) intent.putExtras(parameters);
context.startActivityForResult(intent, code);
}
And then, you can call it like this:
Bundle parameters = new Bundle();
parameters.putString("page_id", xxxx);
parameters.putFloat("temperature", 24.5f);
parameters.putParcelable("complexobject", yourParcelableObject);
runChildActivity(context, CODE, PostsActivity.class, parameters);
The parameter CODE
(int) is a code you assign to your activity
just in case it also returns values. Then you can check for the returning values in an overridden onActivityResult()
in the calling activity. If your activity does not return any value, the parameter is irrelevant.
In the child activity, you can get the parameters in onCreate
(or anywhere after it):
@Override
public void onCreate(Bundle savedInstanceState) {
Bundle parameters = getIntent().getExtras();
// in a fragment it'd be
// Bundle parameters = getArguments();
// those are the parameters passed. Second value is default
// value in case parameter is not found.
String pageId = parameters.getString("page_id", "-1");
float temperature = parameters.getFloat("temperature", 0f);
}
If you want then to return stuff from your child activity back to the parent activity, you then use setResult()
in the child activity before finish()
:
. (child activity)
.
.
private void finishWithParameters() {
Bundle parameters = new Bundle();
parameters.putString("returnvalue", "user is crazy");
parameters.putInteger("filesdownloaded", 43);
Intent i = new Intent();
i.putExtras(parameters);
setResult(Activity.RESULT_OK, i);
finish();
}
.
.
.
And then in the calling activity:
.
.
.
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
if (requestCode == CODE && data != null) {
// that's the CODE we ran runChildActivity() with
// so stuff is coming from that child activity
Bundle parameters = data.getExtras();
int filesDownloaded = parameters.getInt("filesDownloaded")
// ... or directly, without even getting the bundle ....
int filesDownloaded2 = data.getIntExtra("filesDownloaded")
}
}