I am right now fetching movies to my MainActivity.
I need infinite scroll on my RecycleView inside MainActivity.
Can someone tell me where to set code so I can have infinite scroll?
If you need more data, tell me.
Thank you.
MainActivity Code is bellow:
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private MoviesAdapter mAdapter;
#Override
protected void onResume() {
SharedPreferences sharedPref = getBaseContext().getSharedPreferences(getString(R.string.preference_file_key), Context.MODE_PRIVATE);
String order = sharedPref.getString("order", "popular");
if (order.equals("popular")) {
getPopularMovies();
} else {
getTopRatedMovies();
}
super.onResume();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// uci i postaviti order -> popular
Log.d("NESTO", "NESTO-onCreate");
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setLayoutManager(new GridLayoutManager(this, 2));
mAdapter = new MoviesAdapter(MainActivity.this);
mRecyclerView.setAdapter(mAdapter);
}
private void getTopRatedMovies() {
RestAdapter.getMovieService().getTopRatedMovies(new Callback<MovieResult>() {
#Override
public void success(MovieResult movieResult, Response response) {
mAdapter.setMovieList(movieResult.getResults());
}
#Override
public void failure(RetrofitError error) {
error.printStackTrace();
}
});
}
private void getPopularMovies() {
RestAdapter.getMovieService().getPopularMovies(new Callback<MovieResult>() {
#Override
public void success(MovieResult movieResult, Response response) {
mAdapter.setMovieList(movieResult.getResults());
}
#Override
public void failure(RetrofitError error) {
error.printStackTrace();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class MovieViewHolder extends RecyclerView.ViewHolder {
public ImageView imageView;
public MovieViewHolder(View itemView) {
super(itemView);
imageView = (ImageView) itemView.findViewById(R.id.imageView);
}
}
}
Related
I have implemented a cardview along with a recyclerview that fetch data from firebase. I want to implement onclick methods to cards that goes for different activities. How can i add on click method for the cards? Here is my mainactivity.
public class English extends AppCompatActivity {
ViewHolder apt;
RecyclerView mRecyclerView;
FirebaseDatabase mFirebaseDatabase;
DatabaseReference mRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_english);
mRecyclerView = findViewById(R.id.recyclerView);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mFirebaseDatabase = FirebaseDatabase.getInstance();
mRef = mFirebaseDatabase.getReference("English");
}
private void firebaseSearch(String searchText){
Query firebaseSearchQuery=mRef.orderByChild("artist").startAt(searchText).endAt(searchText + "\uf8ff");
FirebaseRecyclerAdapter<englishacti, ViewHolder> firebaseRecyclerAdapter=new FirebaseRecyclerAdapter<englishacti, ViewHolder>(englishacti.class,R.layout.row,ViewHolder.class,firebaseSearchQuery) {
#Override
protected void populateViewHolder(ViewHolder holder, englishacti model, int position) {
holder.setDetails(getApplicationContext(),model.getAlbum(),model.getDescription(),model.getImage(),model.getArtist());
}
};
mRecyclerView.setAdapter(firebaseRecyclerAdapter);
}
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerAdapter<englishacti,ViewHolder> firebaseRecyclerAdapter;
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<englishacti, ViewHolder>(englishacti.class,R.layout.row,ViewHolder.class,mRef) {
#Override
protected void populateViewHolder(ViewHolder viewHolder, englishacti model, int position) {
viewHolder.setDetails(getApplicationContext(), model.getAlbum(), model.getDescription(), model.getImage(), model.getArtist());
}
};
mRecyclerView.setAdapter(firebaseRecyclerAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu,menu);
MenuItem item = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
firebaseSearch(query);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
firebaseSearch(newText);
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id=item.getItemId();
if (id==R.id.action_settings){
return true;
}
return super.onOptionsItemSelected(item);
}
}
please take a look at my snipshed code, in my case i use this way to implement setonlclick in recycleview item and send value to other activity
holder.setName(userName);
holder.setUserImage(userThumb, getContext());
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent chatIntent = new Intent(getContext(), Tampung_chatActivity.class);
chatIntent.putExtra("user_id", list_user_id);
chatIntent.putExtra("user_name", userName);
startActivity(chatIntent);
}
});
full code you can see at here :
full snipshed code implement onclick with recycleview and firebase
I have navigationdrawer with nav menus. When clicking on each nav menus, specific fragment opened. Each fragment display recylerviews who fetch data from SQLite external database.Now when open new fragment, little seconds must wait and when to click on each item for go to next activity for display details information about the item, 5 seconds must wait to open Details Activity. I know this is a problem for fetching data in main Thread and fetch bitmap in the main thread.But I don't know how to solve this problem with use AsyncTask.My big problem is an open new activity for display information and waiting for 5 seconds.
This is my asiafragment.
AsiaFragment
public class AsiaFragment extends Fragment {
private static final String ASIA_FRAGMENT = "asia_fragment";
ArrayList<AsiaCountry> asiaCountries = new ArrayList<>();
ContentAdapter contentAdapter;
RecyclerView recyclerView;
private boolean isListView;
private Menu menu;
private StaggeredGridLayoutManager staggeredGridLayoutManager;
private MyAsyncTas myAsyncTas;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.asia_fragment, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
getActivity().setTitle("Asia");
isListView = true;
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
new MyAsyncTas().execute();
}
// When click on grid icon, view items must be convert to grid.
public void toggle() {
MenuItem item = menu.findItem(R.id.grid);
if (isListView) {
staggeredGridLayoutManager.setSpanCount(2);
item.setIcon(R.drawable.ic_vertical);
item.setTitle("Show as list");
isListView = false;
} else {
staggeredGridLayoutManager.setSpanCount(1);
item.setIcon(R.drawable.ic_grid);
item.setTitle("Show grid");
isListView = true;
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.grid_item, menu);
this.menu = menu;
Log.d("Menu created", "grid");
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.grid) {
Toast.makeText(getActivity(), "Grid item touched", Toast.LENGTH_SHORT).show();
toggle();
return true;
}
if (id == R.id.settings) {
Toast.makeText(getActivity(), "Setting clicked", Toast.LENGTH_SHORT).show();
return true;
}
return onOptionsItemSelected(item);
}
// When loading AsiaFragment, database loading from Eternal database.
public void loadDataBase() {
WorldCountryDatabase worldCountryDatabase = new WorldCountryDatabase(getActivity());
try {
worldCountryDatabase.createDatabase();
worldCountryDatabase.openDataBase();
Log.d("TAG", "Database open");
} catch (SQLiteException o) {
o.printStackTrace();
Log.d("Tag", o.getMessage());
}
try {
// Tell to database , take name and viewImage from worldCountries .
Cursor cursor = worldCountryDatabase.QueryData("SELECT name, Image FROM country WHERE continent ='آسیا'");
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
AsiaCountry asiaCountry = new AsiaCountry();
asiaCountry.setName(cursor.getString(0));
asiaCountry.setFlag(cursor.getString(1));
Log.d(ASIA_FRAGMENT, cursor.getString(1));
asiaCountries.add(asiaCountry);
} while (cursor.moveToNext());
worldCountryDatabase.close();
}
}
} catch (SQLiteException o) {
o.printStackTrace();
Log.d("TAG", o.getMessage());
}
// When loading RecylerView staggeredGridLayout loading.
staggeredGridLayoutManager = new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL);
contentAdapter = new ContentAdapter(getActivity(), asiaCountries);
contentAdapter.notifyDataSetChanged();
contentAdapter.setListener(new ContentAdapter.Listener() {
#Override
public void onClick(int position) {
}
});
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(staggeredGridLayoutManager);
recyclerView.setAdapter(contentAdapter);
}
public class MyAsyncTas extends AsyncTask<Void, Void, Boolean> {
#Override
protected Boolean doInBackground(Void... params) {
return true;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
loadDataBase();
}
}
This is my DetailCountry fragment, who must be displayed detatail country clicked.
DetailsCountry
public class DetailsCountry extends AppCompatActivity implements
TabLayout.OnTabSelectedListener,
EconomicFragment.EconomicOnFragmentInteractionListener,
SummarizeFragment.SummarizeOnFragmentInteractionListener,
HistoryFragment.HistoryOnFragmentInteractionListener,
GeographyFragment.GeographyOnFragmentInteractionListener,
TipsFragment.TipsOnFragmentInteractionListener,
DescriptionFragment.OtherOnFragmentInteractionListener,
PeopleFragment.PeopleOnFragmentInteractionListener {
public static String NAME_COUNTRY = "name";
public final String pageTitle[] = {"خلاصه",
"تاریخ",
"جغرافی",
"اقتصاد",
"مردم",
"غیره",
"نکات"};
ArrayList<AsiaCountry> asiaList = new ArrayList<>();
ImageView imageHistory;
TabLayout tabLayout;
ViewPager viewPager;
String content;
Bundle bundle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detial_country);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_details);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
viewPager = (ViewPager) findViewById(R.id.viewPager_detail_country);
tabLayout = (TabLayout) findViewById(R.id.tabLayout_detail_country);
imageHistory = (ImageView) findViewById(R.id.image_detail_country);
bundle = getIntent().getExtras();
if (bundle != null) {
content = bundle.getString("name");
Log.d("contentDetail", content);
}
// Set title for activity title.
getSupportActionBar().setTitle(content);
retrieveData();
if (asiaList != null && asiaList.size() > 0) {
for (int i = 0; i < asiaList.size(); i++) {
imageHistory.setImageBitmap(loadBitmapFromAssets(getApplicationContext(),
asiaList.get(i).getImageResourceID()));
}
}
int numberPage = 7;
for (int i = 0; i < numberPage; i++) {
tabLayout.addTab(tabLayout.newTab().setText(pageTitle[i]));
}
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
ViewPagerCountryAdapter viewPagerAdapter = new ViewPagerCountryAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setOnTabSelectedListener(this);
}
private void retrieveData() {
WorldCountryDatabase worldCountryDatabase = new WorldCountryDatabase(getApplicationContext());
worldCountryDatabase.createDatabase();
worldCountryDatabase.openDataBase();
Log.d(ARG_PARAM1, "Database opened");
try {
Cursor cursor = worldCountryDatabase.QueryData("SELECT viewImage FROM country WHERE name = '" + content + "'");
Log.d("CURSOR", cursor.toString());
if (cursor.moveToFirst()) {
do {
AsiaCountry asia = new AsiaCountry();
asia.setImageResourceID(cursor.getString(0));
Log.d("image", cursor.getString(0));
asiaList.add(asia);
} while (cursor.moveToNext());
cursor.close();
}
} catch (SQLException e) {
e.printStackTrace();
Log.d("TAG", e.getMessage());
}
}
#Nullable
private Bitmap loadBitmapFromAssets(Context context, String path) {
InputStream stream = null;
try {
stream = context.getAssets().open(path);
return BitmapFactory.decodeStream(stream);
} catch (Exception ignored) {
} finally {
try {
if (stream != null) {
stream.close();
}
} catch (Exception ignored) {
}
}
return null;
}
#Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(base));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
#Override
public void economiOnFragmentInteraction(Uri uri) {
}
#Override
public void tipsOnFragmentInteraction(Uri uri) {
}
#Override
public void otherOnFragmentInteraction(Uri uri) {
}
#Override
public void peopleOnFragmentInteraction(Uri uri) {
}
#Override
public void historyOnFragmentInteraction(Uri uri) {
}
#Override
public void geographyOnFragmentInteraction(Uri uri) {
}
#Override
public void summarizeOnFragmentInteraction(Uri uri) {
}
public class DetailTask extends AsyncTask<Void, Void, Boolean>{
#Override
protected Boolean doInBackground(Void... params) {
return null;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
}
}
Please help me, good friends. Thanks
I'm trying to understand how to implement a search with chips (so there should be the chance to add more than one value) and the suggestion list should come from a web service using Retrofit. An example on what I would like to achieve is the search in Pinterest app.
I read online many post where someone uses AutoCompleteTextView and other SearchView and to be honest I'm very confused on which approach to follow.
Could you address me to the right way please?
Thanks
Here is code example of using Retrofit with AutocompleteEditText
public class MainActivity extends Activity {
private interface GooglePlacesClient {
#GET("/maps/api/place/autocomplete/json")
Observable<PlacesResult> autocomplete(
#Query("key") String key,
#Query("input") String input);
}
private class PlacesResult {
#Expose
List<MainActivity.Prediction> predictions;
#Expose
String status;
}
private class Prediction {
#Expose
String description;
}
private static final String LOG_TAG = "RxRetrofitAutoComplete";
private static final String GOOGLE_API_BASE_URL = "https://maps.googleapis.com";
private static final String API_KEY = "XXX";
private static final int DELAY = 500;
GooglePlacesClient mGooglePlacesClient;
#InjectView(R.id.editText1)
EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
if (API_KEY.length()<10) {
Toast.makeText(this, "API KEY is unset!", Toast.LENGTH_LONG).show();
return;
}
if (mGooglePlacesClient == null) {
mGooglePlacesClient = new RestAdapter.Builder()
.setConverter(new GsonConverter(new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()))
.setEndpoint(GOOGLE_API_BASE_URL)
.setLogLevel(RestAdapter.LogLevel.FULL).build()
.create(GooglePlacesClient.class);
}
Observable<EditText> searchTextObservable = ViewObservable.text(editText);
searchTextObservable.debounce(DELAY, TimeUnit.MILLISECONDS)
.map(new Func1<EditText, String>() {
#Override
public String call(EditText editText) {
return editText.getText().toString();
}
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<String>() {
#Override
public void call(String s) {
Log.d(LOG_TAG, s);
try {
mGooglePlacesClient
.autocomplete(API_KEY, URLEncoder.encode(s, "utf8"))
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<PlacesResult>() {
#Override
public void call(PlacesResult placesResult) {
List<String> strings = new ArrayList<String>();
for (MainActivity.Prediction p : placesResult.predictions) {
strings.add(p.description);
}
ListView listView = (ListView) findViewById(R.id.listView1);
if (listView != null) {
listView.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, strings));
}
}
}, new Action1<Throwable>() {
#Override
public void call(Throwable throwable) {
throwable.printStackTrace();
}
});
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}, new Action1<Throwable>() {
#Override
public void call(Throwable throwable) {
throwable.printStackTrace();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_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) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onStop() {
super.onStop();
}
}
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
I'm not sure how to add a progress bar or make a loading dialog while the data is being retrieved from parse.
This is my code below for retrieving the data from parse. I've tried few tutorials but none have seemed to work for me.
public class HolidayActivity extends AppCompatActivity {
private HolidayAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_holiday);
//noinspection ConstantConditions
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setIcon(R.drawable.dl);
ParseObject.registerSubclass(Holiday.class);
mAdapter = new HolidayAdapter(this, new ArrayList<Holiday>());
ListView mListView = (ListView) findViewById(R.id.holiday_list);
mListView.setAdapter(mAdapter);
updateData();
}
public void updateData() {
ParseQuery<Holiday> query = ParseQuery.getQuery(Holiday.class);
query.setCachePolicy(ParseQuery.CachePolicy.CACHE_THEN_NETWORK);
query.findInBackground(new FindCallback<Holiday>() {
#Override
public void done(List<Holiday> holidays, com.parse.ParseException e) {
if (holidays != null) {
mAdapter.clear();
for (int i = 0; i < holidays.size(); i++) {
mAdapter.add(holidays.get(i));
}
}
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// app icon in action bar clicked; goto parent activity.
this.finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Add this to your updateData():
public void updateData() {
final ProgressDialog progressDialog = ProgressDialog.show(this, null, "Loading…");
(…)
#Override
public void done(List<Holiday> holidays, com.parse.ParseException e) {
progressDialog.dismiss();
(…)
}
}
Hope it helps!