onSaveInstanceState is not called in a fragment (using FragmentPagerAdapter) - android

in my app I have a ViewPager with 3 fragments. I want to save the state of progress bar in my 1st fragment, since it is destroyed when I scroll all the way to the 3th one and go back to the 1st one. Now, I know that I can use setOffscreeLimit method of the viewpager to say 2 and that will fix my issue, but I want my app to be memory efficient. I did try to use the fragment's onSaveInstanceState method but for some reason it is not called when the fragment's view is destroyed. How can I save my progress bar state, please share.
This is my fragment's code:
public class SnapshotFragment extends Fragment {
public static final String ARG_PAGE = "ARG_PAGE";
private static String TAG;
private int mPage;
private ImageView mCantDecideGg;
private CircleProgressBar mCantDecideProgressBar;
private ObjectAnimator cantDecideProgressAnimator;
private Animator.AnimatorListener progressBarAnimationListener = new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animator) {
mCantDecideProgressBar.setProgress(0);
}
#Override
public void onAnimationEnd(Animator animator) {
// Log.d(TAG, "onAnimationEnd");
if(mCantDecideProgressBar.getProgress() < 100){
mCantDecideProgressBar.setProgress(0);
}else {
mCantDecideProgressBar.setProgress(100);
}
}
#Override
public void onAnimationCancel(Animator animator) {}
#Override
public void onAnimationRepeat(Animator animator) {}
};
private View.OnTouchListener onTouchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
cantDecideProgressAnimator.cancel();
Log.d(TAG, "ACTION_UP canceled");
}
if (event.getAction() == MotionEvent.ACTION_DOWN) {
cantDecideProgressAnimator.start();
Log.d(TAG, "ACTION_DOWN executed");
}
return true;
}
};
public static SnapshotFragment newInstance(int page) {
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
SnapshotFragment fragment = new SnapshotFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPage = getArguments().getInt(ARG_PAGE);
TAG = getActivity().getClass().getSimpleName();
Log.d("MainActivity", "onCreate" + mPage);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_snapshot_layout,container,false);
mCantDecideGg = (ImageView)view.findViewById(R.id.cant_devide_black_circle_bg);
if(savedInstanceState != null){
mCantDecideProgressBar.setProgress(savedInstanceState.getInt(Constants.CANT_DECIDE_PROGRESS_BAR));
}
mCantDecideGg.setOnTouchListener(onTouchListener);
mCantDecideProgressBar = (CircleProgressBar)view.findViewById(R.id.cantDecideProgressBar);
//set up the project animator to animate the progress bar from 0 to 100
cantDecideProgressAnimator = ObjectAnimator.ofFloat(mCantDecideProgressBar, "progress", 0.0f, 100.0f);
//add the animation listener to the progress animator to check when the progress has started,finished...
cantDecideProgressAnimator.addListener(progressBarAnimationListener);
//set the duration of the animation to 1.2 seconds
cantDecideProgressAnimator.setDuration(1200);
Log.d("MainActivity", "onCreateView" + mPage);
return view;
}
#Override
public void onDestroyView() {
super.onDestroyView();
Log.d(TAG, "onDestroyView");
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(Constants.CANT_DECIDE_PROGRESS_BAR, (int) mCantDecideProgressBar.getProgress());
Log.d(TAG, "onSaveInstanceState");
}
}

Related

Call an dialog fragment method from Activity to Dialog Fragment

I am showing one dialog fragment (showing progress ) in my activity . Calling rest api methods are in my activity . Based on rest api results , I need to some progress in the dialog fragment . So I need to call a method of dialog fragment from activity . I tried with event bus , (Firing from Activity caught on Dialog Fragment ) - But events are not caught in dialog fragment . Is there any other solution ?
Fragment Code:
public class SyncProgressFragment extends BaseDialogFragment {
#BindView(R.id.layout_cancel)
LinearLayout layoutCancel;
#BindView(R.id.sync_with_master_breadcrumbs)
BreadcrumbsView syncWithMasterBreadCrumbs;
#BindView(R.id.master_breadcrumbs)
BreadcrumbsView masterBreadCrumbs;
#BindView(R.id.tvStep)
AppCompatTextView tvStep;
#BindView(R.id.tv_create_defect_title)
AppCompatTextView tvTitle;
private ThreadBus bus;
private FragmentManager manager;
private GoogleApiHelper googleApiHelper;
private Handler handler;
private Runnable runnable;
private boolean isOld;
private boolean isSync;
//private long requestId;
private BreadcrumbsView breadcrumbsView;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bus = AppController.getInstance().getBus();
bus.register(this);
googleApiHelper = AppController.getInstance().getGoogleApiHelper();
googleApiHelper.reconnect();
if (getArguments() != null) {
Bundle bundle = getArguments();
isOld = bundle.getBoolean(AppConstants.IS_OLD,false);
isSync = bundle.getBoolean(AppConstants.IS_OLD,false);
}
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initUI();
}
private void initUI() {
if (isOld && isSync)
tvTitle.setText(getString(R.string.syncing_old_data_with_bo));
else if(!isOld && isSync)
tvTitle.setText(getString(R.string.syncing_data_with_bo));
else {
tvTitle.setText(getString(R.string.downloading_master_data));
}
if(isSync) {
breadcrumbsView = syncWithMasterBreadCrumbs;
syncWithMasterBreadCrumbs.setVisibility(View.VISIBLE);
masterBreadCrumbs.setVisibility(View.GONE);
tvStep.setText(getString(R.string.sending_data));
}
else{
breadcrumbsView = masterBreadCrumbs;
masterBreadCrumbs.setVisibility(View.VISIBLE);
syncWithMasterBreadCrumbs.setVisibility(View.GONE);
tvStep.setText(getString(R.string.getting_master_data));
}
}
private void initValues() {
handler = new Handler();
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = super.onCreateDialog(savedInstanceState);
// request a window without the title
dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
dialog.setCanceledOnTouchOutside(false);
dialog.setCancelable(false);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
return dialog;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_sync_progress, container, false);
ButterKnife.bind(this, view);
initValues();
return view;
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onStop() {
super.onStop();
}
#Override
public void onDestroy() {
super.onDestroy();
if (bus != null) {
bus.unregister(this);
}
try {
handler.removeCallbacks(runnable);
} catch (Exception e) {
}
}
#Override
public void onDestroyView() {
super.onDestroyView();
}
#Override
public void setCancelable(boolean cancelable) {
super.setCancelable(cancelable);
}
#Override
public void onCancel(DialogInterface dialog) {
super.onCancel(dialog);
}
#Override
public void onDismiss(DialogInterface dialog) {
super.onDismiss(dialog);
try {
handler.removeCallbacks(runnable);
} catch (Exception e) {
}
}
#OnClick({R.id.img_close, R.id.layout_cancel})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.layout_cancel:
case R.id.img_close:
dismissAllowingStateLoss();
break;
}
}
#Subscribe
public void onSyncGotResponse(SyncGotResponse syncGotResponse) {
Utilities.log(SyncProgressFragment.class,"onSyncGotResponse",""+syncGotResponse.isSuccess());
if(syncGotResponse.isSuccess()) {
breadcrumbsView.nextStep();
tvStep.setText(getString(R.string.synced_data_with_bo));
}
else
dismissAllowingStateLoss();
}
#Subscribe
public void onMasterGotResponse(MasterGotResponse masterGotResponse) {
Utilities.log(SyncProgressFragment.class,"onMasterGotResponse",""+masterGotResponse.isSuccess());
if(masterGotResponse.isSuccess()) {
tvStep.setText(getString(R.string.downloaded_data_from_bo));
breadcrumbsView.nextStep();
}
else
dismissAllowingStateLoss();
}
}
Activity Code:
#Override
public void dataSyncSuccess(DataSyncResponse dataSyncResponse) {
bus.post(new SyncGotResponse(true));
}
#Override
public void dataSyncFailure(String msg) {
UiUtils.showToast(getContext(), msg);
bus.post(new SyncGotResponse(false));
}
//Calling Rest Api method
if (CheckInternetConnection(getContext())) {
try {
presenter.data_sync();
Bundle bundle = new Bundle();
bundle.putBoolean(AppConstants.IS_OLD,false);
bundle.putBoolean(AppConstants.IS_SYNC,true);
syncProgressFragment.setArguments(bundle);
syncProgressFragment.setCancelable(false);
syncProgressFragment.show(getSupportFragmentManager(), syncProgressFragment.getTag());
} catch (JSONException e) {
e.printStackTrace();
}
} else {
ShowSanckBarShow();
}

How can I create Gauge animation everytime a fragment becomes visible in viewpager?

I was able to find the solution to the problem "how to check if a fragment becomes visible in viewpager". But, I also want my gauge to animate everytime the fragment comes on the screen. However, it returns null pointer exception. I have used the isVisibleToUser method and the onResume() method. How can I solve this?
public class HumidityFragment extends Fragment {
View view;
public Boolean mIsVisibleToUser;
Gauge gauge;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_soil_moisture, container, false);
gauge = view.findViewById(R.id.gauge);
onVisible();
return view;
}
#Override
public void onStart () {
super.onStart();
if (mIsVisibleToUser) {
onVisible();
}
}
#Override
public void onResume() {
super.onResume();
onVisible();
}
#Override
public void onStop () {
super.onStop();
if (mIsVisibleToUser) {
onInVisible();
}
}
#Override
public void setUserVisibleHint ( boolean isVisibleToUser){
super.setUserVisibleHint(isVisibleToUser);
mIsVisibleToUser = isVisibleToUser;
if (isResumed()) { // fragment have created
if (mIsVisibleToUser) {
onVisible();
} else {
onInVisible();
}
}
}
public void onVisible () {
Toast.makeText(getContext(), "visible", Toast.LENGTH_SHORT).show();
gauge.moveToValue(78);
}
public void onInVisible () {
Toast.makeText(getActivity(), "invisible", Toast.LENGTH_SHORT).show();
}
}
You did not initialize the variable just give the default value to your variable
public Boolean mIsVisibleToUser = false;

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
}

Android studio play an audio file without a button click

I recently paid someone to develop an experimental app for me. The app basically shows a picture with a couple of "buttons" in the corner that have other functions. Essentially, I also want an audio file to play automatically when the image is presented without having to click a button (this sort of function is already written into the script). I'm not a programmer (which is why I had to hire someone) but he couldn't figure out how to do this either. I just wondered whether anyone has any suggestions I can try?
Here is the code that controls the audio files:
public class ObjectFragment extends Fragment {
private int index;
private int trackID;
private int videoID;
private boolean visible;
private Integer[] imageIDs = {R.drawable.c1, R.drawable.c2, R.drawable.c3,
R.drawable.k1, R.drawable.k2, R.drawable.k3,
R.drawable.m1, R.drawable.m2, R.drawable.m3};
private Integer[] trackIDs = {R.raw.chatten, R.raw.chatten, R.raw.chatten,
R.raw.kobo, R.raw.kobo, R.raw.kobo,
R.raw.manu, R.raw.manu, R.raw.manu};
private Integer[] videos = {R.raw.chatten_vid2, R.raw.kobo_vid2, R.raw.manu_vid2};
static ObjectFragment newInstance(int i) {
ObjectFragment f = new ObjectFragment();
Bundle args = new Bundle();
args.putInt("index", i);
f.setArguments(args);
return f;
}
/**
* When creating, retrieve this instance's number from its arguments.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
index = getArguments() != null ? getArguments().getInt("index") : 0;
trackID = getArguments() != null ? getArguments().getInt("index") : 0;
}
#SuppressLint("SetTextI18n")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
visible = true;
final View rootView = inflater.inflate(R.layout.fragment_collection_object, container, false);
final Button videoButton = (Button) rootView.findViewById(R.id.video);
videoButton.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if(MotionEventCompat.getActionMasked(motionEvent)==MotionEvent.ACTION_DOWN)
MainActivity.getPerson().formatString(System.nanoTime()-MainActivity.initTime, "button", motionEvent.getX(), motionEvent.getY(), "video");
return false;
}
});
final VideoView videoView = (VideoView) rootView.findViewById(R.id.videoView);
final TextView tv = (TextView) rootView.findViewById(R.id.word);
final int word;
((ImageView) rootView.findViewById(R.id.imageView)).setImageResource(imageIDs[index]);
//Change values here!!!
if(index<4) {
word=3;
tv.setText("Chatten");
videoButton.setBackgroundResource(R.drawable.snapchatten2);
videoID=0;
}
else if(index <8) {
word=7;
tv.setText("Kobo");
videoButton.setBackgroundResource(R.drawable.snapkobo2);
videoID=1;
}
else {
word=11;
tv.setText("Manu");
videoButton.setBackgroundResource(R.drawable.snapmanu2);
videoID=2;
}
rootView.findViewById(R.id.abc).setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
String text="";
if(word==3)
text = "Chatten";
else if(word==7)
text = "Kobo";
else if(word==11)
text="Manu";
if(MotionEventCompat.getActionMasked(motionEvent)==MotionEvent.ACTION_DOWN)
MainActivity.getPerson().formatString(System.nanoTime()-MainActivity.initTime, "button", motionEvent.getX(), motionEvent.getY(), "abc "+text);
return false;
}
});
rootView.findViewById(R.id.abc).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
tv.setVisibility(View.VISIBLE);
MainActivity.music.stop();
MainActivity.music.doInBackground(new Object[]{trackIDs[trackID]});
MainActivity.music.setLooping(false);
MainActivity.music.play();
while (!MainActivity.playBgMusic()) ;
}
});
rootView.findViewById(R.id.babylabs).setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (MotionEventCompat.getActionMasked(motionEvent) == MotionEvent.ACTION_DOWN)
MainActivity.getPerson().formatString(System.nanoTime() - MainActivity.initTime, "button", motionEvent.getX(), motionEvent.getY(), "babylabs");
return false;
}
});
rootView.findViewById(R.id.babylabs).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (tv.getVisibility() == View.VISIBLE) {
tv.setVisibility(View.GONE);
return;
}
visible = false;
MainActivity.back_counter = 1;
getActivity().onBackPressed();
}
});
videoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
videoButton.setVisibility(View.INVISIBLE);
MainActivity.music.pause();
rootView.findViewById(R.id.imageView).setVisibility(View.INVISIBLE);
videoView.setVisibility(View.VISIBLE);
videoView.setVideoURI(Uri.parse("android.resource://" + getActivity().getPackageName() + "/" + videos[videoID]));
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
videoView.start();
}
});
videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
videoView.setVisibility(View.GONE);
videoButton.setVisibility(View.VISIBLE);
rootView.findViewById(R.id.imageView).setVisibility(View.VISIBLE);
MainActivity.music.play();
}
});
}
});
return rootView;
}
}
Code snippet with ViewTreeObserver solution. It tells you when the image is drawn.
ViewTreeObserver vto = yourImage.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#SuppressWarnings("deprecation")
#Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT < 16) {
yourImage.getViewTreeObserver().removeGlobalOnLayoutListener(this);
} else {
yourImage.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
// do additional stuff here
MainActivity.music.play();
}
});
You can add this code to your oncreate method. Don't forget to prepare your player before. Maybe you want to add a onloadcomplete listener.

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

Categories

Resources