i am using following code to start my activity
public void onClick(View v) {
Intent myIntent = new Intent(v.getContext(), AddReceipt.class);
startActivityForResult(myIntent, RECEIPT_ADDED);
}
Now i want to get arrays from addreceipt class or data from my child activity
public synchronized void onActivityResult(final int requestCode, int resultCode, final Intent data) {
if (resultCode == Activity.RESULT_OK)
{
if (requestCode == RECEIPT_ADDED)
{
String abc = "abs";
}
}
}
when calling this function, it returns data as null and result code as 0. How can i get my data from my child activity.
BesT Regards
To get results from a sub-activity you need to call the setResult() method inside your sub-activity, passing the result code and possibly any amount of data inside an Intent object. Then you can catch this Intent in the onActivityResult() of your main activity. Hope this helps.
To pass data from child activity to parent activity use the following code:
Intent intent= childActivity.getIntent();
intent.putExtra("key","value");
childActivity.setResult(Activity.RESULT_OK, intent);
childActivity.finish();
if value is an list of object use Serializable .
Now if you press back button , onActivityResult method of parent class will be called and you will get RESULT_CANCEL.
Related
I Have an activity A that opens an activity B using startActivityForResult.
Now in activity B it's an activity fragment holder as well it contains an ActionBar with menu items.
Now whenever I press action bar button in activity B it should return data from selected fragment of an activity B not to its holder instead it should return data to activity A because it's the one who did the launch.
So it's basically passing data fragment (inside activity B) to activity B then to Activity A.
I am trying hopelessly to find a way to solve it. Is there any possible way to do it?
Disclaimer there are many ways, this is the one I prefer, not the best ever and not the perfect one, I just like this.
The easiest way, in my opinion, is to pass the data from Fragment inside B to ActivityB, then from ActivityB to ActivityA.
Step 1 to pass data from Fragment to container activity you have many ways; the one I usually use is to use an Interface:
Create interface for ActivityB
public interface IActivityB {
void setDataAAndFinish(whateverType data);
}
Implement interface in your activityB
public class InterventoActivity extends AppCompatActivity implements IInterventoActivity {
#Override
protected void onResume() {
super.onResume();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
private Bundle dataA = null;
#Override
public void setDataAAndFinish(whateverType data) {
dataA = data;
Intent intent = new Intent();
intent.putExtra("data", data)
setResult(RESULT_OK, intent);
finish();
}
}
Set activityA to request and accept return from ActivityB
first, start activityB for result and not normally
Intent i = new Intent(this, ActivityB.class);
startActivityForResult(i, 1);
Then read result
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if(resultCode == RESULT_OK) {
whateverType data = data.getStringExtra("data");
}
}
}
Now from fragment
((IActivityB)getActivity()).setDataAAndFinish(myDatas);
You need to declare a function in your ActivityB like the following.
public void sendDataBackToActivityA(String dataToBePassedToActivityA) {
Intent intent = new Intent();
intent.putExtra("data", dataToBePassedToActivityA);
setResult(RESULT_OK, intent);
finish();
}
Now from the Fragment that you launched from ActivityB, just call the method on some action in your Fragment that was launched from ActivityB. So the pseudo implementation of the process in your Fragment should look like the following. Declare this function in your Fragment and invoke the function on some action in your Fragment.
public void sendDataToActivityAFromFragment(String dataToBePassed) {
((ActivityB)getActivity()).sendDataBackToActivityA(dataToBePassed);
}
This will serve your purpose I hope.
You can declare static variables in your A activity and set it from the B activity
Or you can make static class and set variables values from B Activity and get it in A activity
Or you can send the menu value from Activity B to A while you exit Activity B and start activity A by using bundle
this is how you set the data to be passed to activity A in activity B
val resultIntent = Intent()
resultIntent.putExtra(DATA, "closed")
setResult(Activity.RESULT_OK, resultIntent)
finish()
this is how you get data in activity A
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == FILE_UPLOAD_CODE) {
when (resultCode) {
Activity.RESULT_OK -> {
// data here is obtained data of the method paramater
}}}}
In your Activity A.Move from activity A to b like this:-
int YOUR_CODE=101; // it can be whatever you like
Intent i = new Intent(getActivity(), B.class);
startActivityForResult(i,YOUR_CODE);
In your Activity B in its fragment
Intent resultIntent = new Intent();
resultIntent.putExtra("NAME OF THE PARAMETER", valueOfParameter);
...
setResult(Activity.RESULT_OK, resultIntent);
finish();
And in your Activity A's onActivityResult() function do this:-
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (resultCode==YOUR_CODE)
{
String value = (String) data.getExtras().getString("NAME OF THE PARAMETER"); //get Data here
}
}
}
In kotlin: -
In class A
startActivityForResult(Intent(context, B::class.java), 143)
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == 143) {
if (data!!.extras.get("check").equals("0")) {
childpager.currentItem = 0
}
}
}
In Class B
val intent = Intent()
intent.putExtra("check", "0")
setResult(Activity.RESULT_OK, intent)
I am using StartActivityForResult for multiple activities. My main activity is where I initialize it. On my second activity I input some values and pass to a third activity. Now, When i'm on the third activity I want to be able to go back to the second activity if ever I want to edit the values i passed. What should I do?
MainAct.java
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE)
{
if (resultCode == Activity.RESULT_OK)
{
//Something
}
}
SecondAct.java
Intent vd2 = new Intent(ViolatorDetails1.this,ViolatorDetails2.class);
vd2.putExtra("name",name);
vd2.putExtra("lname",lname);
vd2.putExtra("lnumber",lnumber);
vd2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
vd2.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT);
startActivity(vd2);
finish();
ThirdAct.java
Intent intent = new Intent();
intent.putExtra("firstname",name);
intent.putExtra("lastname", lname);
intent.putExtra("licensenumber", lnumber);
setResult(Activity.RESULT_OK, intent);
finish();
How can I go back to second Activity from third activity to edit some values if ever?
You should not call finish() on second activity when starting the third one.
Then onActivityResult() will be call when third activity is finished.
Call
startActivityForResult(vd2);
instead of
startActivity(vd2);
simply remove finish();
Intent vd2 = new Intent(ViolatorDetails1.this,ViolatorDetails2.class);
vd2.putExtra("name",name);
vd2.putExtra("lname",lname);
vd2.putExtra("lnumber",lnumber);
vd2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
vd2.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT);
startActivity(vd2);
finish(); //remove this line
in this way when your third activity closes user will go back to 2nd one, also you should implement onActivityResult in your 2nd activity so you can handle weather user wants to edit or has finished and should go back to 1st activity! (i.e. setting the result of the intent came from 1st activity and finish the 2nd one!)
here is what I mean in code:
In your 2nd activity do this,
#override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE)
{
if (resultCode == Activity.RESULT_OK)
{
// user should have done his job on 3rd activity and we should finish the 2nd activity to go back to first activity!
}else{
//user still editing!
}
}
and instead of startActivity(vd2); do startActivityForResult(vd2);
I'm wondering, is it possible to send information to the activity that I return to after calling finish()?
For example, I have an Activity SendMessageActivity.class which allows the user to post a message to their feed. Once that message has been saved to the server, I call finish(). Should I instead just start my MainActivity.class with a new Intent? Or is it better for life cycle development to just finish SendMessageActivity.class?
I don't see the point of starting a new activity since closing the current one will always bring you back to MainActivity.class. How can I just send a String extra after finishing the current Activity?
Use onActivityResult.
This might help you to understand onActivityResult.
By using startActivityForResult(Intent intent, int requestCode) you can start another Activity and then receive a result from that Activity in the onActivityResult() method.So onActivityResult() is from where you start the another Activity.
onActivityResult(int requestCode, int resultCode, Intent data) check the params here. request code is there to filter from where you got the result. so you can identify different data using their requestCodes!
Example
public class MainActivity extends Activity {
// Use a unique request code for each use case
private static final int REQUEST_CODE_EXAMPLE = 0x9988;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create an Intent to start AnotherActivity
final Intent intent = new Intent(this, AnotherActivity.class);
// Start AnotherActivity with the request code
startActivityForResult(intent, REQUEST_CODE_EXAMPLE);
}
//-------- When a result is returned from another Activity onActivityResult is called.--------- //
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// First we need to check if the requestCode matches the one we used.
if(requestCode == REQUEST_CODE_EXAMPLE) {
// The resultCode is set by the AnotherActivity
// By convention RESULT_OK means that what ever
// AnotherActivity did was successful
if(resultCode == Activity.RESULT_OK) {
// Get the result from the returned Intent
final String result = data.getStringExtra(AnotherActivity.EXTRA_DATA);
// Use the data - in this case, display it in a Toast.
Toast.makeText(this, "Result: " + result, Toast.LENGTH_LONG).show();
} else {
// AnotherActivity was not successful. No data to retrieve.
}
}
}
}
AnotherActivity <- This the the one we use to send data to MainActivity
public class AnotherActivity extends Activity {
// Constant used to identify data sent between Activities.
public static final String EXTRA_DATA = "EXTRA_DATA";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_another);
final View button = findViewById(R.id.button);
// When this button is clicked we want to return a result
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Create a new Intent as container for the result
final Intent data = new Intent();
// Add the required data to be returned to the MainActivity
data.putExtra(EXTRA_DATA, "Some interesting data!");
// Set the resultCode to Activity.RESULT_OK to
// indicate a success and attach the Intent
// which contains our result data
setResult(Activity.RESULT_OK, data);
// With finish() we close the AnotherActivity to
// return to MainActivity
finish();
}
});
}
#Override
public void onBackPressed() {
// When the user hits the back button set the resultCode
// to Activity.RESULT_CANCELED to indicate a failure
setResult(Activity.RESULT_CANCELED);
super.onBackPressed();
}
}
Note : Now check in MainActivity you startActivityForResult there you specify a REQUEST_CODE. Let's say you want to call three different Activities to get results.. so there are three startActivityForResult calls with three different REQUEST_CODE's. REQUEST_CODE is nothing but a unique key you specify in your activity to uniquely identify your startActivityForResult calls.
Once you receive data from those Activities you can check what is the REQUEST_CODE, then you know ah ha this result is from this Activity.
It's like you send mails to your lovers with a colorful covers and ask them to reply in the same covers. Then if you get a letter back from them, you know who sent that one for you. awww ;)
You can set result of an activity, which allow you to data into an initent.
In your first activity, call the new one with startActivityForResult() and retrieve data in method onActivityResult. Everything is in documentation.
try this:
in First Activity:
Intent first = new Intent(ActivityA,this, ActivityB.class);
startActivityForResult(first, 1);
Now in Second activity: set Result during finish()
Intent intent = new Intent();
intent.putExtra("result",result); //pass intent extra here
setResult(RESULT_OK,intent);
finish();
First activity Catch the result;
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 1
if(requestCode==1)
{
String message=data.getStringExtra("result");
//get the result
}
}
If you call finish() to avoid that the user go back to SendMessageActivity.class, you can set this flags to your intent:
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
This will open the MainActivity and remove the SendMessageActivity from the activities stack.
I'm new to android . This might be the simplest question of all !! but I couldn't figure out whats gone wrong here,
I was trying to create a basic example for passing values through intent.So I need to pass data to Main Activity when I close my Second Activity here is the code
IntentTest1(MainActivity)
public void onClick(View arg0) {
// TODO Auto-generated method stub
MyClass.myToast("Clicked",getApplicationContext());
Intent myIntent = newIntent(getApplicationContext(),SecondPage.class);
startActivityForResult(myIntent,0);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if(requestCode == 0 && resultCode == RESULT_OK)
if(data.hasExtra("title"))
{
MyClass.myToast(""+resultCode+""+requestCode, getApplicationContext());
String str = data.getExtras().getString("title").toString();
titleText.setText(str);
}
super.onActivityResult(requestCode, resultCode, data);
}
SeconPage
public void finish()
{
Intent returnIntent = new Intent(getApplicationContext(),Intenttest1.class);
returnIntent.putExtra("Welcome Back!!","title");
setResult(RESULT_OK, returnIntent);
// below was for tosting and it works!!
MyClass.myToast("finally",getApplicationContext());
super.finish();
}
I think there is some mistake in receiving the intent ,I couldn't figure out.
Answers and Advises are needed
thanks in advance
The first problem is when you create your Intent to send back to the first Activity. Since you are using startActivityForResult() you want to use an empty constructor. So change
Intent returnIntent = new Intent(getApplicationContext(),Intenttest1.class);
to
Intent returnIntent = new Intent();
The second problem is that you have your key/value pair backwards in your Extras. The key, which is what you look for with getStringExtra() etc... should be the first in the pair. So this
returnIntent.putExtra("Welcome Back!!","title");
should be
returnIntent.putExtra("title", "Welcome Back!!");
Off-topic
I would consider using relevant names as your params. For example, I would change your onClick() from
public void onClick(View arg0)
to
public void onClick(View view)
view, v, or something similar makes more sense since the argument actually is a view and it will be more readable
I would also recommend using the Activity Context for your Intent which you can get from the argument (the View) passed into onClick(). So change it to
public void onClick(View v)
{
MyClass.myToast("Clicked",getApplicationContext());
Intent myIntent = newIntent(v.getContext(),SecondPage.class);
startActivityForResult(myIntent,0);
You have to use
if(data.hasExtra("Welcome Back!!"))
instead of
if(data.hasExtra("title"))
in onActivityResult. Welcome Back!! is the key and title is the value for that key in your extras.
try this code:
Intent returnIntent = new Intent(getApplicationContext(),Intenttest1.class);
returnIntent.putExtra("Key name here in ur case title","Value name");
setResult(RESULT_OK, returnIntent);
// below was for tosting and it works!!
MyClass.myToast("finally",getApplicationContext());
super.finish();
}
I am currently trying to send data from a child activity back to its parent activity. I have used the startActivityForResult() to go to my child activity. However I cannot understand what I would do to put the data I want to put back to my intent and make my parent activity receive it. I have been looking at different examples online but I think it is only throwing the result variable.
As per my understanding this is what I used when I return my child activity back to the parent activity:
String somestring = "somevalue";
Intent i = getIntent();
setResult(RESULT_OK, i);
finish();
I want to load the content of the string somestring for it to return back to the parent activity.
How can I load it back to my parent activity?
startActivityForResult(intent, 1);
And lastly how can I capture the data in my parent activity in the onActivityResult?
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode,resultCode,data);
}
Add your data to an intent, just as you would in any other situation:
Intent intent=new Intent();
intent.putExtra("ComingFrom", "Hello");
setResult(RESULT_OK, intent);
finish();
Then retrieve it in onActivityResult in your other activity.
#Override
public void onActivityResult(int requestCode,int resultCode,Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
String extraData=data.getStringExtra("ComingFrom"));
}