How can I send data from one activity (intent) to another?
I use this code to send data:
Intent i=new Intent(context,SendMessage.class);
i.putExtra(\
First, get the intent which has started your activity using the getIntent()
method:
Intent intent = getIntent();
If your extra data is represented as strings, then you can use intent.getStringExtra(String name)
method. In your case:
String id = intent.getStringExtra("id");
String name = intent.getStringExtra("name");
// How to send value using intent from one class to another class
// class A(which will send data)
Intent theIntent = new Intent(this, B.class);
theIntent.putExtra("name", john);
startActivity(theIntent);
// How to get these values in another class
// Class B
Intent i= getIntent();
i.getStringExtra("name");
// if you log here i than you will get the value of i i.e. john
If you are trying to get extra data in fragments then you can try using:
Place data using:
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER);
Get data using:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
getArguments().getInt(ARG_SECTION_NUMBER);
getArguments().getString(ARG_SECTION_STRING);
getArguments().getBoolean(ARG_SECTION_BOOL);
getArguments().getChar(ARG_SECTION_CHAR);
getArguments().getByte(ARG_SECTION_DATA);
}
We can do it by simple means:
In FirstActivity:
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("uid", uid.toString());
intent.putExtra("pwd", pwd.toString());
startActivity(intent);
In SecondActivity:
try {
Intent intent = getIntent();
String uid = intent.getStringExtra("uid");
String pwd = intent.getStringExtra("pwd");
} catch (Exception e) {
e.printStackTrace();
Log.e("getStringExtra_EX", e + "");
}
Put data by intent:
Intent intent = new Intent(mContext, HomeWorkReportActivity.class);
intent.putExtra("subjectName", "Maths");
intent.putExtra("instituteId", 22);
mContext.startActivity(intent);
Get data by intent:
String subName = getIntent().getStringExtra("subjectName");
int insId = getIntent().getIntExtra("instituteId", 0);
If we use an integer value for the intent, we must set the second parameter to 0 in getIntent().getIntExtra("instituteId", 0)
. Otherwise, we do not use 0, and Android gives me an error.
In the receiving activity
Bundle extras = getIntent().getExtras();
String userName;
if (extras != null) {
userName = extras.getString("name");
// and get whatever type user account id is
}