Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refresh the fragment after activity finished in android?

I am working on the user login procedure

First of all, the user enter a fragment ,

In fragment , it firstly check whether the user has logged in , if true, then inflate the login-ed screen, otherwise, the login form is inflated.

The simple code is like this

if (prefs_user exist) {
  v = inflater.inflate(R.layout.fragment_logined, container, false);

  logout.setOnClickListener(new View.OnClickListener() {
         editor.remove(prefs_user).commit();
         FragmentTransaction ft = getFragmentManager().beginTransaction();
         ft.detach(frag).attach(frag).commit();
  });
} else {
    v = inflater.inflate(R.layout.fragment_login, container, false);
    login.setOnClickListener(new View.OnClickListener() {
         editor.put(prefs_user, true).commit();
         FragmentTransaction ft = getFragmentManager().beginTransaction();
         ft.detach(frag).attach(frag).commit();
    });

    reg.setOnClickListener(new View.OnClickListener() {
        intent to start register activity
    });        
}

Then, for the register activity

if(reg_success) {
 app.editor.putString("prefs_user",true).commit();
 finish();
}

So far it works for login / logout, the problem is , after register in the new activity, the fragment is not updated e.g. it should show logout screen after the user success registered.

How to refresh the fragment after activity finish? Thanks

like image 465
user3538235 Avatar asked Dec 10 '22 20:12

user3538235


1 Answers

For solving it you can start register Activity like below :

Intent intent = new Intent(getActivity(), register .class);
startActivityForResult(intent, 10001);

And when you finish your activity you should setResult like below :

setResult(Activity.RESULT_OK)

Now in your fragment you will get event of finishing your activity by overriding onActivityResult() in the fragment.

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
    super.onActivityResult(requestCode, resultCode, data);
    if ((requestCode == 10001) && (resultCode == Activity.RESULT_OK))
       // recreate your fragment here
     FragmentTransaction ft = getFragmentManager().beginTransaction();
     ft.detach(frag).attach(frag).commit();
}

That's it.

Hope it will help you.

like image 63
KishuDroid Avatar answered Mar 15 '23 22:03

KishuDroid