I am trying to save the type of map that the user selected through the menu so the type of map remains even if the device will be rotated or the activity will be suspended for a few moments. This is what I did but it doesn't seem to work. Please can you tell me what am I doing wrong?
private int mapTypeSelected;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null){
mapTypeSelected = GoogleMap.MAP_TYPE_NORMAL;
} else {
mapTypeSelected = savedInstanceState.getInt("the_map_type",GoogleMap.MAP_TYPE_NORMAL);
}
}
My main menu has more choices but I added here only the relevant ones for the map type:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.change_map_type:
Toast.makeText(getApplicationContext(), "Change map type", Toast.LENGTH_LONG).show();
return true;
case R.id.map_type_normal:
mapTypeSelected = GoogleMap.MAP_TYPE_NORMAL;
mMap.setMapType(mapTypeSelected);
return true;
case R.id.map_type_satellite:
mapTypeSelected = GoogleMap.MAP_TYPE_SATELLITE;
mMap.setMapType(mapTypeSelected);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Then at the end of my activity I added this two:
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("the_map_type", mapTypeSelected);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
savedInstanceState.get("the_map_type");
}
I am sure that is something stupid that I am doing wrong but I cannot seem to see what. There is no error and everything is working fine just that on rotation the map type changes always to normal.
Thanks in advance for any help!
Try this one..
private int mMapType;
private boolean mRestoreMap;
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("the_map_type", mMap.getMapType());
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mMapType = savedInstanceState.getInt("the_map_type", -1);
mRestoreMap = (mMapType != -1);
}
#Override
public void onMapReady(GoogleMap map) {
mMap = map;
if(mRestoreMap){
mMap.setMapType(mMapType);
}
}
Related
I have tried writing asynctask within fragment so that orientation dilemma can be solveable.So far asynctask working good but the progressbar which is associated with it, on screen change, not showing .
I have attached my code below .
On Screen rotate, progressbar and textview gets hidden
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.a_fragment, container, false);
unbinder = ButterKnife.bind(this, view);
setRetainInstance(true);
return view;
}
#OnClick(R.id.btn)
public void onViewClicked() {
Log.w(TAG, "onBtn clicked");
new URLAsyncTask().execute();
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
progressBar.setVisibility(View.VISIBLE);
tvProgress.setVisibility(View.VISIBLE);
progressValue = savedInstanceState.getInt("value");
System.out.println(progressValue);
progressBar.setProgress(progressValue);
String rcv = savedInstanceState.getString("value2");
tvProgress.setText(rcv);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("value", progressBar.getProgress());
outState.putString("value2", tvProgress.getText().toString());
}
private class URLAsyncTask extends AsyncTask<Void, Integer, String> {
#Override
protected void onPreExecute() {
progressBar.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(Void... voids) {
String result = null;
for (int i = 0; i <= 20; i++) {
SystemClock.sleep(500);
System.out.println("Loading..... " + i);
publishProgress(i);
}
result = "A dummy";
return result;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progressBar.setProgress(values[0]);
progressValue = values[0];
tvProgress.setText("Loading .. at % ".concat(String.valueOf(progressValue)));
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.d(TAG, "onPostExecute() : s : " + s);
System.out.println(TAG + " " + progressValue);
if (progressValue == 20) {
tvProgress.setText("LOADING 100 % DONE");
progressBar.setVisibility(View.GONE);
}
}
}
}
A bit help would be highly appreciated
I dont understand well your problem but I assume that you have problem with device orientation in fragment, that the AsynTask is reexecuting and displaying wrong percentage.
If I'm correct: Then instead using AsynTask, try this :
AsynTaskLoader
Also you can find some quality tutorial on Udacity`s Android Developer Course,
(free)
https://www.udacity.com/course/android-basics-networking--ud843
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.
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
}
I have a SettingsActivity which extends PreferenceActivity to show settings in my app.
There is a back arrow, but it is not working.
Here's SettingsActivity.java file's code:
public class SettingsActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener{
private AppCompatDelegate mDelegate;
public static final String RESET_PASSWORD_KEY = "reset_password";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
getDelegate().installViewFactory();
getDelegate().onCreate(savedInstanceState);
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
SharedPreferences sharedPreferencesCompat = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
Preference myPref = (Preference) findPreference(RESET_PASSWORD_KEY);
myPref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
//open browser or intent here
Intent resetPasswordActivityIntent = new Intent(SettingsActivity.this, ResetPasswordActivity.class);
startActivity(resetPasswordActivityIntent);
return true;
}
});
}
#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);
getDelegate().getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
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;
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals(RESET_PASSWORD_KEY)) {
}
}
}
Here's preferences.xml file's code:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<Preference
android:title="xxx"
android:summary="xxxxxx"
android:key="reset_password" />
</PreferenceScreen>
Here's how 'SettingsActivity' is defined in AndroidManifest.xml:
<activity
android:name=".SettingsActivity"
android:label="#string/title_activity_settings"
android:parentActivityName=".MainActivity">
</activity>
How can I make that arrow operational?
Please let me know.
Sorry, if question format seems inappropriate. I'm still a beginner.
You need to call your private method setSupportActionBar() inside onCreate().
Also, you might want to implement onOptionsItemSelected:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
You can do it like this
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
I have made some assumptions on what you might be trying to achieve. This should work if you want to use a custom toolbar with PreferenceActivity. The following code goes inside onPostCreateView()
LinearLayout root = (LinearLayout)findViewById(android.R.id.list).getParent().getParent().getParent();
mToolBar = (Toolbar) LayoutInflater.from(this).inflate(R.layout.toolbar, root,false);
mToolBar.setTitle(R.string.title);
// insert at top
root.addView(mToolBar, 0);
setSupportActionBar(mToolBar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
You forgot to call this method in your onCreate()
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
In Android targetSdkVersion 29
inside onCreate()
getActionBar().setDisplayHomeAsUpEnabled(true);
then implement onOptionsItemSelected from #Matias Elorriaga Answer
If all else fails, try calling setDisplayHomeAsUpEnabled() twice with different arguments:
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
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