Sobes.tech
Junior — Middle

What methods can be used to implement data exchange between two Activities in an application?

sobes.tech AI

Answer from AI

Data exchange between two Activities in Android can be implemented in several ways:

  1. Via Intent — when launching the second Activity, data can be passed through extras:
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("key", "value");
startActivity(intent);

The second Activity retrieves data from the Intent.

  1. startActivityForResult — if you need to get a result back:
// In the first Activity
Intent intent = new Intent(this, SecondActivity.class);
startActivityForResult(intent, REQUEST_CODE);

// In the second Activity
Intent resultIntent = new Intent();
resultIntent.putExtra("resultKey", "resultValue");
setResult(RESULT_OK, resultIntent);
finish();
  1. Using shared storage — for example, SharedPreferences, databases, or singleton classes for storing data accessible to both Activities.

  2. Via ViewModel and LiveData (if using MVVM architecture with Jetpack) — for data exchange between Activities and fragments.

The method choice depends on the task and the application's architecture.