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).
Related
I open a RemoteInput via intent but need to pass some additional data. I eventually retrieve it in the onActivityResult
Launch:
Bundle d = new Bundle();
d.putString("chatID", id);
RemoteInput remoteInput = new RemoteInput.Builder("remote_input")
.setLabel("Send to "+name)
.addExtras(d)
.build();
RemoteInput[] remoteInputs = new RemoteInput[]{remoteInput};
Intent intent = new Intent(RemoteInputIntent.ACTION_REMOTE_INPUT);
intent.putExtra(RemoteInputIntent.EXTRA_REMOTE_INPUTS, remoteInputs);
intent.putExtra("chatID", id);
intent.putExtra("asd", "das");
startActivityForResult(intent, 0);
Retrieve:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
System.out.println(data);
System.out.println(data.getExtras());
System.out.println(data);
System.out.println(data.getExtras().toString());
if (resultCode == RESULT_OK && requestCode == 0) {
System.out.println(data);
Bundle results = RemoteInput.getResultsFromIntent(data);
String text = results.getCharSequence("remote_input").toString();
System.out.println(" >");
Bundle c = data.getExtras();
//Object cd = data.getExtras().get("remote_input_types");
Object cd = results.get("remote_input");
System.out.println(cd);
System.out.println(cd.getClass().getName());
System.out.println(c);
System.out.println(c.keySet());
System.out.println(" <");
Set<String> keys = c.keySet();
Iterator<String> it = keys.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
None of what I try brings up "chatID", it simply seems to be missing from the keys. How else am I supposed to get the extras?
I believe the problem is how you are sending or launching the data.
Try using putExtraS() instead of putExtra(). PutExtras() is used to hold object of bundle class.
Launch:
Bundle bundle = new Bundle();
bundle.putString(Key, value);
Intent intent = new Intent(context, className);
intent.putExtras(bundle);
intent.setFlags(intFlag);
startActivityForResult();
Retrieve:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == 0) {
Bundle dataBundle = data.getExtras();
//Use data bundle
}
}
I want to receive data in previous Activity from next activity like (1 <--- 2 ). I tried but data is not received from second to first activity .
This is First Cativity
Intent i = new Intent(CustomActionActivity.this, Edit_Post.class);
i.putExtra("ActivityId", getItemActivity);
i.putExtra("Vessel", strVesselName);
i.putExtra("HashTag", strHashTag);
i.putExtra("RemarkTitle", strRemark);
i.putExtra("ShortRGN", strShortTypeRGN);
i.putExtra("VessId", strvesselid);
startActivity(i);
This is second Activity
Intent intent = getIntent();
strActivityId = intent.getStringExtra("ActivityId");
strVesselName = intent.getStringExtra("Vessel");
strHashTag = intent.getStringExtra("HashTag");
strRemark = intent.getStringExtra("RemarkTitle");
strShortRGN = intent.getStringExtra("ShortRGN");
strVessId = intent.getStringExtra("VessId");
img_AddPostAudio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Edit_Post.this, EditRecord.class);
i.putExtra("EditVesselId", strVessId);
i.putExtra("EditActivityId" , strActivityId);
startActivity(i);
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==REQUEST_CODE)
{
String audioString=data.getStringExtra("AUDIO_STRING");
Log.e(" audioString "," = "+audioString);
}
}
This is Third Activity
Intent intent = getIntent();
vesselId = intent.getStringExtra("EditVesselId");
strActivityId = intent.getStringExtra("EditActivityId");
Intent intent=new Intent(EditRecord.this, Edit_Post.class);
intent.putExtra("AUDIO_STRING",newAudioFile);
setResult(REQUEST_CODE, intent);
finish();
do this when you are calling the second activity
Intent i = new Intent(CustomActionActivity.this, Edit_Post.class);
i.putExtra("HashTag", strHashTag);
startActivityForResult(i, REQUEST_CODE);
Now you need to set the result what you want on CustomActionActivity
e.g.
Intent intent=new Intent();
intent.putExtra("MESSAGE",message);
setResult(REQUEST_CODE,intent);
finish();
Now you will get this data to the your first activity
e.g.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==REQUEST_CODE)
{
String message=data.getStringExtra("MESSAGE");
textView1.setText(message);
}
}
let me know in case of any issue
Use SharedPreferences
Store the data in a SharedPreference and access it in from the SharedPreference in the other activity.
Add the data to the SharedPreference in the onStop for the 2nd Activity and access it in the onCreate of the other Activity
#Override
public void onStop(){//Where you wish to insert data
SharedPreferences data=getSharedPreferences(PREFS_FILE,0);
SharedPreferences.Editor editor= count.edit();
editor.put("data","DATA");
editor.apply();
super.onStop();
}
in onCreate() of the other Activity:
SharedPreferences data = getApplicationContext().getSharedPreferences(PREFS_FILE, 0);
String dataString=data.get("Data",0);
Hope this helps. Cheers.
I am doing this way its works for me:
Activity 2:
public void onBackPressed() {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.putExtra("MESSAGE", strtext + "");
setResult(2, intent);
if (isclose) {
finish();
} else {
super.onBackPressed();
}
}
}
Activity1:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
String sSuName = data.getStringExtra("MESSAGE");
//txtfavouratecount.setText(sSuName);
}
in Your onclick listener
Intent itemintent = new Intent(context,your target Activity.class);
Bundle b = new Bundle();
b.putStringArray("iarray", Qtag);
b.putInt("mflag", 0);
itemintent.putExtra("android.intent.extra.INTENT", b);
startActivityForResult(itemintent,2);
I would do something like this:
In Activity A:
private static final int REQUEST_CODE = 9001;
Intent intent = new Intent(this, ActivityB.class);
startActivityForResult(intent, REQUEST_CODE);
In Activity B:
Intent data = new Intent();
data.putExtra("key", parameter);
setResult(CommonStatusCodes.SUCCESS, data);
finish();
And finally, in the Activity A, receive result:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE) {
if (resultCode == CommonStatusCodes.SUCCESS) {
if (data != null) {
String result = data.getStringExtra("key");
}
} else {
//Error to receive data
}
}
else {
super.onActivityResult(requestCode, resultCode, data);
}
}
Good luck!
Suppose I have a main activity A and two other activities B and C.
A launches intent B and at some point B launches intent C.
Then C sets setResult(...) and finish()'s, as does B, finally ending at onActivityResult(...) in A.
Is this allowed; will it work?
Yes, it will work. Just finish activity B when recieve the result from C. However the result from activity C will not be propagated when finishing B, you will have to set it manually if necessary.
In activity A:
Intent intent = new Intent(this, B.class);
startActivityForResult(intent, 1);
....
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1){
if (resultCode == RESULT_OK){
Bundle bundle = data.getExtras();
String code = "";
try{
code = bundle.getString("code");
} catch (Exception e){
e.printStackTrace();
}
if (!code.equals("")){
//do something
}
}
}
In Activity B:
Intent intent = new Intent(this, C.class);
startActivityForResult(intent, 1);
...
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1){
if (resultCode == RESULT_OK){
Bundle bundle = data.getExtras();
String code = "";
try{
code = bundle.getString("code");
} catch (Exception e){
e.printStackTrace();
}
if (!code.equals("")){
Intent intent = new Intent();
Bundle bundle = new Bundle();
bundle.putString("code", code);
intent.putExtras(bundle);
setResult(RESULT_OK, intent);
finish();
}
}
}
Then in Activity C at some point:
Intent intent = new Intent();
Bundle bundle = new Bundle();
bundle.putString("code", code);
intent.putExtras(bundle);
setResult(RESULT_OK, intent);
finish();
I hope this can help you.
Yes it will work. Here's an overview of the process you probably just need:
Activity A {
startActivityForResult() // start activity B
onActivityResult() // receive B's result
}
Activity B {
getIntentFromA()
startActivityForResult(); // start activity C
onActivityResult() {
// receive C's result
setResult(c's result); <-- this will pass back to A
}
}
Activity C {
getIntentFromB()
setResult(c's result); <-- this will pass back to B
}
I am trying to save some data in "MainActivity" when switching to another activity, and restoring that data as I switch back to it.
In "MainActivity": (restoring data)
protected void onCreate(Bundle savedInstanceState) {
// do usual stuff
restoreData();
}
In "MainActivity": (switching to "StatusActivity"):
Bundle data = saveData();
Log.d(TAG, "Sending data to status activity intent: " +data);
Intent intent = new Intent(getApplicationContext(), StatusActivity.class);
intent.putExtras(data);
startActivity(intent);
In "StatusActivity":
Bundle data = getIntent().getExtras();
Log.d(TAG, "Sending data to main activity intent: " +data);
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtras(data);
startActivity(intent);
My saveData() function:
private Bundle saveData() {
Log.d(TAG, "Started saving state");
Bundle data = new Bundle();
// store stuff in the bundle
return data;
}
My restoreData() function:
private void restoreData() {
Log.d(TAG, "Started restoring state");
Bundle data = getIntent().getExtras();
// restore stuff in the bundle
}
LogCat:
My bundle is fine when sending to StatusActivity:
Sending data to status activity intent:
Bundle[{obj0=Bundle[{timeSinceLastPooped=3224, hunger=5,
id=2130837505, timeSinceLastHungerUpdate=3224,
timeSinceLastFed=0, timeSinceLastHappinessUpdate=3224,
timeSinceLastEvolution=3224, posY=0.0, posX=0.0,
isDead=false, happiness=5, evolutionStage=0, type=pet}],
time=7.794168E7}]
But then sending back to MainActivity:
Sending data to main activity intent: Bundle[mParcelledData.dataSize=648]
What do I do with mParcelledData to get the original bundle back? Thanks!
Answer:
In "MainActivity": (restoring data)
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if(requestCode == 1) {
if(resultCode == RESULT_OK) {
restoreData(intent);
}
}
}
In "MainActivity": (switching to "StatusActivity"):
Bundle data = saveData();
Log.d(TAG, "Sending data to status activity intent: " +data);
Intent intent = new Intent(getApplicationContext(), StatusActivity.class);
intent.putExtras(data);
startActivityForResult(intent, 1);
In "StatusActivity":
Bundle data = getIntent().getExtras();
Log.d(TAG, "Sending data to main activity intent: " +data);
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtras(data);
setResult(RESULT_OK, getIntent());
finish();
You can use onRestoreInstanceState() witch is called after onStart(), whereas onCreate() is called before onStart().
Use the put methods to store values in onSaveInstanceState():
protected void onSaveInstanceState(Bundle bundle) {
super.onSaveInstanceState(bundle);
bundle.putInt("value", value);
}
And restore the value in onCreate():
public void onCreate(Bundle bundle) {
if (bundle!= null){
value = bundle.getInt("value");
}
}
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.