Finish the fragment while moving to other activity? - android

I have a main activity that contains 3 fragments. In each fragment I have a listView, on clicking which it is diverted to a new activity.
In the new Activity, I am changing the list view content that is clicked and diverting back to the main activity using intent.
This opens a new main Activity fragment and when I press back button I again get back to the previous Main Activity that was opened earlier.

Save activity's context in static variable like this
public class MainActivity extends AppCompatActivity {
public static MainActivity mainActivityInstance;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_staff_login);
//finishing older loaded mainActivity
if(MainActivity.mainActivityInstance!=null){
MainActivity.mainActivityInstance.finish();
}
mainActivityInstance=this;
}
}
From other activities you can finish your older activity like this
if(MainActivity.mainActivityInstance!=null){
MainActivity.mainActivityInstance.finish();
}

Instead of using startActivity use startActivityForResult in your fragment and have onActivityResult to obtain result from new Activity you have started
In your fragment do like this
static final int NEXT_ACTIVITY = 100;
//insert in listview on click
Intent intent = new Intent(context,Activity2.class);
intent.putExtra("key","value");//if needed
startActivityForResult(intent,NEXT_ACTIVITY);
#Override //*Note* you must override this method in you parent Activity in order to reflect the data inside your fragment
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode,resultCode,data);//while using inside fragment
switch(requestCode) {
case NEXT_ACTIVITY:
if (resultCode == RESULT_OK) {
Bundle res = data.getExtras();
String result = res.getString("param_result");
Log.d("FIRST", "result:"+result);
}
break;
}
}
In your new Activity while finishing/onBackpressed
Bundle data = new Bundle();
data.putString("param_result", "Thanks Thanks");
setResult(RESULT_OK, data);
finish();

For fragments, instead of finish();, you should call
getActivity().finish();

Related

Return result to Activity from DialogFragment

I am trying to do the following:
Show dialog fragment from an Activity (not Fragment);
Retrieve result in the Activity.
The problem is that onActivityResult in the Activity is not being called.
Here is how I am showing a DialogFragment
DriverRatingDialogFragment dp = new DriverRatingDialogFragment();
// this solution works well in case of showing dialog from a fragment
// but I have to show it from the Activity
// dp.setTargetFragment(getSupportFragmentManager().findFragmentById(R.id.flContent), DriverRatingDialogFragment.REQUEST_CODE);
dp.show(getSupportFragmentManager(), DriverRatingDialogFragment.ARG_RATING);
And here is how I am trying to return result from DialogFragment:
Intent intent = new Intent();
// This solution works well in case of previously setting target Fragment,
// but I have to return result to Activity
// getTargetFragment().onActivityResult(
// getTargetRequestCode(), REQUEST_CODE, intent);
// and with this attempt App crashes
// this.onActivityResult(REQUEST_CODE, Activity.RESULT_OK, intent);
here is where I want to retrieve result in the Activity, but it doesn't get called:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == DriverRatingDialogFragment.REQUEST_CODE) {
// todo
}
super.onActivityResult(requestCode, resultCode, data);
}
What's wrong?
I start the DialogFragment the same way you do.
CreatePostDialog createPostDialog = new CreatePostDialog();
createPostDialog.show(getSupportFragmentManager(), "create_post_dialog");
And I send back data using a public method in the activity rather than with intents.
((MainActivity)mContext).logout(Utils.getLocation(v));
The snippets above are copy pasted examples of my working code. Logout in this case is a public method in MainActivity that takes in a point and does what is needs with it.
you can use callback
1.define a callback in you dialog fragment
public Call mCall;
public interface Call {
void returnData(Data data);
}
2.on dialog fragment life circle
#Override
public void onDetach() {
super.onDetach();
mCall = (Call) getActivity();
mCall.returnData(data);
}
3.activity just implements Call
activity implements DiaFragment.Call
onActivityResult is there to receive informations after startActivityForResult is called, which is not your case.
What kind of datas you need to get from the dialog ?
DialogFragment is usually used in a fragment, not an activity. Look at alert dialog.

Close fragments on button click and return result?

On a click of a button within a fragment, is it possible to close the two fragments within the same activity and return the result of the fragment to another activity? One fragment is expecting input while the other fragment has information for the user to view and is not expecting input.
Also, my code worked prior to using fragments in the activity, however the fragments are no longer showing up when clicking the intent to go to the activity (NextActivity.class) that holds the fragments...does any happen to know why the fragments are not appearing?
Here is some of my code below
A piece from the original activity:
public class MessageList extends ListActivity {
private void createMessage() {
Intent i = new Intent(this, NextActivity.class);
startActivityForResult(i, ACTIVITY_CREATE); //this line is incorrect, right?
}}
Here is a snippet from a fragment class:
public class MessageEditorFragment extends Fragment {
confirmButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
getActivity().finish();
}}
Also here is the activity class that holds the fragments, just incase you want a look:
public class NextActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
Tab one = actionBar.newTab().setText("Message Editor");
Tab two = actionBar.newTab().setText("Information");
one.setTabListener(new MyTabListener(new MessageEditorFragment()));
two.setTabListener(new MyTabListener(new InformationFragment()));
actionBar.addTab(one);
actionBar.addTab(two);
}
public class MyTabListener implements TabListener{
Fragment fragment;
public MyTabListener(Fragment f){
fragment = f;
}}}
I deeply appreciate all and any help!! Please let me know if you need to see more code as well.. Thank you :)
When the Activity is destroyed by calling finish , both the fragments will be destroyed/closed.
So, Before you finish the Activity from fragment, you can pass the values to the Activity which started it.
When you start the Activity , You need to start the Activity for Result , to return back the result data from the Fragment/Activity
In your Activity declare a integer request code
int FRAGMENT_REQUEST_CODE = 1000;
Start the activity , as per your logic
Intent intent = new Intent(this,MainActivityEx.class);
startActivityForResult(intent, FRAGMENT_REQUEST_CODE);
Add a callback method onActivityResult to receive the result
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == FRAGMENT_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
TextView textView = (TextView)findViewById(R.id.textView1);
textView.setText(data.getExtras().getString("DATA"));
}
}
}
Now. In your Fragment, When you close the two Fragments , You can pass the data back to the caller Activity
Intent intent = new Intent();
intent.putExtra("DATA","Hai");
getActivity().setResult(Activity.RESULT_OK,intent);
getActivity().finish();

send data to fragment from another activity in android

I have an activity which is a container for several fragments. One of the fragments starts another activity and from the second activity I want to send some data to one of the fragments. How can I do that? Basically the first activity stays beyond the second one and one of the EditViews will be updated with a new value when the second activity closes. I could've used an intent but how can I send it if the activity is already started? Thank you.
You would need to start your second activity using startActivityForResult(). In your second activity before you finish it, you need to add the data to a bundle pass this to an intent and then set the result to the intent.
Bundle bundle = new Bundle();
bundle.putString("myData", "myValue");
Intent intent = new Intent();
intent.putExtra(bundle);
setResult(intent, 0);
finish();
And then in activity 1 there should be an onactivityresult method which retrieves the value from the intent and sets it where you want in your fragment
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Bundle bundle = data.getData();
string value = bundle.getString("myData");
}
I'm not sure if I have it exactly right as remembering it at the top of my head but should be enough to get you started I think.
If you want to pass data back to its containing activity from your fragment, can do it by declaring an interface handler and through that interface pass the data. And ensure your containing activity implements those interfaces.
For example: In your fragment, declare this interface as follows :
public interface CallBackInterface {
public void onCallBack(String param);
}
//Declare this interface in your fragment
CallBackInterface callBk;
#Override
public void onAttach(Activity a) {
super.onAttach(a);
callBk= (CallBackInterface ) a;
}
Within your fragment, when you need to handle the passing of data, just call it on the "callBk " object:
public void callBack(String param) {
callBk.onCallBack(param);
}
Finally, in your containing activity which implements CallBackInterface ...
#Override
public void onCallBack(String param) {
Log.d("TAG","hi " + param);
}

restart activity in android

I have one activity A, that has one button and one list view which shows names of books . on click of the button, activity B starts, there user fill the book form and save it . when he press back button , user comes to activity A. Here the book name should be updated in listview. I think I have to write some code in onResume() . Can u please tell me what to write. I am using customised list view.
Start activity B with startActivityForResult() and use method onActivityResult() to restart or process the new data
For example, to start Activity B:
String callingActivity = context.getLocalClassName();
Intent newActivity = new Intent(getApplicationContext(),ActivityB.class);
newActivity.setData(Uri.parse(callingActivity));
startActivityForResult(newActivity, 0);
Then somewhere in your Activity A class:
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode == 0){
// do processing here
}
}
The other answers should suffice, but onResume() can be called in cases where the activity is resumed by other means.
To simply restart Activity A when user presses back button from Activity B, then put the following inside the onActivityResult:
if(requestCode == 0){
finish();
startActivity(starterintent);
}
And in the onCreate of Activity A, add starterintent = getIntent();
Just remember to initiate the variable with Intent starterintent; somewhere before your onCreate is called.
e.g.
public class ActivityA extends ListActivity {
Intent starterintent;
public void onCreate(Bundle b){
starterintent = getIntent();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode == 0){
finish();
startActivity(starterintent);
}
}
private void startActivityB(){
String callingActivity = context.getLocalClassName();
Intent newActivity = new Intent(getApplicationContext(),ActivityB.class);
newActivity.setData(Uri.parse(callingActivity));
startActivityForResult(newActivity, 0);
}
}
Then just call startActivityB() from a button click or whatever
YES you are right. Write code in onResume.
When you updated date just call notifyDataSetChanged(); for your ListView adapter
Hope, it help you!
You can either start the activity when user press on Save, and it will fix it for you.
Or if you want to press back:
#Override
public void onResume(){
super.onResume();
list.clear();
list.addAll(getBooks());
adapter.notifyDataSetChanged();
}

onActivityResult never invoked within Activity part of ActivityGroup

I'm using a TabActivity that calls an ActivityGroup. Tipical approach that brings problems.
Now I'm facing a problem with onActivityResult
in my Activity I have..
public class MyActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.place_buttontab_community_media);
Button ButtonClick =(Button) findViewById(R.id.addPicture);
ButtonClick.setOnClickListener(new OnClickListener (){
#Override
public void onClick(View view)
{
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
// request code
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i(TAG, "hi");
super.onActivityResult(requestCode, resultCode, data);
}
}
unfortunately onActivityResult is never invoked.
You should listen for the result in the ActivityGroup's onActivityResult(). When a result is received, you have to decide which Activity should receive it and call it's onActivityResult() method with the received values.
I recently encountered this, to consolidate Andras' and virtual82's answer and discussion above (Sorry I can't add comment due to my low rep):
If your activity is started inside an ActivityGroup, which is used by TabActivity for example, then only the ActivityGroup activity can receive method calls to onActivityResult when you start an activity with startActivityForResult(Intent intent, int requestCode) from an activity inside the ActivityGroup.
In my situation, I have a TabActivity that contains FragmentActivitys. A Fragment inside a FragmentActivity may start an activity for result.
In this case the Fragment needs to start the activity with TabActivity as the calling activity:
Intent doSomethingIntent = new Intent();
//getActivity() returns the FragmentActivity, so we need to get the TabActivity with getParent()
Activity tabActivity = getActivity().getParent();
doSomethingIntent .setClass(tabActivity , PostCommentActivity.class);
tabActivity.startActivityForResult(doSomethingIntent , DO_SOMETHING_REQ_CODE);
Then in onActivityResult of the TabActivity, pass the result back to the Fragment.
Activity currentActivity = getLocalActivityManager().getCurrentActivity();
//get the FragmentActivity in order to get the Fragment instance
if(currentActivity instanceof FragmentActivity){
FragmentActivity currentFragmentActivity = (FragmentActivity)currentActivity ;
//R.id.l_container is the layout/viewgroup that contains the Fragment
Fragment currentFragment = currentFragmentActivity.getSupportFragmentManager().findFragmentById(R.id.l_container);
if(currentFragment != null){
//pass result to the Fragment!
frag.onActivityResult(requestCode, resultCode, data);
}
}
I realize that ActivityGroup, TabActivity and LocalActivityManager are deprecated in favor of Fragment and FragmentManager, but my project time constraint didn't allow me enough time to fully upgrade.
Hopefully this post will help someone in this situation, instead of the usual "don't do it" kind of response you see else where.

Categories

Resources