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.
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.
My source code is as follows:
in MainActivity:
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode)
{
case LOGIN_ACTIVITY_REQUEST_CODE:
{
if(resultCode == RESULT_OK){
Bundle bd = new Bundle();
bd = data.getBundleExtra("bundle");
}
}
default:
{
Log.d(DEBUG_ACTIVITY_CLASS_NAME, "ERROR : onActivityResult - unknown activity code");
}
}
}
And second activity's code is:
public void returnToGameActivity(Bundle bundle) {
Intent intent = new Intent();
intent.putExtra("bundle", bundle);
this.setResult(RESULT_OK, intent);
finish();
}
But i can't receive data 'bd' of Bundle type in onActivityResult() in MainActivity. Why?
But in this case, i can get data of bd:
in second activity,
putExtra("string", "test string");
and in MainActivity,
String str = getStringExtra("string");
Why i can't get data in bundle type?
To transfer a Bundle element from one activity to other,use the following code:
Intent i=new Intent(First.this,Second.class);
//i.putExtra("mylist",amt);
Bundle b = new Bundle();
b.putSerializable("bundleinterest", (Serializable) amtint);
b.putSerializable("bundleobj", (Serializable) amt);
i.putExtras(b);
startActivity(i);
In Second.class:
Bundle bn = new Bundle();
bn = getIntent().getExtras();
getobj = new ArrayList<CompoundAmount>();
getinterestobj=new ArrayList<CompoundIntAmount>();
getobj = (ArrayList<CompoundAmount>) bn.getSerializable("bundleobj");
getinterestobj = (ArrayList<CompoundIntAmount>) bn.getSerializable("bundleinterest");
Explanation:
Use Serializable or Parcelable interfaces while transferring Bundles.
Your set-get class must implements Serializable as:
public class CompoundIntAmount implements Serializable {
private final String amt;
public CompoundIntAmount(String amt){
this.amt = amt;
}
public String getIntAmount() {
return amt;
}
}
Here CompoundAmount and CompoundIntAmount are custom set-get classes which must implement Serializable(like the one above).
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);
}
}
I have an application calling a second activity using a list of objects. that return the list of objects, my code is following
Intent returnIntent = new Intent();
Bundle bundle = new Bundle();
bundle.putSerializable("myList", (Serializable) list);
returnIntent.putExtras(bundle);
context.setResult(100, returnIntent);
context.finish();
And I am trying to retrive that list of objects, but I cannt
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == 100) {
Bundle bundel = data.getExtras();
try {
list = (List<Model>) bundel.get("myList");
} catch (Exception ex) {
Log.d("MY ERROR", ex.toString());
}
Toast.makeText(GetXmlFromUrlActivity.this, "You need to enter your name: " + list.size(), Toast.LENGTH_LONG).show();
}
}
Can anyone please help me?
you can use two methods:1. Serializable your List ,your cannot put the list to the intent direct
2. you can use static for the (List as global variable
I just found my answer, I just change my class structure, make it Serializable such,
public class Model implements Serializable
it works fine for me.
I have this code:
Intent intent = new Intent();
intent.setAction(Intent.ACTION_PICK);
intent.setData(ContactsContract.Contacts.CONTENT_URI);
intent.putExtra(EXTRA_ONLINE_ID, (String) v.getTag());
startActivityForResult(intent, PICK_CONTACT);
Then on response:
public void onActivityResult(int reqCode, int resultCode, Intent data) {
switch (reqCode) {
case (PICK_CONTACT):
if (resultCode == Activity.RESULT_OK) {
try {
Uri contactData = data.getData();
String onlineid = data.getStringExtra(EXTRA_ONLINE_ID);
} catch (Exception e) {
e.printStackTrace();
}
}
break;
}
super.onActivityResult(reqCode, resultCode, data);
}
the onlineid variable is null. How can I pass a value and then to receive it back?
EDIT
I even tried,
Bundle extras = data.getExtras(); // returns null
This is done by design; system activities will not send back the extras with which they're called, so you have to manage the data elsewhere.
Luckily, the resultCode parameter is fully controlled by yourself, which means that you can use it to index your data.
private final int PICK_CONTACT = 0;
private Bundle[] myDataTransfer = { null };
...
Bundle myData = new Bundle();
myData.putString(EXTRA_ONLINE_ID, (String) v.getTag());
myDataTransfer[PICK_CONTACT] = myData;
// create intent and all
startActivityForResult(intent, PICK_CONTACT);
...
public void onActivityResult(int reqCode, int resultCode, Intent data) {
if (resultCode == PICK_CONTACT) {
Bundle myData = myDataTransfer[resultCode];
String onlineid = myData.getString(EXTRA_ONLINE_ID);
}
}
I'm not a Java programmer, there must be a nicer way to implement a map of Bundles, but this works :)
ok Check if your Activity android:launchMode is configured as SingleTask or SingleInstance! that must be the problem :)
The EXTRA_ONLINE_ID field will have to be set in the activity that you launched using setResult. If it's not setting that value in the returned Intent (which is different from what you sent) then you will get a null value.
I was running into some problems with this as well.
Instead of this line
intent.putExtra(EXTRA_ONLINE_ID, (String) v.getTag());
Try
intent.putExtra(EXTRA_ONLINE_ID, "" + v.getTag());