Skip to content

Instantly share code, notes, and snippets.

@vamsitallapudi
Last active July 8, 2021 03:45
Show Gist options
  • Save vamsitallapudi/26030c15829d7be8118e42b1fcd0fa42 to your computer and use it in GitHub Desktop.
Save vamsitallapudi/26030c15829d7be8118e42b1fcd0fa42 to your computer and use it in GitHub Desktop.
public class RetainFragEgActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
Button b = (Button) findViewById(R.id.aaa);
b.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
RetainFragment retainFragment =
RetainFragment.getInstance(getFragmentManager());
retainFragment.loadAsync();
}
});
}
private void handleResponse(String response) {
// do something with the response...
}
public static class RetainFragment extends Fragment {
private static final String TAG = "RetainFragment";
private RetainFragment() {
}
public static RetainFragment getInstance(FragmentManager fm) {
RetainFragment fragment = (RetainFragment) fm.findFragmentByTag(TAG);
if (fragment == null) {
fragment = new RetainFragment();
fm.beginTransaction().add(fragment, TAG).commit();
}
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
public void loadAsync() {
new AsyncTask<Void, Void, String>() {
@Override protected String doInBackground(Void... params) {
// Do some work...
return null;
}
@Override protected void onPostExecute(String response) {
MyActivity myActivity = (MyActivity)getActivity();
if (myActivity != null) {
myActivity.handleResponse(response);
}
}
}.execute();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment