How do you pass data between activities in an Android application?
3 Answers
in your current activity, create an intent
Intent i = new Intent(getApplicationContext(), ActivityB.class); i.putExtra(key, value); startActivity(i); then in the other activity, retrieve those values.
Bundle extras = getIntent().getExtras(); if(extras !=null) { String value = extras.getString(key); } 3 Comments
dotty
Is this how everyone does it?
M_M
I currently have insufficient rep to vote this down, but it's worth noting that, while this will work in some cases, it is not the only way to do it, and is not always the best, simplest, quickest or most efficient. Emre's answer (which has luckily been selected as the right answer despite a huge difference in votes) links to a variety of methods, from which you can choose the best solution for your app.
Aurelian Cotuna
This is not working all the time, because when you have lots of data, you can't attach them to the intent as extras. groups.google.com/forum/?fromgroups#!topic/android-developers/…
Use a global class:
public class GlobalClass extends Application { private float vitamin_a; public float getVitaminA() { return vitamin_a; } public void setVitaminA(float vitamin_a) { this.vitamin_a = vitamin_a; } } You can call the setters and the getters of this class from all other classes. Do do that, you need to make a GlobalClass-Object in every Actitity:
GlobalClass gc = (GlobalClass) getApplication(); Then you can call for example:
gc.getVitaminA() Comments
Put this in your secondary activity
SharedPreferences preferences =getApplicationContext().getSharedPreferences("name", MainActivity.MODE_PRIVATE); android.content.SharedPreferences.Editor editor = preferences.edit(); editor.putString("name", "Wally"); editor.commit(); Put this in your MainActivity
SharedPreferences preferences = getApplicationContext().getSharedPreferences("name", MainActivity.MODE_PRIVATE); if(preferences.contains("name")){ Toast.makeText(getApplicationContext(), preferences.getString("name", "null"), Toast.LENGTH_LONG).show(); }