Sobes.tech
Junior

How to pass data from one Activity to another?

sobes.tech AI

Answer from AI

Data transfer methods:

  1. Intent Extras: The most common method. Key-value pairs are added to the Intent.
// In the sending Activity
Intent intent = new Intent(this, TargetActivity.class);
intent.putExtra("key_string", "Hello!");
intent.putExtra("key_int", 42);
intent.putExtra("key_boolean", true);
startActivity(intent);
// In the receiving Activity
Bundle extras = getIntent().getExtras();
if (extras != null) {
    String stringData = extras.getString("key_string");
    int intData = extras.getInt("key_int");
    boolean booleanData = extras.getBoolean("key_boolean", false); // With default value
}

Supported types: primitives, String, Bundle, Parcelable, Serializable. For complex objects, Parcelable is preferred.

  1. ViewModel (together with LiveData or Channel): Suitable for more complex scenarios where data needs to be preserved during screen rotations or used by multiple components. DataFlow can be implemented via MutableLiveData or Channel.
// In a shared ViewModel (e.g., shared by host Activity and fragments)
private val _data = MutableLiveData<MyData>()
val data: LiveData<MyData> = _data

fun setData(newData: MyData) {
    _data.value = newData
}
// In the sending Activity/Fragment
viewModel.setData(MyData(...))
// In the receiving Activity/Fragment observing ViewModel
viewModel.data.observe(viewLifecycleOwner) { data ->
    // Use the data
}
  1. Callback / Interface (when starting Activity for result): Used when the receiving Activity should return a result to the sending Activity.
// In the sending Activity
ActivityResultLauncher<Intent> someActivityResultLauncher = registerForActivityResult(
    new ActivityResultContracts.StartActivityForResult(),
    result -> {
        if (result.getResultCode() == Activity.RESULT_OK) {
            Intent data = result.getData();
            if (data != null && data.getExtras() != null) {
                String resultData = data.getExtras().getString("result_key");
            }
        }
    });

// Launching Activity for result
Intent intent = new Intent(this, TargetActivity.class);
someActivityResultLauncher.launch(intent);
// In the receiving Activity
Intent resultIntent = new Intent();
resultIntent.putExtra("result_key", "Result");
setResult(Activity.RESULT_OK, resultIntent);
finish();
  1. Local database / Shared Preferences / Internal Storage: For transferring large amounts of data or data that needs to be saved. Data is written in one Activity and read in another.
// Writing (example with Shared Preferences)
SharedPreferences sharedPref = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("saved_data", "Data saved");
editor.apply();
// Reading (example with Shared Preferences)
SharedPreferences sharedPref = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
String savedData = sharedPref.getString("saved_data", null);

This approach requires additional logic to manage the data lifecycle (when to clear it).

  1. Singleton / Global static object: Not recommended due to potential memory leaks and architecture violations. Use only in extreme and very simple cases.

    // Singleton class
    public class DataHolder {
        private static final DataHolder instance = new DataHolder();
        private String data;
    
        private DataHolder() {}
    
        public static DataHolder getInstance() {
            return instance;
        }
    
        public String getData() {
            return data;
        }
    
        public void setData(String data) {
            this.data = data;
        }
    }
    
    // In the sending Activity
    DataHolder.getInstance().setData("Data via singleton");
    
    // In the receiving Activity
    String data = DataHolder.getInstance().getData();
    

The choice of method depends on the volume of data, its complexity, the need for persistence, and the required interaction between Activities. The most common and recommended approaches are Intent Extras and ViewModel.