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) {
Related
I am facing a strange issue while returning to an Activity with a Result, I am passing an Intent for startActivityForResult from an Adapter like this :
Intent i = new Intent(activity, EditInfoActivity.class);
i.putExtra("id", list.get(position).getID());
activity.startActivityForResult(i, 100);
and in second Activity i.e. in EditInfoActivity in my case on a Button click I am setting Result for first activity like this:
Intent i = getIntent();
i.putExtra("isDataChange", isDataChange);
setResult(100, i);
finish();
In Activity's onActivityResult method I am able to get result code but getting Intent null.
Why? anybody have any idea on this please share.
in Activity:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100) {
//Here data is null and app crash
if (data.getExtras() != null && data.getBooleanExtra("isDataChange", false)) {
recreate();
}
}
}
First, you need to start the Activity with a REQUEST_CODE:
// Here we set a constant for the code.
private final int REQUEST_CODE = 100;
Intent i = new Intent(activity, EditInfoActivity.class);
i.putExtra("id", list.get(position).getID());
activity.startActivityForResult(i, REQUEST_CODE);
Then you need to send RESULT_OK when finishing EditInfoActivity:
Intent i = getIntent();
i.putExtra("isDataChange", isDataChange);
setResult(RESULT_OK, i);
finish();
Then handle the result on your first activity with this:
Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// REQUEST_CODE is defined as 100
if (resultCode == RESULT_OK && requestCode == 100) {
// do process
}
}
setResult TAKES RESULT_CODE instead of REQUEST_CODE.
Replace your code with this, May be it will solve your problem.
setResult(RESULT_OK, i);
And in yout onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
//Here data is null and app crash
if (data != null && data.getBooleanExtra("isDataChange", false)) {
recreate();
}
}
}
Two mistakes. You are passing the intent that was used to launch the activity you are finishing. Use new Intent() instead.
When setting activity result you should use result codes, not a request code setResult(RESULT_OK) alternatively RESULT_CANCELED and handle the response accordingly.
I am trying to get results back from intents in android studio.
In my main I start an activity and use startActivityForResult(intent, 1)
I then use get results in mainActivity from activity 2's setResults()
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if(resultCode == RESULT_OK){
Bundle extras = data.getExtras();
if (extras != null) {
String name = extras.getString("FIRSTNAME");
String Lname = extras.getString("LASTNAME");
int ID = extras.getInt("ID");
//TODO: Get the list fragment to newinstance with out new arraylist
Person p = new Person(name, Lname, ID);
people.add(p);
getFragmentManager().beginTransaction().replace(R.id.content_main, FullList.newInstance(people)).commit();
}
In my fragment in activity 1 I am calling a new startActivityForResult(i, 2)
How do i get my main activity to grab the setResults()
from Activity 3?
Activity 3 is doing this:
Intent deleteIntent = new Intent();
deleteIntent.putExtra("FNAME", first);
deleteIntent.putExtra("LNAME", last);
deleteIntent.putExtra("ID", num);
setResult(RESULT_OK, deleteIntent);
finish();
I am trying to have my main activity call if (requestCode == 2)
But it works to no avail.
Here is the all the onActivityResult for reference:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if(resultCode == RESULT_OK){
Bundle extras = data.getExtras();
if (extras != null) {
String name = extras.getString("FIRSTNAME");
String Lname = extras.getString("LASTNAME");
int ID = extras.getInt("ID");
//TODO: Get the list fragment to newinstance with out new arraylist
Person p = new Person(name, Lname, ID);
people.add(p);
getFragmentManager().beginTransaction().replace(R.id.content_main, FullList.newInstance(people)).commit();
}
// NOW SEEING IF THE DETAILS SCREEN PASSED BACK RESULTS
} else if (requestCode == 2) {
if (resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
if (extras != null) {
String name = extras.getString("FNAME");
String Lname = extras.getString("LNAME");
int ID = extras.getInt("ID");
Person p = new Person(name, Lname, ID);
// Delete happens here //
if (people.contains(p)) {
people.remove(p);
// If empty show blank frag, if not, update list //
if (people.isEmpty()) {
getFragmentManager().beginTransaction().replace(R.id.content_main, BlankList.newInstance());
} else {
getFragmentManager().beginTransaction().replace(R.id.content_main, FullList.newInstance(people)).commit();
}
} else {
Toast.makeText(this, "DIDNT RECEIVE SAME INFO", Toast.LENGTH_SHORT).show();
}
}
}
}
// END ELSE CHECK
}
}
Here is the code that is calling the startActivityForResult() in the Fragment on activity 1.
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
//super.onListItemClick(l, v, position, id);
ArrayList<Person> people = (ArrayList<Person>) getArguments().getSerializable(ARG_People);
if (people != null && position != -1) {
Person listPerson = people.get(position);
Intent i = new Intent("OPENDETAILS");
i.putExtra("NAME", listPerson.name);
i.putExtra("LASTNAME", listPerson.lName);
i.putExtra("ID", listPerson.ID);
startActivityForResult(i, 2);
} else {
Toast.makeText(getActivity(), "EMPTY LIST ERROR", Toast.LENGTH_SHORT).show();
}
}
It's a little unclear what you're trying to do, but it sounds like:
Activity1 starts Activity2 for result
Activity2 starts Activity3 for result
Activity3 returns a result
Activity1 is expected receive Activity3's result.
If I got that right then the key element that seems to be missing here is that you are expecting Activity1 to get a result from Activity3 even though it was Activity2 that started it for result. In this case you should implement onActivityResult in Activity2, handle the results coming back from Activity3 and set them as Activity2's results to pass back to Activity1 and then finish; An activity will only receive results from activities it directly starts via startActivityForResult.
Use different code to launch different activities,
such as
startActivtityForResult(new Intent(this,Person1.class),1);
startActivtityForResult(new Intent(this,Person2.class),2);
startActivtityForResult(new Intent(this,Person3.class),3);
then on activityresult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (resultCode) {
case 1:
//implement your code here
break;
case 2:
//implement your code here
break;
case 3:
//implement your code here
break;
}
}
then set Retrun result in these classes
Person1.class
return_intent.putExtra("result", 1);
setResult(1, return_intent);
Person2.class
Person1.class
return_intent.putExtra("result", 2);
setResult(2, return_intent);
Person3.class
Person1.class
return_intent.putExtra("result", 3);
setResult(3, return_intent);
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 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();
}
}
}
Here is my first activity code from where I call the second Activity:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT){
startActivityForResult(new Intent("chap.two.Chapter2Activity2"),request_Code);
}
return false;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == request_Code) {
if (resultCode == RESULT_OK)
Toast.makeText(this,data.getData().toString(),Toast.LENGTH_SHORT).show();
}
}
And here is a code of chap.two.Chapter2Activity2:
Button n = (Button) findViewById(R.id.btn_OK);
n.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent data = new Intent();
//---get the EditText view---
EditText txt_username =(EditText) findViewById(R.id.txt_username);
//---set the data to pass back---
data.setData(Uri.parse(txt_username.getText().toString()));
setResult(RESULT_OK, data);
//---closes the activity---
finish();
}
});
here I see that setResult(RESULT_OK, data) has two arguments but
onActivityResult(int requestCode, int resultCode, Intent data) has three and I want know how onActivityResult gets value for third parameter? How it works can anyone tell me? Why isn't this error ?
When you call Activity.startActivityForResult(), you set the requestCode. Later, this request code is needed by onActivityResult() in order to determine what Activity is sending data to it. We don't need to supply requestCode again on setResult() because the requestCode is carried along.
The data is intent data returned from launched intent. We usually use this data when we set extras on the called intent.
Consider this example:
CALL SECOND ACTIVITY
Intent i = new Intent(MainActivity.this, CheckActivity.class);
startActivityForResult(i, REQUEST_CODE_CHECK);
ON SECOND ACTIVITY, SET INTENT RESULT
getIntent().putExtra("TADA", "bla bla bla");
setResult(RESULT_OK, getIntent());
finish();
BACK TO FIRST ACTIVITY, ONACTIVITYRESULT()
if(requestCode == REQUEST_CODE_CHECK && resultCode == RESULT_OK){
text1.setText(data.getExtras().getString("TADA") );
}
There you go. You should now understand what is Intent data and how to set and fetch the value.
Third parameter is Intent, which you sent from the sub-Activity(Second Activity, which is going to finish).
If you want to perform some calculations or fetch some username/password in sub-activity and you want to send the result to the main activity, then you place the data in the intent and will return to the Main activity before finish().
After that you will check in onActivityResult(int, int, Intent) in main activity for the result with Intent parameter.
Example::
MainActivity:
public void onClick(View view) {
Intent i = new Intent(this, subActivity.class);
startActivityForResult(i, REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
if (data.hasExtra("username") && data.hasExtra("password")) {
String username = data.getExtras().getString("username");
String password = data.getExtras().getString("password");
}
}
subActivity::
#Override
public void finish() {
// Create one data intent
Intent data = new Intent();
data.putExtra("username", "Bla bla bla..");
data.putExtra("password", "*****");
setResult(RESULT_OK, data);
super.finish();
}