This question already has answers here:
How do I pass data between Activities in Android application?
(53 answers)
Closed 8 years ago.
My app has 2 activites.
The first activity is just a simple form where a user enters course information(class title, professor..etc.) the first activity passes the data which is supposed to be stored in a list.
In the second activity. The problem is that only the first course gets stored in the list, after the first time nothing new gets added to the second activity.
How can i do this ?
In your first activity :
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("login", jObj.getString(KEY_LOGIN));
intent.putExtra("mdp", jObj.getString(KEY_MDP));
intent.putExtra("prenom", jObj.getString(KEY_PRENOM));
intent.putExtra("nom", jObj.getString(KEY_NOM));
intent.putExtra("mail", jObj.getString(KEY_MAIL));
intent.putExtra("tel", jObj.getString(KEY_TEL));
startActivity(intent);
In your second activity :
Intent intent = getIntent();
if (intent != null) {
login = intent.getStringExtra("login");
mdp = intent.getStringExtra("mdp");
items.add(intent.getStringExtra("login"));
items.add(intent.getStringExtra("prenom"));
items.add(intent.getStringExtra("nom"));
items.add(intent.getStringExtra("mail"));
items.add(intent.getStringExtra("tel"));
}
Generally you can pass data from one Activity to another with an Intent like this:
In your first Activity:
// Create your Intent
Intent intent = new Intent(context, TargetActivity.class);
// Now you can add extras to the intent, you identify extras with a String key
intent.putExtra("text", someString);
intent.putExtra("amount", someInteger);
// Then you start your Activity with this Intent
startActivity(intent);
In your second Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Only get data from Intent when the Activity is new
if(savedInstanceState == null) {
Intent intent = getIntent();
// Now you read the values from the Intent
String someString = intent.getStringExtra("text");
int someInteger = intent.getIntExtra("amount", 0);
}
}
hey its simple look at the code
for sending
Intent i = new Intent(getApplicationContext(), Confirmation.class)
i.putExtra("name",etName.getText().toString()));
i.putExtra("pass",etPass.getText().toString());
startActivity(i);
for recieving in next activity
Bundle extras = getIntent().getExtras();
String strEmployeeID="";
if (extras != null)
{
String value = extras.getString("name");
String value1 = extras.getString("pass");
//
Toast.makeText(getBaseContext(), value, Toast.LENGTH_LONG).show();
strEmployeeID = value;
strEmployeePass = value1;
}
just simply do it like that:
passing data from 1st activity to 2nd activity:
Intent intent = new Intent(yourafirstctivity.this,Yoursecondactivity.class);
intent.putExtra("yourkey", yourvalue);
intent.putExtra("yourkey", yourvalue);
intent.putExtra("yourkey", yourvalue);
startActivity(intent);
and get the data from 1st activity to 2nd activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.yourlayout);
String yourstring = getIntent().getExtras().getString("yourkey");
String yourstring = getIntent().getExtras().getString("yourkey");
String yourstring = getIntent().getExtras().getString("yourkey");
}
if you want to send data between two Activities .You must call following one,
startActivityForResult(getcontext(), SecondActivity.class);
On calling this,Activity starts the second.In turn, second response to this intent and reply back with necessary data.
public void startActivityForResult(Intent intent, int requestCode, Bundle options) {
if (mParent == null) {
Instrumentation.ActivityResult ar =
mInstrumentation.execStartActivity(
this, mMainThread.getApplicationThread(), mToken, this,
intent, requestCode, options);
if (ar != null) {
mMainThread.sendActivityResult(
mToken, mEmbeddedID, requestCode, ar.getResultCode(),
ar.getResultData());
}
if (requestCode >= 0) {
mStartedActivity = true;
}
} else {
if (options != null) {
mParent.startActivityFromChild(this, intent, requestCode, options);
} else {
// Note we want to go through this method for compatibility with
// existing applications that may have overridden it.
mParent.startActivityFromChild(this, intent, requestCode);
}
}
}
Following one you must call this on the First Activity (from where the intent called).It helps to recieves the reply data from second Activity.
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(!isFeatureInstalled(getContext()))
return;
if(requestCode == GET_REMINDER_DETAILS && resultCode == Activity.RESULT_OK)
{
mFilled = true;
fillDataFromIntent(data);
checkALertRequired.setChecked(true);
}
}
Related
I searched a lot and tried things but the onActivityResult function isn't launched when the intent from which I try to get a string information is closed.
I use Visual Studio to write this application, this is my code :
The click event that opens the activity where users can type strings :
private void Btn_Valid_Click(object sender, EventArgs e)
{
----
Intent intent = new Intent(this, typeof(activity_OF_TransfertChxChmb));
StartActivityForResult(intent, 0);
----
}
The function in the openned Intent that should return the string information :
private void Validate()
{
string stringToPassBack = tb_Store.Text;
// put the String to pass back into an Intent and close this activity
Intent intent = new Intent();
intent.PutExtra("result", stringToPassBack);
SetResult(Result.Ok, intent);
Finish();
}
And the onActivityResult function that should be launched in the first activity:
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
base.onActivityResult(requestCode, 0, data);
if (requestCode == 0)
{
if (resultCode == -1) // Ok
{
string result = data.GetStringExtra("result");
}
if (resultCode == 0) // Canceled
{
//Write your code if there's no result
}
}
}
I am missing something, but can't figure out what.
Thank you for your help.
You are adding the extra via:
intent.PutExtra(Intent.ExtraText, stringToPassBack);
Your key is Intent.ExtraText.
You are retrieving the extra via:
string result = data.GetStringExtra("result");
Your key is "result".
So, perhaps Intent.ExtraText does not equal "result". You need to use the same key in both places.
I can send data from the first activity but on repeating the same procedure on the second activity to send data to ble device is not successful. How can I send data from second activity?
use this to save
Intent intent = new Intent(FirstScreen.this, SecondScreen.class)
intent .putExtra(strName, keyIdentifer );
use this to get
String newString;
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
newString= null;
} else {
newString= extras.getString("STRING_I_NEED");
}
} else {
newString= (String) savedInstanceState.getSerializable("STRING_I_NEED");
}
If you just want to send data to the next activity, use
Intent intent = new Intent(FirstActivity.this, SecondActivity.class)
intent.putExtra("id_for_value", value);
startActivity(intent);
And recover it with
value= getIntent().getExtras().getString("id_for_value");//if it is a string
OR
If you want to send data back from the Second activity back to the Previous, you have to use start activity for results
Intent intent=new Intent(MainActivity.this,SecondActivity.class);
startActivityForResult(intent, 2)//where 2 is the request code
finish();
Again in the FirstActivity, overide this
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 2
if(requestCode==2)
{
String result=data.getStringExtra("ResultId");
}
}
And in your PreviousActivity, you pass the data like this
Intent intent=new Intent();
intent.putExtra("ResultId",message);
setResult(2,intent);
finish();
I'm trying to send an image path from one activity to another. I'm catching the intent in onResume, but the string path is always null. I don't know what I'm doing wrong. Hopefully you guys can help me with this problem.
Here's my activity where I grab the image path and send an intent.
private Intent testImage = new Intent(this, MyActivity.class);
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.card_create_layout);
testImage = new Intent(this, MyActivity.class);
}
private void grabImage()
{
Intent imageGetter = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(imageGetter, RESULT_LOAD_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data)
{
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};//Array size of 1, and we put in a string
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
user_image_path = cursor.getString(columnIndex);//here we have our image path.
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.imageView);
imageView.setImageBitmap(BitmapFactory.decodeFile(user_image_path));
}
testImage.putExtra("the_image", user_image_path);
}
#Override
public void onClick(View v)
{
switch (v.getId())
{
case R.id.theCreateButton:
grabImage();
break;
case R.id.theDesButton:
startActivity(sendInformation);
}
}
#Override
public void onBackPressed()
{
super.onBackPressed();
MyActivity.checkCard();
setResult(Activity.RESULT_OK, getIntent());
finish();
}
Now in my other activity, when I grab the image and press back
#Override
public void onResume()
{
super.onResume();
String ImagePath = getIntent().getStringExtra("the_image");
if(ImagePath == null)
{
Toast.makeText(this,"hello everyone",Toast.LENGTH_LONG).show();
}
}
It keeps on showing the toast message "hello everyone", which means ImagePath is continuously null. How do I fix this?
Pass mechanism between activities is available in three ways :
via DI(Dependency Injection)
via Bundle mechanism
via Singletone class which play a role a bridge or data holder between activities.
To avoid duplicating answer - please search any way(i recommend easiest - via Bundle) in stackoverflow.
Quick guide :
You put your string into bundle via intent.putExtra(String name, String value) in Activity A
Start this intent with startActivity(intent);
In B activity read value view getIntent().getStringExtra(String name) in OnCreate method.
name value is need the same in activity A and B. This is a key.
I don't see a
startActivity(testImage);
If you aren't using that intent to start the activity, then there is no extra called 'the_image' and the getStringExtra function will effectively return a null.
#Override
public void onBackPressed() {
Intent intent = new Intent();
intent.putExtra("the_image", user_image_path);
setResult(RESULT_OK, intent);
super.onBackPressed();
}
The above is how to correctly do it, if you have started an activity for result.
I am currently working on an android project and I have an activity that is started using the startActivityForResult() function.
Within this activity I have an ArrayList and I create an Internet and then set the result as the intent, as in the following code.
private void getSearchData()
{
ArrayList<Spanned> passwords = null;
String searchTerm = txtSearch.getText().toString();
GetSearchResults search = new GetSearchResults(this, searchTerm);
if (rdoApp.isChecked())
{
passwords = search.getData(SearchType.App);
}
else if (rdoName.isChecked())
{
passwords = search.getData(SearchType.Name);
}
else if (rdoUsername.isChecked())
{
passwords = search.getData(SearchType.Username);
}
Intent intent = new Intent();
intent.putExtra("searchResults", passwords);
setResult(1, intent);
finish();
}
In the first activity in the function OnActivityResult I then want to get the ArrayList so that I can process the data. I have the following code so far.
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
common.showToastMessage("Result received", Toast.LENGTH_LONG);
Bundle bundle = data.getExtras();
}
I have no idea where to go from here.
I've managed to find a way, it is thank to #Jan Gerlinger answer pointed me in the correct direction but I've found how to do it.
In the activity where I am setting the result I have the following code
ArrayList<Spanned> passwords = search.getResult();
Intent intent = new Intent();
Bundle bundle = new Bundle();
bundle.putSerializable("passwords", passwords);
intent.putExtras(bundle);
setResult(1, intent);
finish();
In the activity for inside the OnActivityResult function I have the following
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
common.showToastMessage("Result received", Toast.LENGTH_LONG);
Bundle bundle = data.getExtras();
ArrayList<Spanned> passwords = (ArrayList<Spanned>) bundle.getSerializable("passwords");
}
intent.putExtra("searchResults", passwords);
here uses the putExtra(String name, Serializable value) method. So you can use getSerializableExtra(String name) to get it back:
ArrayList<Spanned> passwords = (ArrayList<Spanned>) data.getSerializableExtra("searchResults");
Depending on the type of your Spanned objects and if they do implement Serializable, this may however throw Exceptions as Spanned does not implement Serializable directly.
This question already has answers here:
How to pass a value from one Activity to another in Android? [duplicate]
(7 answers)
Closed 9 years ago.
In Activity1, I input some data like name and address. When I click the next button, there will be another input form. What I want to do is, when I click BACK, I will return to Activity1 and the data I entered there previously is shown.
HELP please :)
=============
UPDATED: Activity1
private void startActivityForResult()
{
TextView textname = (TextView) findViewById(R.id.username);
TextView textaddress = (TextView) findViewById(R.id.useraddress);
Intent intent = new Intent(this, GetInformation.class);
//intent.putExtras(getIntent());
intent.putExtra("username", textname.getText().toString());
intent.putExtra("useradd", textaddress.getText().toString());
startActivityForResult(intent, 0);
}
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
TextView textname = (TextView) findViewById(R.id.username);
TextView textaddress = (TextView) findViewById(R.id.useraddress);
textname.setText(data.getStringExtra("returnname").toString());
textaddress.setText(data.getStringExtra("returnadd").toString());
}
Activity2
private void startActivityForResult()
{
final String username;
final String useraddress;
Intent intent = getIntent();
//intent.putExtras(getIntent());
username = getIntent().getStringExtra("username");
useraddress = getIntent().getStringExtra("useradd");
intent.putExtra("returnname", username);
intent.putExtra("returnadd", useraddress);
setResult(0, intent);
}
There's a simple way to do this in Android : startActivityForResult. Basically, when you launch the activity, you say that you are expecting a result. The other activity can then add information that will be returned to the starting activity. Here's a very simple code sample from the official doc :
public class MyActivity extends Activity {
...
static final int PICK_CONTACT_REQUEST = 0;
protected boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
// When the user center presses, let them pick a contact.
startActivityForResult(
new Intent(Intent.ACTION_PICK,
new Uri("content://contacts")),
PICK_CONTACT_REQUEST);
return true;
}
return false;
}
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (requestCode == PICK_CONTACT_REQUEST) {
if (resultCode == RESULT_OK) {
// A contact was picked. Here we will just display it
// to the user.
startActivity(new Intent(Intent.ACTION_VIEW, data));
}
}
}
}
You can get a much more complete description of all this on the Activity page in the official doc (section Starting Activities and Getting Results).
Save Activity1 state in method onSaveInstanceState, and then in method
void onCreate(Bundle savedInstanceState)
you can restore state, using savedInstanceState.
Or, if you want pass entered data to second activity, you can place data in intent.
Sample:
Intent i = new Intent(FirstActivity.this, SecondActivity.class);
i.putExtra("Key", "Value");
startActivityForResult(i, 0);
in Second Activity you can get data:
getIntent().getStringExtra("Key");
To return result from second activity:
Intent data = new Intent();
data.put("key", "value");
setResult(RESULT_OK, data);
then you can retrieve data in first activity using
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
data.getStringExtra("key");
}