Otto subscribe and post in the same fragment does not work - android

I have three fragments in the same activity, let says FragmentA, FragmentB and FragmentC
Let´s say that FragmentA sends an int to FragmentB so in the FragmentA I have:
//FRAGMENT_A
#Override
public void onDestroy() {
super.onDestroy();
EventBus.getBus().register(this);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
EventBus.getBus().register(this);
}
private void registerEventBus(int i) {
EventBus.getBus().post(i);
}
FragmentB received the int so:
//FRAGMENT_B
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EventBus.getBus().register(this);
}
#Override
public void onDestroyView() {
super.onDestroyView();
EventBus.getBus().unregister(this);
}
#Subscribe
public void getBusData(int data) {
//whatever
}
But now I have to send a double from FagmentB to FragmentC, I have created a new Bus class so now in the FragmentB, I have
//Fragment_B
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EventBus.getBus().register(this);
EventBus2.getBus.register(this)
}
#Override
public void onDestroyView() {
super.onDestroyView();
EventBus.getBus().unregister(this);
EventBus2.getBus..unregister(this)
}
#Subscribe
public void getBusData(int data) {
//whatever
}
private void createEventBus2(double number){
EventBus2.post(number);
}
And finally the FragmentC
//FragmentC
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EventBus2.getBus().register(this);
}
#Override
public void onDestroyView() {
super.onDestroyView();
EventBus2.getBus().unregister(this);
}
#Subscribe
public void getBus2Data(double data) {
//whatever
}
From FragmentA to FragmentB works perfectly but in the FragmentC I have never get the double data value.
What am I doing wrong?

Related

AccountAuthenticatorActivity for AppCompat

I'm making an authenticator following the tutorial: http://blog.udinic.com/2013/04/24/write-your-own-android-authenticator/
The login Activity requires to extend AccountAuthenticatorActivity, the issue starts here: AccountAuthenticatorActivity extends the regular Activity and not AppCompatActivity.
Using the regular Activity in AppCompat results in a Activity without ActionBar. I want to use AccountAuthenticatorActivity AND having an ActionBar.
I think that is not the real solution. If you are doing an app with support libraries, mixing AppCompatActivities, Fragments &c with the standard ones is not a good idea.
I´ve created an AccountAuthenticatorAppCompatActivity extending AppCompatActivity and then copy/paste the code from API AccountAuthenticatorActivity and it seems to work properly.
public class AccountAuthenticatorAppCompatActivity extends AppCompatActivity {
private AccountAuthenticatorResponse mAccountAuthenticatorResponse = null;
private Bundle mResultBundle = null;
public final void setAccountAuthenticatorResult(Bundle result) {
mResultBundle = result;
}
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
mAccountAuthenticatorResponse =
getIntent().getParcelableExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE);
if (mAccountAuthenticatorResponse != null) {
mAccountAuthenticatorResponse.onRequestContinued();
}
}
public void finish() {
if (mAccountAuthenticatorResponse != null) {
// send the result bundle back if set, otherwise send an error.
if (mResultBundle != null) {
mAccountAuthenticatorResponse.onResult(mResultBundle);
} else {
mAccountAuthenticatorResponse.onError(AccountManager.ERROR_CODE_CANCELED,
"canceled");
}
mAccountAuthenticatorResponse = null;
}
super.finish();
}
}
Hope it helps to someone.
The key is AppCompatDelegate, my code is based on the AppCompatPreferenceActivity class generated by Android Studio:
#SuppressWarnings("unused")
public class AppCompatAuthActivity extends AccountAuthenticatorActivity {
private AppCompatDelegate mDelegate;
#Override
protected void onCreate(Bundle savedInstanceState) {
getDelegate().installViewFactory();
getDelegate().onCreate(savedInstanceState);
super.onCreate(savedInstanceState);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
getDelegate().onPostCreate(savedInstanceState);
}
public ActionBar getSupportActionBar() {
return getDelegate().getSupportActionBar();
}
public void setSupportActionBar(#Nullable Toolbar toolbar) {
getDelegate().setSupportActionBar(toolbar);
}
#Override
#NonNull
public MenuInflater getMenuInflater() {
return getDelegate().getMenuInflater();
}
#Override
public void setContentView(#LayoutRes int layoutResID) {
getDelegate().setContentView(layoutResID);
}
#Override
public void setContentView(View view) {
getDelegate().setContentView(view);
}
#Override
public void setContentView(View view, ViewGroup.LayoutParams params) {
getDelegate().setContentView(view, params);
}
#Override
public void addContentView(View view, ViewGroup.LayoutParams params) {
getDelegate().addContentView(view, params);
}
#Override
protected void onPostResume() {
super.onPostResume();
getDelegate().onPostResume();
}
#Override
protected void onTitleChanged(CharSequence title, int color) {
super.onTitleChanged(title, color);
getDelegate().setTitle(title);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
getDelegate().onConfigurationChanged(newConfig);
}
#Override
protected void onStop() {
super.onStop();
getDelegate().onStop();
}
#Override
protected void onDestroy() {
super.onDestroy();
getDelegate().onDestroy();
}
public void invalidateOptionsMenu() {
getDelegate().invalidateOptionsMenu();
}
private AppCompatDelegate getDelegate() {
if (mDelegate == null) {
mDelegate = AppCompatDelegate.create(this, null);
}
return mDelegate;
}
}
The AppCompatDelegate is the key to add ActionBar to ANY regular Activity (for example PreferenceActivity).
Don't forget your activity must extend AppCompatAuthActivity.

UI of Fragment with tabs is not being updated

I have two tabs which contain two different fragments. Tab1 for fragment1 and tab2 for fragment2. From fragment1, I want to pass a string value in fragment2's TextView by clicking on a Button.
However, the UI of fragment2 is not being updated. Sample code has given below.
In MainActivity :
private Fragment1 fragment1;
private Fragment2 fragment2;
private TabLayout tabLayout;
protected void onCreate(Bundle savedInstanceState) {
fragment1 = new Fragment1();
fragment2 = new Fragment2();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_holder, fragment1).commit();
tabLayout = (TabLayout) findViewById(R.id.tab);
tabLayout.getTabAt(0).select();
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
if (tab.getPosition() == 0) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_holder, fragment1).commit();
} else if (tab.getPosition() == 1) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_holder, fragment2).commit();
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
}
}
public void showFragment2(final String data) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_holder, fragment2).commit();
tabLayout.getTabAt(1).select();
if (!TextUtils.isEmpty(data)) {
if (fragment2 != null) {
fragment2.setData(data);
}
}
}
In Fragment1 :
private Button button;
protected void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
button = (Button) view.findViewById(R.id.btn);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((MainActivity)getActivity()).showFragment2("Updated Data");
}
});
}
In Fragment2 :
private TextView tv;
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
tv = (TextView) view.findViewById(R.id.tv);
}
public void setData(String data){
tv.setText(data);
}
Important Update:
If I update the UI in Handler. Then it works. But, seems it's not the proper way.
handler.postDelayed(new Runnable() {
#Override
public void run() {
tabLayout.getTabAt(1).select();
if(!TextUtils.isEmpty(data)){
if(fragment2 != null){
fragment2.setData(data);
}
}
}
},500);
Use .executePendingTransactions() which would work synchronously along with .commit() which works Asynchronously.
After a FragmentTransaction is committed with
FragmentTransaction.commit(), it is scheduled to be executed
asynchronously on the process's main thread. If you want to
immediately executing any such pending operations, you can call this
function (only from the main thread) to do so. Note that all callbacks
and other related behavior will be done from within this call, so be
careful about where this is called from.
DO:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_holder, fragment2).commit();
getSupportFragmentManager().executePendingTransactions();
tabLayout.getTabAt(1).select();
if(!TextUtils.isEmpty(data)){
if(fragment2 != null){
fragment2.setData(data);
}
}
Hey hi i am not sure but try this:
public void showFragment2(final String data) {
if (!TextUtils.isEmpty(data)) {
if (fragment2 != null) {
// fragment2.setData(data);
Bundle arguments = new Bundle();
arguments.putString( "string_key" , data);
fragment2.setArguments(arguments);
}
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_holder, fragment2).commit();
tabLayout.getTabAt(1).select();
}
and In Fragment2 :
private TextView tv;
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Bundle arguments = getArguments();
String desired_string = arguments.getString("string_key");
tv = (TextView) view.findViewById(R.id.tv);
setData(desired_string);
}
public void setData(String data){
tv.setText(data);
}
set the data in activity method from fragment 1 and while loading fragment get the data from activity and set it in fragment 2
mainActivity(){
string fragment1Data;
public void setFragment1Data(string data){
fragment1Data = data;
}
public string getFragment1Data(){
return fragment1Data
}
}
in Fragment 1
private Button button;
protected void onViewCreated(View view, #Nullable Bundle savedInstanceState)
{
button = (Button) view.findViewById(R.id.btn);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((MainActivity)getActivity()).showFragment2("Updated Data");
((MainActivity)getActivity()).setFragment1Data("data");
}
});
}
in Fragment 2
private TextView tv;
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
tv = (TextView) view.findViewById(R.id.tv);
tv.setText(((MainActivity)getActivity()).getFragment1Data());
}

Don't call method on screen rotation

I have parent fragment called OpFragment. From this fragment are inherited all fragments in my app.
public abstract class OpFragment extends Fragment {
private Loading loading;
public abstract int getLayoutId();
public abstract void getData();
public abstract void setListeners();
protected BackHandlerInterface backHandlerInterface;
public boolean onBackPressed(){
return false;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
if(!(getActivity() instanceof BackHandlerInterface)) {
throw new ClassCastException("Hosting activity must implement BackHandlerInterface");
} else {
backHandlerInterface = (BackHandlerInterface) getActivity();
}
FragmentArgs.inject(this);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(getLayoutId(), container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if(!isAdded()){
return;
}
getData();
setListeners();
}
protected String returnName() {
return null;
}
public void showTitle() {
EventBus.getDefault().post(new ShowName(returnName()));
}
#Override
public void onDestroyView() {
super.onDestroyView();
}
public Loading getLoading() {
if (this.loading == null) {
this.loading = new Loading(this.getActivity());
}
return this.loading;
}
/**
* Gets a component for dependency injection by its type.
*/
#SuppressWarnings("unchecked")
protected <C> C getComponent(Class<C> componentType) {
return componentType.cast(((HasComponent<C>) getActivity()).getComponent());
}
#Override
public void onStart() {
super.onStart();
backHandlerInterface.setSelectedFragment(this);
}
public interface BackHandlerInterface {
void setSelectedFragment(OpFragment backHandledFragment);
}
#Override
public void onResume() {
super.onResume();
sendGAScreens();
}
private void sendGAScreens() {
final Tracker tracker = OpApp.getDefaultTracker();
if(tracker != null) {
tracker.setScreenName(getClass().getSimpleName());
tracker.send(new HitBuilders.ScreenViewBuilder().build());
}
}
}
There are methods getData() and setListeners() inside onViewCreated.
I don't want to recall this methods after screen rotation. How can I do that ?
Simply checking savedInstanceState == null not gave me expected result.
override this method to detect screen rotation in your fragment and set some flag if its screen rotation. as shown below:
#Override
public void onConfigurationChanged(Configuration newConfig)
{
Log.d("tag", "config changed");
super.onConfigurationChanged(newConfig);
int orientation = newConfig.orientation;
if (orientation == Configuration.ORIENTATION_PORTRAIT || orientation == Configuration.ORIENTATION_LANDSCAPE)
flag= true;
....
}
and in your onViewCreated() do like this
if(!flag){
// call your functions
}

Half of the lifecycle methods of fragment get not called after rotation

I'm experiencing an strange behavior of Fragment life-cycle each time that i rotate the screen. Only the first half of life-cycle methods are getting called, onPause,onSaveInstanceState,onStop, onDestroyView,onDestroy and onDetach. The other half (onAttach ...-onResume) are not getting called. The Activity associated with the Fragment is calling all its life-cycle methods.
Any help would be highly appreciated because I'm stuck on this issue.
Thanks in advance.
Here the entire code of the Activity and the static nested class where is the Fragment:
public class MoviesFeed extends AppCompatActivity {
private static boolean mTwoPane;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("ACT","onCreate");
setContentView(R.layout.themoviedb_main);
if(findViewById(R.id.detail_activity_container)!=null) {
//the detail_activity_container will be present only in large-screen
//Layouts (res/Layout-sw600dp. If this view is present, then the activity
//should be in two-pane mode
mTwoPane=true;
//In two-pane mode, show the detail view in this activity by adding
// or replacing the detail fragment using a fragment transaction
DetailActivityFragment detailActivityFragment=new DetailActivityFragment();
// Bundle bundle=new Bundle();
// bundle.putBoolean("twopane",mTwoPane);
// detailActivityFragment.setArguments(bundle);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.detail_activity_container, detailActivityFragment)
.commit();
}
} else {
mTwoPane=false;
}
}
#Override
protected void onStart() {
Log.d("ACT","onStart");
super.onStart();
}
#Override
protected void onResume() {
Log.d("ACT","onResume");
super.onResume();
}
#Override
protected void onPause() {
Log.d("ACT","onPause");
super.onPause();
}
#Override
protected void onStop() {
Log.d("ACT","onStop");
super.onStop();
}
#Override
protected void onRestart() {
Log.d("ACT","onRestart");
super.onRestart();
}
#Override
protected void onDestroy() {
Log.d("ACT","onDestroy");
super.onDestroy();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.movies_feed_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
startActivity(new Intent(this,SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
public static class MoviesFeedFragment extends Fragment implements AdapterView.OnItemClickListener {
private static final int APPROX_FIXED_IMAGE_WIDTH=170;
private GridView mGridView;
private MovieAdapter mMovieAdapter;
private ArrayList<Response.Movie> mListMovies=new ArrayList<Response.Movie>();
private TimeMeasure mTm;
private boolean mFromDetailsActivity =false;
private boolean mUserRotation=false;
private boolean mFavoritesMode=false;
#Override
public void onAttach(Activity activity) {
Log.d("FRAG", "onAttach");
super.onAttach(activity);
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("FRAG", "onCreate");
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.fragment_moviesfeed, container, false);
Log.d("FRAG", "onCreateView");
mGridView= (GridView) view.findViewById(R.id.gridView);
mGridView.setOnItemClickListener(this);
mMovieAdapter = new MovieAdapter(getActivity(), mListMovies);
mGridView.setAdapter(mMovieAdapter);
//for tablets specially
// float scalefactor = getResources().getDisplayMetrics().density * APPROX_FIXED_IMAGE_WIDTH;
// Point size=new Point();
// getWindowManager().getDefaultDisplay().getSize(size);
// int number=size.x;
// int columns = (int) ((float) number / (float) scalefactor);
//
// mGridView.setNumColumns(columns);
if(savedInstanceState!=null){
mUserRotation=true;
ArrayList<Response.Movie> tempList=new ArrayList<Response.Movie>();
tempList=savedInstanceState.getParcelableArrayList("mListMovies");
mListMovies.clear();
mListMovies.addAll(tempList);
mMovieAdapter = new MovieAdapter(getActivity(), mListMovies);
mGridView.setAdapter(mMovieAdapter);
}
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
Log.d("FRAG", "onActivity");
super.onActivityCreated(savedInstanceState);
}
#Override
public void onPause() {
Log.d("FRAG", "onPause");
super.onPause();
}
#Override
public void onStop() {
Log.d("FRAG", "onStop");
super.onStop();
}
#Override
public void onSaveInstanceState(Bundle outState) {
Log.d("FRAG", "onSaveInstanceState");
super.onSaveInstanceState(outState);
outState.putParcelableArrayList("mListMovies", mListMovies);
}
#Override
public void onResume() {
Log.d("FRAG", "onResume");
super.onResume();
if (mFromDetailsActivity !=true && mUserRotation!=true) {
executeCallToMoviesApi();
} else if(mFromDetailsActivity==true && mFavoritesMode==true) {
getFavoritesMovies();
}
mFromDetailsActivity =false;
mUserRotation=false;
}
#Override
public void onDestroyView() {
Log.d("FRAG", "onDestroyView");
super.onDestroyView();
}
#Override
public void onDestroy() {
Log.d("FRAG", "onDestroy");
super.onDestroy();
}
#Override
public void onDetach() {
Log.d("FRAG", "onDetach");
super.onDetach();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (mTwoPane==true) {
DetailActivityFragment detailActivityFragment=new DetailActivityFragment();
Bundle args=new Bundle();
args.putString("movieId", String.valueOf(mListMovies.get(position).getId()));
//Response.Movie movie=new Response.Movie();
//movie.setId(mListMovies.get(position).getId());
//args.putParcelable("movie",movie);
args.putBoolean("favoritesMode",mFavoritesMode);
detailActivityFragment.setArguments(args);
getActivity().getSupportFragmentManager().beginTransaction()
.replace(R.id.detail_activity_container,detailActivityFragment)
.commit();
} else {
Intent intent = new Intent(getActivity(), DetailActivity.class);
intent.putExtra("favoritesMode", mFavoritesMode);
intent.putExtra("movieId", mListMovies.get(position).getId());
mFromDetailsActivity = true;
startActivity(intent);
}
}
public void executeCallToMoviesApi(){
SharedPreferences sharedPreferences= PreferenceManager.getDefaultSharedPreferences(getActivity());
String orderStr= sharedPreferences.getString(getString(R.string.pref_order_key),
getString(R.string.pref_order_default));
mFavoritesMode=false;
if (orderStr.equals(getString(R.string.pref_popularity))){
getActivity().setTitle(getString(R.string.mainactivity_title_popularity));
getMoviesByPopularity();
}
if (orderStr.equals(getString(R.string.pref_rate))){
getActivity().setTitle(getString(R.string.mainactivity_title_rate));
getMoviesByRate();
}
if (orderStr.equals(getString(R.string.pref_favorites))) {
getActivity().setTitle(getString(R.string.mainactivity_title_favorites));
mFavoritesMode=true;
getFavoritesMovies();
}
}
public void getMoviesByPopularity(){
ApiClient.MyApi myApi=ApiClient.getMyApiClient();
myApi.getMoviesByPopularityDesc(AppConstants.API_KEY, callbackResponse());
}
public void getMoviesByRate(){
ApiClient.MyApi myApi=ApiClient.getMyApiClient();
myApi.getMoviesByAverageRate(AppConstants.API_KEY, callbackResponse());
}
private Callback<Response> callbackResponse() {
return new Callback<Response>() {
#Override
public void success(Response response, retrofit.client.Response response2) {
// Message.displayToast(MoviesFeed.this, "success");
mListMovies.clear();
mListMovies.addAll((ArrayList) response.getResults());
mMovieAdapter = new MovieAdapter(getActivity(), mListMovies);
mGridView.setAdapter(mMovieAdapter);
}
#Override
public void failure(RetrofitError error) {
Log.v("VILLANUEVA", "error:" + error.getMessage().toString());
Message.displayToast(getActivity(), "failure" + error.getMessage().toString());
}
};
}
public void getFavoritesMovies(){
List<MovieDetail> tempListDetail;
ArrayList<Response.Movie> tempList=new ArrayList<Response.Movie>();
SharedPreferenceManager sharedPreferenceManager=new SharedPreferenceManager(getActivity());
tempListDetail = sharedPreferenceManager.getFavoritesList();
Response.Movie tempMovie;
if (tempListDetail!=null) {
for (MovieDetail movieDetail : tempListDetail) {
tempMovie = new Response.Movie();
tempMovie.setId(movieDetail.getId());
tempMovie.setPoster_path(movieDetail.getPoster_path());
tempList.add(tempMovie);
}
mListMovies.clear();
mListMovies.addAll(tempList);
}
mMovieAdapter = new MovieAdapter(getActivity(), mListMovies);
mGridView.setAdapter(mMovieAdapter);
}
}//MoviesFeedFragment
Screenshots, before and after rotation.
Before:
After:
Log

Saving data in Fragment on orientation change

What i am trying to do:: I am trying to save the data entered into edittext and spinner onorientation change
What is happening::: I am not able to save the data, how can i resolve this
MainActivity.java
public class MainActivity extends FragmentActivity {
Fragment_A frgObj;
#Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
Log.d("MAIN-ACTIVITY", "onCreate");
setContentView(R.layout.activity_main);
}
#Override
protected void onStart() {
super.onStart();
Log.d("MAIN-ACTIVITY", "onStart");
frgObj=Fragment_A.newInstance();
getSupportFragmentManager().beginTransaction().replace(R.id.container, frgObj).addToBackStack(null).commit();
}
public void onSaveInstanceState(Bundle outState){
getSupportFragmentManager().putFragment(outState,"myfragment",frgObj);
}
public void onRetoreInstanceState(Bundle inState){
frgObj = (Fragment_A) getSupportFragmentManager().getFragment(inState,"myfragment");
}
}
Fragment_A.java
public class Fragment_A extends Fragment{
Button btn;
Spinner spinner;
EditText editText;
SeekBar seekBar;
public static Fragment_A newInstance() {
Log.d("FRAGMENT-A", "newInstance");
Fragment_A fragment = new Fragment_A();
return fragment;
}
#Override
public void onAttach(Activity activity) {
Log.d("FRAGMENT-A", "onAttach");
super.onAttach(activity);
}
#Override
public void onCreate(Bundle savedInstanceState) {
Log.d("FRAGMENT-A", "onCreate");
super.onCreate(savedInstanceState);
}
#Override
public void onSaveInstanceState(Bundle outState) {
Log.d("FRAGMENT-A", "onSaveInstanceState");
super.onSaveInstanceState(outState);
//City Spinner state
outState.putString("editText", editText.getText().toString());
outState.putInt("yourSpinner", spinner.getSelectedItemPosition());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d("FRAGMENT-A", "onCreateView");
View view=inflater.inflate(R.layout.fragment_a, container, false);
btn=(Button) view.findViewById(R.id.buttonId1);
spinner=(Spinner) view.findViewById(R.id.spinnerId1);
editText=(EditText) view.findViewById(R.id.editTextId1);
seekBar=(SeekBar) view.findViewById(R.id.seekBarId1);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
Log.d("FRAGMENT-A", "onActivityCreated");
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
//City Spinner state
editText.setText(savedInstanceState.getString("editText"));
spinner.setSelection(savedInstanceState.getInt("yourSpinner", 0));
}
}
#Override
public void onStart() {
Log.d("FRAGMENT-A", "onStart");
super.onStart();
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.d("FRAGMENT-A", "button Clicked");
Fragment_B frgObj=Fragment_B.newInstance();
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, frgObj,"Fragment_B").addToBackStack(null).commit();
}
});
}
}
I don't think you need to change anything in your activity other than call super.onSaveInstanceState(Bundle). Saving the data onSaveInstanceState in the fragment should be enough. I would put the restoring logic in onCreateView instead of onActivityCreated. onCreateView is guaranteed to be called whenever the fragment is recreated however this is not the case with onActivityCreated.
An other thing you can try is not going any of this and using setRetainInstance(true) which should retain your instance variables through orientation change.

Categories

Resources