I would like to ask if there is a way to put Extras or Bundle when you call finish() method.
For example just like calling an Activity you can do this:
Intent intent = new Intent(view.getContext(), AddListing.class);
intent.putExtra("user_id", userID);
startActivity(intent);
is it possible to use it in finish()?
Thanks.
If you are looking to pass back results when an Activity is destroyed, what you should be looking for is : startActivityForResult.
There are two variants of startActivityForResult() , which allows to pass bundle as well in case of a necessity:
public void startActivityForResult (Intent intent, int requestCode)
public void startActivityForResult (Intent intent, int requestCode, Bundle options)
See this example to understand the concept better:
MainActivity.java:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView1=(TextView)findViewById(R.id.textView1);
button1=(Button)findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent=new Intent(MainActivity.this,SecondActivity.class);
startActivityForResult(intent, 2);// Activity is started with requestCode 2
}
});
}
// Call Back method to get the Message from other Activity
#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 message=data.getStringExtra("MESSAGE");
textView1.setText(message);
}
}
SecondActivity.java:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
editText1=(EditText)findViewById(R.id.editText1);
button1=(Button)findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
String message=editText1.getText().toString();
Intent intent=new Intent();
intent.putExtra("MESSAGE",message);
setResult(2,intent);
finish();//finishing activity
}
});
}
No finish() method is available with intent as it's parameter.If you want to pass some data back to calling Activity you can use setResult(int resultCode, Intent intent) before calling finish(). In this method you will need to pass bundle or extras in intent. And accept it in onActivityResult method in calling activity. This is the only way to pass data back to calling Activity. You can refer this link https://developer.android.com/training/basics/intents/result.html
Define the userId-->after the intent initiation ,
Example,
Intent i = new Intent(1st.this, 2nd.class);
String sDate = Dpcheckin.getText().toString();
String eDate = Dpcheckout.getText().toString();
String roomtext=RoomText.getText().toString();
i.putExtra("date1", sDate);
i.putExtra("date2", eDate);
i.putExtra("roomtext",roomtext);
startActivity(i);
where,
Mainly you need to define 2 classes inside the Intent,
1st one is the class from which you are sending the data, with(.this)extension.
2nd one is the class you are receiving the data , with (.class)extension.
Related
I have an activity that very quickly has to process data and then return to the previous activity, I give an example: I have a MainActivity class that passes information through Intent to another Loader class, this processes the data and sends it back to the MainActivity. I don't know how to put this procedure into practice...
From your MainActivity call the TargetActivity using startActivityForResult()-
For example:
Intent intent = new Intent(this, TargetActivity.class);
intent.putExtra(); // sent your putExtra data here to pass through intent
startActivityForResult(intent, 1000);
In your intent set the data which you want to return back to MainActivity. If you don't want to return back any data then you don't need to set any data.
For example:
In TargetActivity if you want to send back data:
Intent returnIntent = new Intent();
returnIntent.putExtra("result", result);
setResult(Activity.RESULT_OK, returnIntent);
finish();
If you don't want to return data:
Intent returnIntent = new Intent();
setResult(Activity.RESULT_CANCELED, returnIntent);
finish();
Now in your MainActivity class write following code for the onActivityResult() method.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1000) {
if(resultCode == Activity.RESULT_OK){
String result=data.getStringExtra("result");
}
if (resultCode == Activity.RESULT_CANCELED) {
// Do your task here.
}
}
}
//do Some work
Intent i = new Intent(this,MainActivity2..class);
startActivityForResult(i,12);
}
In MainActivity2.class
// after your work complete
Intent i =new Intent();
i.putExtra("result",true);// any data you want to pass
setResult(RESULT_OK,i);
After this we handle result
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
switch(requestCode){
case 12:
if(resultCode == Activity.RESULT_OK){// onsuccess do something
boolean isSucces = data.getBooleanExtra("result",false);
if(isSuccess)// perform action
{// show toast}
}
}
}
I find the best to use callbacks.
in Loader:
Create inner class
MyCallback callback;
viod setCallback(MyCallback callback){
this.callback = callback;
}
viod onStop(){
callback = null;
}
interface MyCallback{
void doSomething(Params params);
}
in MainActivity:
implement MyCallback
set reference in onCreate
Loader loader = new Loader();
loader.setCallback(this);
override method doSomething()
#override
void doSomething(Params params){
//do your thing with the params…
}
when the job is done inside Loader call MainActivity:
callback.doSomething(params);
destroy reference inside MainActivity in onStop()
loader.onStop();
By the help of android startActivityForResult() method, you can get result from another activity.
By the help of android startActivityForResult() method, you can send information from one activity to another and vice-versa. The android startActivityForResult method, requires a result from the second activity (activity to be invoked).
In such case, we need to override the onActivityResult method that is invoked automatically when second activity returns result.
MainActivity.java
public class MainActivity extends Activity {
TextView textView1;
Button button1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView1=(TextView)findViewById(R.id.textView1);
button1=(Button)findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent=new Intent(MainActivity.this,SecondActivity.class);
startActivityForResult(intent, 2);// Activity is started with
requestCode 2
}
});
}
// Call Back method to get the Message form other Activity
#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 message=data.getStringExtra("MESSAGE");
textView1.setText(message);
}
}
SecondActivity.java
public class SecondActivity extends Activity {
EditText editText1;
Button button1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
editText1=(EditText)findViewById(R.id.editText1);
button1=(Button)findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
String message=editText1.getText().toString();
Intent intent=new Intent();
intent.putExtra("MESSAGE",message);
setResult(Activity.RESULT_OK,intent);
finish();//finishing activity
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.second, menu);
return true;
}
}
I'm not sure if this is expected behavior, but if I do the following in OneActivity to launch TwoActivity:
Intent intent = new Intent(this, TwoActivity.class);
startActivityForResult(intent, RESULT_OK);
And in TwoActivity when I pass back to OneActivity:
Intent resultIntent = new Intent();
resultIntent.putExtra(SOURCE, TAG);
setResult(RESULT_OK, resultIntent);
finish();
With the above code and after overriding onActivityResult in OneActivity nothing happens. onActivityResult doesn't even seem to be called. If, however, I change RESULT_OK to 0, it works.
Is this expected? Has anyone else experienced that?
Check out the docs definition of the startActivityForResult method. It says:
requestCode int: If >= 0, this code will be returned in onActivityResult() when the activity exits.
So your request code should be >= 0. If you check the value of the RESULT_OK response code, it's -1. It's important to note that the request code isn't the same as the result code. The request code serves you to identify the request the result is for, and the result code tells you if the request was successful or not.
You are confusing two different concepts:
The requestCode (the second parameter to startActivityForResult) is a unique ID you assign that can be any positive integer.
The resultCode (the first parameter to setResult) must be one of the constants in the Activity class as seen in the setResult documentation
You'll note that your onActivityResult receives both the requestCode you pass into startActivityForResult and the resultCode that you've set in setResult - make sure you are comparing the right numbers in your onActivityResult
please check your code with this sample:
MainActivity:
public class MainActivity extends Activity {
TextView textView1;
Button button1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView1=(TextView)findViewById(R.id.textView1);
button1=(Button)findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent=new Intent(MainActivity.this,SecondActivity.class);
startActivityForResult(intent, 2);// Activity is started with requestCode 2
}
});
}
// Call Back method to get the Message form other Activity
#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 message=data.getStringExtra("MESSAGE");
textView1.setText(message);
}
}
}
and then SecondActivity:
public class SecondActivity extends Activity {
EditText editText1;
Button button1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
editText1=(EditText)findViewById(R.id.editText1);
button1=(Button)findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
String message=editText1.getText().toString();
Intent intent=new Intent();
intent.putExtra("MESSAGE",message);
setResult(2,intent);
finish();//finishing activity
}
});
}
I've got a class which handles a question sequence. It doesn't extend Activity. In the class there is the method:
public class QuizMaster {
public void startQuiz(Activity activity, Model model) {
//switch - case statement using model
Intent intent = new Intent(activity, QuestionTextActivity.class)
activity.startActivityForResult(intent, requestCode);
//other case statements with other intents
}
}
When I call this method from a working activity with
mQuizMaster.startQuiz(this, mModel);
And I finish() the child activity:
Intent returnIntent = new Intent();
returnIntent.putExtra(ARG_SELECTED_CHECKBOX, checkedBox);
setResult(RESULT_CODE, returnIntent);
finish();
it doesn't execute the parent activity's
#Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
Log.d(LOG_TAG, "OnActivityResult called in SignDetailsActivity. Resultcode is: ");
}
But when I execute the
Intent intent = new Intent(activity, QuestionTextActivity.class)
activity.startActivityForResult(intent, requestCode);
in the actual parent activity file, it does execute the onActivityResult method.
Why doesn't the child activity run the onActivityResult in the parent activity if sent with a non-activity class? How do i fix this?
I haven't found anyone with the same problem with executing new Intent() in a non-activity class like this. If there is someone, i didn't use the right search keywords and some others might type in the same as I did and come on this page.
You need to call setResult(int) before call finish(). This is from Activity documentation:
When an activity exits, it can call setResult(int) to return data back
to its parent. It must always supply a result code, which can be the
standard results RESULT_CANCELED, RESULT_OK, or any custom values
starting at RESULT_FIRST_USER. In addition, it can optionally return
back an Intent containing any additional data it wants. All of this
information appears back on the parent's Activity.onActivityResult(),
along with the integer identifier it originally supplied.
Here is my implementation, which worked:
MainActivity.java (parent activity)
public class MainActivity extends AppCompatActivity {
private Sample sample;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sample = new Sample();
sample.startActivity(MainActivity.this);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d("TEST", "DONE");
}
}
LaunchActivity.java (child activity)
public class LaunchActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launch);
Button btn = (Button) findViewById(R.id.button2);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setIntent(new Intent());
finish();
}
});
}
}
Sample.java (class start activity)
public class Sample {
public Sample () {}
public void startActivity (Activity a) {
Intent it = new Intent(a, LaunchActivity.class);
a.startActivityForResult(it, 0);
}
}
I am trying to call another app through intent, the app is called but the onActivityResult is not being called. Could someone please help me on this?
Below is my code:
public class EncryptCommandActivity extends Activity{
EncryptionFactory encryptionFactory = new EncryptionFactory();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.encrpyt_command_activity);
ActivityContexts.setEncryptCommandActivityContext(this);
Intent intent = new Intent("asd.com.qweapi.MAIN_ACTIVITY");
Bundle bundle = new Bundle();
bundle.putInt("Function", 1006);
bundle.putString("MSG", MQTTFactory.getById());
intent.putExtras(bundle);
startActivityForResult(intent, 0);
finish();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent pData)
{
super.onActivityResult(requestCode,resultCode,pData);
Log.d("Encrypt","Inside"); //not called
Toast.makeText(ActivityContexts.getMainActivityContext(),"encrypt", Toast.LENGTH_LONG).show(); //not called
}
}
You should remove finish() in onCreate() because it will finish activity and then it's no longer to exist, since can not fire onActivityResult()
move finish() to onActivityResult from onCreate
I have an activity A that calls an activity B (FragmentActivity) using startActivityForResult(). Before activity B finishes by calling finish(), I use setResult(). In spite of all of this, onActivityResult() is not called. I'm not sure what I'm doing wrong as I'm not doing anything unconventional, or if this is an Android bug.
Seeing some of the suggestions on here, I've checked to see that I don't have android:launchMode="singleInstance" nor android:noHistory="true" set anywhere in my manifest file.
Calling activity B from A:
Intent intent = new Intent(getActivity(), ActivityB.class);
startActivityForResult(intent, MY_RESULT);
Finishing activity B:
Intent intent = new Intent();
setResult(Activity.RESULT_OK, intent);
finish();
Overriding onActivityResult() in activity A:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
Toast.makeText(getApplication(), "toast", Toast.LENGTH_LONG).show();
}
Edit 1
I commented out nearly all of activity B's code (see below), leaving A's intact and the problem remained. So, A is definitely doing something strange that causes the problem. Worse, I have done this with other activities (using the same code) without any problems! A extends ExpandableListActivity, although I don't understand how any of that code would cause issues in onActivityResult(). Logcat isn't giving me anything useful.
This is the code tested for activity B, for posterity's sake (though it seems to be that the problem is in A):
public class ActivityB extends FragmentActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_activityb);
Intent intent = new Intent();
intent.putExtra("data", "Hello from ActivityB");
setResult(Activity.RESULT_OK, intent);
finish();
}
}
try this and verify with your code:
ActivityA.java
public class ActivityA extends Activity{
private static final int MY_RESULT = 0;
private Button btnStart;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_a);
btnStart=(Button)findViewById(R.id.btnstart);
btnStart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(this, ActivityB.class);
startActivityForResult(intent, MY_RESULT);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Toast.makeText(getApplication(), data.getStringExtra("data"), Toast.LENGTH_LONG).show();
}
}
ActivityB.java
public class ActivityB extends FragmentActivity{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_b);
Intent intent = new Intent();
intent.putExtra("data", "Hello from ActivityB");
setResult(Activity.RESULT_OK, intent);
finish();
}
}
Note : make sure you have added both the activity in your manifest file.
OK, thanks to everyone that pointed me in the right direction. I found the solution. The issue was that I was doing startActivityForResult() in a DialogFragment so I should have done
getActivity().startActivityForResult()
instead of just
startActivityForResult()
then it works as expected.