I want to call a method from mainactivity in other activities. For that, I've researched a lot and found that using OnActivityResult is the best option. Can anyone please explain how to use this method with the help of an example? I've gone through similar questions but found them confusing.
Thanks!
EDIT:I have a custom dialog activity in my app. It asks the users whether they want to start a new game or not and it has two buttons yes and no. I want to implement the above method only to get the pressed button.
Define constant
public static final int REQUEST_CODE = 1;
Call your custom dialog activity using intent
Intent intent = new Intent(Activity.this,
CustomDialogActivity.class);
startActivityForResult(intent , REQUEST_CODE);
Now use onActivityResult to retrieve the result
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
try {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
String requiredValue = data.getStringExtra("key");
}
} catch (Exception ex) {
Toast.makeText(Activity.this, ex.toString(),
Toast.LENGTH_SHORT).show();
}
}
In custom dialog activity use this code to set result
Intent intent = getIntent();
intent.putExtra("key", value);
setResult(RESULT_OK, intent);
finish();
Start the Activity:
you do need to pass an additional integer argument to the startActivityForResult() method.You may do it by defining a constant or simply put an integer.The integer argument is a "request code" that identifies your request. When you receive the result Intent, the callback provides the same request code so that your app can properly identify the result and determine how to handle it.
static final int ASK_QUESTION_REQUEST = 1;
// Create an Intent to start SecondActivity
Intent askIntent = new Intent(FirstActivity.this, SecondActivity.class);
// Start SecondActivity with the request code
startActivityForResult(askIntent, ASK_QUESTION_REQUEST);
Return The Result:
After completing your work in second activity class simply set the result and call that activity where it comes from and lastly don't forget to write finish() statement.
// Add the required data to be returned to the FirstActivity
sendIntent.putExtra(Result_DATA, "Your Data");
// Set the resultCode to Activity.RESULT_OK to
// indicate a success and attach the Intent
// which contains our result data
setResult(RESULT_OK, sendIntent);
// With finish() we close the SecondActivity to
// return to FirstActivity
finish();
Receive The Result:
When you done with the subsequent activity and returns, the system calls your activity's onActivityResult() method. This method includes three arguments:
#The request code you passed to startActivityForResult().
#A result code specified by the second activity. This is either RESULT_OK if the operation was successful or RESULT_CANCELED if the operation failed
#An Intent that carries the result data.
#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 1
if (requestCode == ASK_QUESTION_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
final String result = data.getStringExtra(SecondActivity.Result_DATA);
// Use the data - in this case display it in a Toast.
Toast.makeText(this, "Result: " + result, Toast.LENGTH_LONG).show();
}
}
}
This is my example.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Image_Request_Code && resultCode ==RESULT_OK && data != null && data.getData() != null) {
FilePathUri = data.getData();
try {
// Getting selected image into Bitmap.
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), FilePathUri);
// Setting up bitmap selected image into ImageView.
SelectImage.setImageBitmap(bitmap);
// After selecting image change choose button above text.
ChooseButton.setText("Image Selected");
}
catch (IOException e) {
e.printStackTrace();
}
}*strong text*
if (requestCode == 2000)
{
if (resultCode == Activity.RESULT_OK)
{
try {
Uri selectedImages = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().getContentResolver().query(selectedImages,
filePathColumn,null,null,null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
receivedImageBitmap = BitmapFactory.decodeFile(picturePath);
imageView.setImageBitmap(receivedImageBitmap);
}
catch (Exception e)
{
Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
Related
I have the following code
public void changeContentOnClick(View view) {
Intent intent = new Intent(this, ChangeNodeContentActivity.class);
intent.putExtra("SELECTED_NODE_ID", selectedNode.getNodeId());
intent.putExtra("SELECTED_NODE_CONTENT", selectedNode.getNodeContent());
startActivityForResult(intent,RESULT_OK);
Log.d(TAG, "Can I get here?");
onActivityResult(RESULT_OK, RESULT_OK, intent);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
try {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
String editedNodeId = data.getStringExtra("EDITED_NODE_ID");
String editedNodeContent = data.getStringExtra("EDITED_NODE_CONTENT");
Node nodeChecker = new Node(editedNodeId);
Node editedNode = new Node(editedNodeId, editedNodeContent);
Log.d(TAG, editedNode.toString());
nodes.set(nodes.indexOf(nodeChecker), editedNode);
adapter.notifyDataSetChanged();
}
} catch (Exception e) {
Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
}
}
Somehow, after startActivityForResult method is called, everything stops. The log with message "Can I get here?" is never printed and I don't understand why not. I have followed the answer to this topic, but somehow couldn't make it work. Do I call the onActivityResult in the wrong way or place? Please help me out!
The that should send back some info from the ChangeNodeContentActivity and the one that handles the result code is the following on click listener:
public void changeContentOnClick(View view) {
Intent intent = getIntent();
selectedNode.setNodeContent(nodeContentDisplay.getText().toString());
intent.putExtra("EDITED_NODE_ID", selectedNode.getNodeId());
intent.putExtra("EDITED_NODE_CONTENT", selectedNode.getNodeContent());
setResult(RESULT_OK, intent);
Log.d(TAG, selectedNode.toString());
finish();
}
startActivityForResult() method receives an intent and requestCode, so you should change it to:
startActivityForResult(intent, REQUEST_CODE)
And onActivityResult() method is automatically called when returning from the activity, so you should remove the direct call you made to the method, i.e. onActivityResult(RESULT_OK, RESULT_OK, intent)
Here is my code:
final Intent intent = new Intent(this, SelectWidgetActivity.class);
startActivityForResult(intent, REQUEST_CREATE_APPWIDGET);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK ) {
String selectedName = data.getStringExtra(SelectWidgetActivity.SELECTED_WIDGET);
if(!mAppWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId, info.provider)) {
Intent bindIntent = new Intent(AppWidgetManager.ACTION_APPWIDGET_BIND);
bindIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
bindIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER, info.provider);
bindIntent.putExtra(SelectWidgetActivity.SELECTED_WIDGET, selectedName);
startActivityForResult(bindIntent, REQUEST_BIND_APPWIDGET);
}
}
}
I put String on the first call of startActivityForResult and on the second call I'm trying to get the same string, but getting null. For example on the first call selectedName="Calendar", the second call onActivityResult() selectedName=null
Any ideas?
you must be even checking for the requestCode in onActivityResult that you send when you are making this call
startActivityForResult(intent, REQUEST_CREATE_APPWIDGET);
Try this
if (requestCode == REQUEST_CREATE_APPWIDGET && resultCode == Activity.RESULT_OK) {
//do your work here;
}
I have an activity B called by an activity A.
In activity A:
intent = new Intent (MainActivity.this, SelectionActivity.class);
startActivityForResult(intent, RESULT_OK);
In activity B (it's about a ListView when items are clicked):
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
TextView tv = (TextView)arg0.getChildAt(arg2);
String key = tv.getText().toString();
Intent myIntent = new Intent();
myIntent.putExtra("genre", key);
setResult(RESULT_OK,myIntent);
finish();
}
And I override the onActivityResult method like this in A:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (data != null) {
Bundle b = data.getExtras();
String str = b.getString("genre");
Log.v("nope","loaded ! " + str);
r.LoadGenre(str);
}
Log.v("nope"," not loaded ! ");
}
}
But I'm never reaching any of these Log.v messages.
LogCat is clear, no errors. When running, A, it starts B perfectly, when items are clicked on B, B closes perfectly to get back to A.
You do need to pass request code to the startActivityForResult() method.
The "request code" identifies your request. When you receive the result Intent, the callback provides the same request code so that your app can properly identify the result and determine how to handle it.
In your case you didn't checking received result with requestcode
So check requestCode also in your onActivityResult method.So Change
startActivityForResult(intent, RESULT_OK);
to
startActivityForResult(intent, 200);
and
if (resultCode == RESULT_OK) {
to
if (requestCode == 200 && resultCode == RESULT_OK) {
This question already has answers here:
How to manage startActivityForResult on Android
(14 answers)
Closed 8 years ago.
I am new to android development
I call an intent now how can i get result from called activity
can any one tell me how to perform this task ?
i have called intent like.
Intent I = new Intent (this ,abc.class);
startActivity(i);
thanks
Use startActivityForResult and then override onActivityResult in your FirstActivity.
In FirstActivity
Intent intent = new Intent(FirstActivity.this,SecondActivity.class);
startActivityForResult(intent, 2);// Activity is started with requestCode 2
Override onActivityResult
#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");
Log.i("Message is",message);
// logs Testing
}
}
In SecondAcivity
Intent intent=new Intent();
intent.putExtra("MESSAGE","Testing");
setResult(2,intent);
finish();//finishing activity
Reference to the docs:
http://developer.android.com/reference/android/app/Activity.html#startActivityForResult(android.content.Intent, int)
Example:
http://www.javatpoint.com/android-startactivityforresult-example
For going to second activity use startActivityForResult in your firstclass
Intent callIntent = new Intent(FirstClass.this, SecondClass.class);
startActivityForResult(callIntent, 1);
then override onActivityResult method in your first class like this
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == 1) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// get values from data
}
} }
In your second class do this for returning back, if you want to send
something to first class. Store this in your intent.
Intent result = new Intent(); setResult(Activity.RESULT_OK, result);
finish();
hi you can get result calling activity
Start activity with startActivityForResult(intent, 0);
add below method in calling activity
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
// do your task
} else if (resultCode == RESULT_CANCELED) {
// do your task
}
}
}
In your main Class....
static final int CODE_REQUEST = 1; // The request code
....
Intent pickContactIntent = new Intent(MainClass.this, CallingClassName.class);
startActivityForResult(pickContactIntent, CODE_REQUEST);
..........
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == PICK_CONTACT_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// The user picked a contact.
// The Intent's data Uri identifies which contact was selected.
// Do something with the contact here (bigger example below)
}
}
}
In your calling class
Intent result = new Intent();
setResult(Activity.RESULT_OK, result);
finish()
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());