How to handle getResults from multiple activities? - android

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);

Related

Get value from returnActivity when backpressed android

I have 2 activities in my Android application, Activity1 and Activity2.
I want to display the data retrieved from a String in Activity2 and this string value set text in Activity 1 textview when back is pressed from Activity2.
Please anyone give the solution for this problem,thanks in advance.
Activity 2: here I pass the string value to Activity 1 when I back press the Activity 2 this will be retrieved to Activity 1.
public void onBackPressed() {
// TODO Auto-generated method stub
NoolDataBaseHelper db = new NoolDataBaseHelper(NoolDashboardDetailPage.this);
int strtext = db.getProfilesCount();
db.close();
Intent intent = new Intent();
intent.putExtra("Obj", strtext+"");
setResult(Activity.RESULT_OK, intent);
if (isclose) {
finish();
}
else
{
if (!isplays) {
inflateLoginlayout.setVisibility(View.GONE);
topview.setVisibility(View.VISIBLE);
isplays = true;
//edtnames.getText().clear();
}
else
{
super.onBackPressed();
}
}
}
Activity1: here i retreive the string from Activity 2 and set the string value to my textview
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if (resultCode == Activity.RESULT_OK) {
String sSuName = data.getStringExtra("Obj");
txtfavouratecount.setText(sSuName);
} else if (resultCode == 0) {
}
}
}
You should follow this structure
In Activity 1
Intent intent=new Intent(Activity1.this,Activity2.class);
startActivityForResult(intent, 2);// Activity is started with requestCode 2
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// check the request code here is 2
if(requestCode==2){
if(resultCode == 3){ // check the result code
String message=data.getStringExtra("MESSAGE");
// set text for your textview
textView1.setText(message);
}
}
}
In Activity 2
public void onBackPressed() {
String message = "abc";
Intent intent=new Intent();
intent.putExtra("MESSAGE",message);
setResult(3,intent); // 3 is result code
super.onBackPressed();
}
Hope this help

Why does onActivityResult fail to enter method?

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) {

resultCode is 0 besides the using startActivityForResult and setResult

I use startActivityForResult for Activity1 to start Activity2 :
btnSelectFiles.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
savePreferences();
Intent i = new Intent(getApplicationContext(),
FileManagerActivity.class);
Bundle mBundle = new Bundle();
mBundle.putString("FileManager", "NewOrder");
i.putExtras(mBundle);
startActivityForResult(i, Constants.addFilesCode);
}
});
onActivityResult method :
and in Activity2 :
Intent returnIntent = new Intent();
setResult(1,returnIntent);
FileManagerActivity.this.finish();
But in the Activity1
requestCode is correct, but the resultCode is always 0.
I do not use Back buttons.
my onActivityResult in the Activity1
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.i(TAG, "onActivityResult");
Log.i(TAG,
"onActivityResult requestCode" + Integer.toString(requestCode)
+ "resultCode" + Integer.toString(resultCode));
// adding files to the list if the files were added successfully
if (requestCode == Constants.addFilesCode)
{
// successfull operation
if (resultCode == 1)
{
if (adapter == null)
addFiles();
else if (adapter.getCount() == 0)
addFiles();
else {
adapter.notifyDataSetChanged();
changeFileHeader();
}
btnFilesRemove.setVisibility(View.VISIBLE);
for (int b = 0; b < FileManagerActivity.getFinalAttachFiles()
.size(); b++) {
checks.add(b, 0);
}
}
}
My issue was that I was starting activity with FLAG_ACTIVITY_NO_HISTORY. As soon as I removed it, resultCode started propagating back to caller.

Why does onActivityResult return, but I am getting the correct requestCode?

I'm building an application where the first Activity starts another one by startActivityByResult. After some setting is done, I need to send the setting result back.
So I override the second Activity's onPause() method, I get the intent, putExra, and send it back through setResult().
Back to the first Activity. onActivityResult has definitely been called. I got the resultCode set before, but the intent data is null. I can't figure out what's wrong.
Here's my code:
The first Activity
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.e("page1", requestCode + "_");
Log.e("page1", resultCode + "_");
Log.e("page1", (data == null) + "_");
// if ((requestCode == 1) && (data != null)) {
if (data != null) {
String size = data.getStringExtra("size");
Log.e("switch", size + "_");
switch (size.charAt(0)) {
case '1': {
text.setTextSize(10);
}
break;
case '2': {
text.setTextSize(20);
}
break;
case '3': {
text.setTextSize(30);
}
break;
}
}
}
My second Activity
#Override
protected void onPause() {
Intent intent = getIntent();
Log.e("prefs", (intent == null) + "_");
intent.putExtra("size", size);
setResult(3, intent);
super.onPause();
}
I've tested in LogCat. In the second Activity. The intent about to be sent is definitely not null. But when it goes to the first Activity. Null just returned. This is driving me really crazy.
Problem with your code is in String size = data.getStringExtra("size"); this line.
You should change it with String size = data.getExtras.getString("size");
In your first activity:
Intent intent = new Intent(context,SecondActivity.class);
startActivityForResult(intent, REQUEST_CODE);
And in your second activity make a button called SAVE and in its listener;
Intent result = new Intent();
Bundle bundle = new Bundle();
bundle.putString("keyName", "KeyValue");
result.putExtras(bundle);
setResult(RESULT_OK,result);
finish();
And again in your first activity's onActivityresult method:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode==RESULT_OK){
if(requestCode == REQUEST_CODE){
Log.d("Activity Result", data.getExtras.getString("keyName");
}
}
}
Can you try this.
you want to finish your activity in all the cases in pause manually and in back press automatically so it will be better to save your intent data in onDestroy
#Override
protected void onPause() {
super.onPause();
finish();
}
#Override
public void onDestroy() {
Intent intent = getIntent();
intent.putExtra("size", size);
setResult(3, intent);
super.onDestroy();
}

startActivityForResult and Intents Extras, it seems extras are not pushed back

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());

Categories

Resources