Add Material Dialog from library - android

I want to use this from the material-dialog library without using the library in my build.gradle file.
Is there a way to do that?

Thanks to Abderrahim Soubai Elidrissi deleted answer I used LovelyDialog and implemented the following classes in my project:
AbsLovelyDialog.java
#SuppressWarnings({"unchecked", "WeakerAccess"})
public abstract class AbsLovelyDialog<T extends AbsLovelyDialog> {
private static final String KEY_SAVED_STATE_TOKEN = "key_saved_state_token";
private Dialog dialog;
private View dialogView;
private ImageView iconView;
private TextView topTitleView;
private TextView titleView;
private TextView messageView;
public AbsLovelyDialog(Context context) {
init(new AlertDialog.Builder(context));
}
public AbsLovelyDialog(Context context, int theme) {
init(new AlertDialog.Builder(context, theme));
}
private void init(AlertDialog.Builder dialogBuilder) {
dialogView = LayoutInflater.from(dialogBuilder.getContext()).inflate(getLayout(), null);
dialog = dialogBuilder.setView(dialogView).create();
iconView = findView(R.id.ld_icon);
titleView = findView(R.id.ld_title);
messageView = findView(R.id.ld_message);
topTitleView = findView(R.id.ld_top_title);
}
#LayoutRes
protected abstract int getLayout();
public T setMessage(#StringRes int message) {
return setMessage(string(message));
}
public T setMessage(CharSequence message) {
messageView.setVisibility(View.VISIBLE);
messageView.setText(message);
return (T) this;
}
public T setTitle(#StringRes int title) {
return setTitle(string(title));
}
public T setTopTitle(#StringRes int title) {
return setTopTitle(string(title));
}
public T setTitle(CharSequence title) {
titleView.setVisibility(View.VISIBLE);
titleView.setText(title);
return (T) this;
}
public T setTopTitle(CharSequence title) {
topTitleView.setVisibility(View.VISIBLE);
topTitleView.setText(title);
return (T) this;
}
public T setTopTitleColor(int color) {
topTitleView.setTextColor(color);
return (T) this;
}
public T setIcon(Bitmap bitmap) {
iconView.setVisibility(View.VISIBLE);
iconView.setImageBitmap(bitmap);
return (T) this;
}
public T setIcon(Drawable drawable) {
iconView.setVisibility(View.VISIBLE);
iconView.setImageDrawable(drawable);
return (T) this;
}
public T setIcon(#DrawableRes int iconRes) {
iconView.setVisibility(View.VISIBLE);
iconView.setImageResource(iconRes);
return (T) this;
}
public T setIconTintColor(int iconTintColor) {
iconView.setColorFilter(iconTintColor);
return (T) this;
}
public T setTitleGravity(int gravity) {
titleView.setGravity(gravity);
return (T) this;
}
public T setMessageGravity(int gravity) {
messageView.setGravity(gravity);
return (T) this;
}
public T setTopColor(#ColorInt int topColor) {
findView(R.id.ld_color_area).setBackgroundColor(topColor);
return (T) this;
}
public T setTopColorRes(#ColorRes int topColoRes) {
return setTopColor(color(topColoRes));
}
/*
* You should call method saveInstanceState on handler object and then use saved info to restore
* your dialog in onRestoreInstanceState. Static methods wasDialogOnScreen and getDialogId will
* help you in this.
*/
public T setInstanceStateHandler(int id, LovelySaveStateHandler handler) {
handler.handleDialogStateSave(id, this);
return (T) this;
}
public T setCancelable(boolean cancelable) {
dialog.setCancelable(cancelable);
return (T) this;
}
public T setSavedInstanceState(Bundle savedInstanceState) {
if (savedInstanceState != null) {
boolean hasSavedStateHere =
savedInstanceState.keySet().contains(KEY_SAVED_STATE_TOKEN) &&
savedInstanceState.getSerializable(KEY_SAVED_STATE_TOKEN) == getClass();
if (hasSavedStateHere) {
restoreState(savedInstanceState);
}
}
return (T) this;
}
public Dialog show() {
dialog.show();
return dialog;
}
public Dialog create() {
return dialog;
}
public void dismiss() {
dialog.dismiss();
}
void onSaveInstanceState(Bundle outState) {
outState.putSerializable(KEY_SAVED_STATE_TOKEN, getClass());
}
void restoreState(Bundle savedState) {
}
boolean isShowing() {
return dialog != null && dialog.isShowing();
}
protected String string(#StringRes int res) {
return dialogView.getContext().getString(res);
}
protected int color(#ColorRes int colorRes) {
return ContextCompat.getColor(getContext(), colorRes);
}
protected Context getContext() {
return dialogView.getContext();
}
protected <ViewClass extends View> ViewClass findView(int id) {
return (ViewClass) dialogView.findViewById(id);
}
protected class ClickListenerDecorator implements View.OnClickListener {
private View.OnClickListener clickListener;
private boolean closeOnClick;
protected ClickListenerDecorator(View.OnClickListener clickListener, boolean closeOnClick) {
this.clickListener = clickListener;
this.closeOnClick = closeOnClick;
}
#Override
public void onClick(View v) {
if (clickListener != null) {
if (clickListener instanceof LovelyDialogCompat.DialogOnClickListenerAdapter) {
LovelyDialogCompat.DialogOnClickListenerAdapter listener =
(LovelyDialogCompat.DialogOnClickListenerAdapter) clickListener;
listener.onClick(dialog, v.getId());
} else {
clickListener.onClick(v);
}
}
if (closeOnClick) {
dismiss();
}
}
}
}
LovelyChoiceDialog.java
public class LovelyChoiceDialog extends AbsLovelyDialog<LovelyChoiceDialog> {
private static final String KEY_ITEM_CHECKED_STATES = "key_item_checked_states";
private ListView choicesList;
private TextView confirmButton;
{
choicesList = findView(R.id.ld_choices);
}
public LovelyChoiceDialog(Context context) {
super(context);
}
public LovelyChoiceDialog(Context context, int theme) {
super(context, theme);
}
public <T> LovelyChoiceDialog setItems(T[] items, OnItemSelectedListener<T> itemSelectedListener) {
return setItems(Arrays.asList(items), itemSelectedListener);
}
public <T> LovelyChoiceDialog setItems(List<T> items, OnItemSelectedListener<T> itemSelectedListener) {
ArrayAdapter<T> adapter = new ArrayAdapter<>(getContext(),
R.layout.dialog_item_simple_text, android.R.id.text1,
items);
return setItems(adapter, itemSelectedListener);
}
public <T> LovelyChoiceDialog setItems(ArrayAdapter<T> adapter, OnItemSelectedListener<T> itemSelectedListener) {
choicesList.setOnItemClickListener(new ItemSelectedAdapter<>(itemSelectedListener));
choicesList.setAdapter(adapter);
return this;
}
public <T> LovelyChoiceDialog setItemsMultiChoice(T[] items, OnItemsSelectedListener<T> itemsSelectedListener) {
return setItemsMultiChoice(items, null, itemsSelectedListener);
}
public <T> LovelyChoiceDialog setItemsMultiChoice(T[] items, boolean[] selectionState, OnItemsSelectedListener<T> itemsSelectedListener) {
return setItemsMultiChoice(Arrays.asList(items), selectionState, itemsSelectedListener);
}
public <T> LovelyChoiceDialog setItemsMultiChoice(List<T> items, OnItemsSelectedListener<T> itemsSelectedListener) {
return setItemsMultiChoice(items, null, itemsSelectedListener);
}
public <T> LovelyChoiceDialog setItemsMultiChoice(List<T> items, boolean[] selectionState, OnItemsSelectedListener<T> itemsSelectedListener) {
ArrayAdapter<T> adapter = new ArrayAdapter<>(getContext(),
R.layout.dialog_item_simple_text_multichoice, android.R.id.text1,
items);
return setItemsMultiChoice(adapter, selectionState, itemsSelectedListener);
}
public <T> LovelyChoiceDialog setItemsMultiChoice(ArrayAdapter<T> adapter, OnItemsSelectedListener<T> itemsSelectedListener) {
return setItemsMultiChoice(adapter, null, itemsSelectedListener);
}
public <T> LovelyChoiceDialog setItemsMultiChoice(ArrayAdapter<T> adapter, boolean[] selectionState, OnItemsSelectedListener<T> itemsSelectedListener) {
LayoutInflater inflater = LayoutInflater.from(getContext());
View confirmBtnContainer = inflater.inflate(R.layout.dialog_item_footer_confirm, null);
confirmButton = (TextView) confirmBtnContainer.findViewById(R.id.ld_btn_confirm);
confirmButton.setOnClickListener(new ItemsSelectedAdapter<>(itemsSelectedListener));
choicesList.addFooterView(confirmBtnContainer);
ListView choicesList = findView(R.id.ld_choices);
choicesList.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE);
choicesList.setAdapter(adapter);
if (selectionState != null) {
for (int i = 0; i < selectionState.length; i++) {
choicesList.setItemChecked(i, selectionState[i]);
}
}
return this;
}
public LovelyChoiceDialog setConfirmButtonText(#StringRes int text) {
return setConfirmButtonText(string(text));
}
public LovelyChoiceDialog setConfirmButtonText(String text) {
if (confirmButton == null) {
throw new IllegalStateException(string(R.string.ex_msg_dialog_choice_confirm));
}
confirmButton.setText(text);
return this;
}
public LovelyChoiceDialog setConfirmButtonColor(int color) {
if (confirmButton == null) {
throw new IllegalStateException(string(R.string.ex_msg_dialog_choice_confirm));
}
confirmButton.setTextColor(color);
return this;
}
#Override
void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (isMultiChoiceList()) {
ListAdapter adapter = choicesList.getAdapter();
boolean[] checkedStates = new boolean[adapter.getCount()];
SparseBooleanArray checkedPositions = choicesList.getCheckedItemPositions();
for (int i = 0; i < checkedPositions.size(); i++) {
if (checkedPositions.valueAt(i)) {
checkedStates[checkedPositions.keyAt(i)] = true;
}
}
outState.putBooleanArray(KEY_ITEM_CHECKED_STATES, checkedStates);
}
}
#Override
void restoreState(Bundle savedState) {
super.restoreState(savedState);
if (isMultiChoiceList()) {
boolean[] checkedStates = savedState.getBooleanArray(KEY_ITEM_CHECKED_STATES);
if (checkedStates == null) {
return;
}
for (int index = 0; index < checkedStates.length; index++) {
choicesList.setItemChecked(index, checkedStates[index]);
}
}
}
#Override
protected int getLayout() {
return R.layout.dialog_choice;
}
private boolean isMultiChoiceList() {
return choicesList.getChoiceMode() == AbsListView.CHOICE_MODE_MULTIPLE;
}
public interface OnItemSelectedListener<T> {
void onItemSelected(int position, T item);
}
public interface OnItemsSelectedListener<T> {
void onItemsSelected(List<Integer> positions, List<T> items);
}
private class ItemSelectedAdapter<T> implements AdapterView.OnItemClickListener {
private OnItemSelectedListener<T> adaptee;
private ItemSelectedAdapter(OnItemSelectedListener<T> adaptee) {
this.adaptee = adaptee;
}
#Override
#SuppressWarnings("unchecked")
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (adaptee != null) {
adaptee.onItemSelected(position, (T) parent.getItemAtPosition(position));
}
dismiss();
}
}
private class ItemsSelectedAdapter<T> implements View.OnClickListener {
private OnItemsSelectedListener<T> adaptee;
private ItemsSelectedAdapter(OnItemsSelectedListener<T> adaptee) {
this.adaptee = adaptee;
}
#Override
#SuppressWarnings("unchecked")
public void onClick(View v) {
if (adaptee != null) {
SparseBooleanArray checkedItemPositions = choicesList.getCheckedItemPositions();
List<T> selectedItems = new ArrayList<>(checkedItemPositions.size());
List<Integer> selectedPositions = new ArrayList<>(checkedItemPositions.size());
ListAdapter adapter = choicesList.getAdapter();
for (int index = 0; index < adapter.getCount(); index++) {
if (checkedItemPositions.get(index)) {
selectedPositions.add(index);
selectedItems.add((T) adapter.getItem(index));
}
}
adaptee.onItemsSelected(selectedPositions, selectedItems);
}
dismiss();
}
}
}
LovelyDialogCompat.java
public class LovelyDialogCompat {
/**
* If you don't want to change implemented interfaces when migrating from standard dialogs
* to LovelyDialogs - use this method.
*/
public static View.OnClickListener wrap(Dialog.OnClickListener listener) {
return new DialogOnClickListenerAdapter(listener);
}
static class DialogOnClickListenerAdapter implements View.OnClickListener {
private Dialog.OnClickListener adapted;
DialogOnClickListenerAdapter(DialogInterface.OnClickListener adapted) {
this.adapted = adapted;
}
public void onClick(DialogInterface dialogInterface, int which) {
if (adapted != null) {
adapted.onClick(dialogInterface, which);
}
}
#Override
public void onClick(View v) {
}
}
}
LovelySaveStateHandler.java
public class LovelySaveStateHandler {
private static final String KEY_DIALOG_ID = "id";
private SparseArray<WeakReference<AbsLovelyDialog<?>>> handledDialogs;
public LovelySaveStateHandler() {
handledDialogs = new SparseArray<>();
}
public static boolean wasDialogOnScreen(Bundle savedInstanceState) {
return savedInstanceState.keySet().contains(KEY_DIALOG_ID);
}
public static int getSavedDialogId(Bundle savedInstanceState) {
return savedInstanceState.getInt(KEY_DIALOG_ID, -1);
}
public void saveInstanceState(Bundle outState) {
for (int index = handledDialogs.size() - 1; index >= 0; index--) {
WeakReference<AbsLovelyDialog<?>> dialogRef = handledDialogs.valueAt(index);
if (dialogRef.get() == null) {
handledDialogs.remove(index);
continue;
}
AbsLovelyDialog<?> dialog = dialogRef.get();
if (dialog.isShowing()) {
dialog.onSaveInstanceState(outState);
outState.putInt(KEY_DIALOG_ID, handledDialogs.keyAt(index));
return;
}
}
}
void handleDialogStateSave(int id, AbsLovelyDialog<?> dialog) {
handledDialogs.put(id, new WeakReference<AbsLovelyDialog<?>>(dialog));
}
}

Related

Add sheet from api step by step and dynamically

I am training to work with api and the problem arose that when scrolling the RecyclerView, I need the data to be added, namely, "page" is added, and thus the content is added.
I have achieved that before reaching the end of the list, the "onReachEndListener" method is triggered, but I cannot understand the implementation of adding to the sheet. PLEASE HELP ME!
public class MainActivity extends AppCompatActivity {
private SwitchMaterial switchMaterial;
private TextView textViewPopularity, textViewTopRated;
private RecyclerView recyclerViewPosters;
private MovieAdapter movieAdapter;
private MainViewModel viewModel;
private ProgressBar progressBar;
private static final int LOADER_ID = 122;
private LoaderManager loaderManager;
private static int page = 1;
private static String methodOfSort;
private static boolean isLoaning = true;
private static String lang;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.itemMain:
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
break;
case R.id.itemFavourite:
Intent i = new Intent(this, FavouriteActivity.class);
startActivity(i);
break;
}
return super.onOptionsItemSelected(item);
}
private int getColumnCount() {
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int width = (int) (displayMetrics.widthPixels / displayMetrics.density);
return width / 185 > 2 ? width / 2 : 2;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lang = Locale.getDefault().getLanguage();
viewModel = new ViewModelProvider(this).get(MainViewModel.class);
recyclerViewPosters = findViewById(R.id.recyclerViewPosters);
switchMaterial = findViewById(R.id.switchSort);
textViewPopularity = findViewById(R.id.textViewPopularity);
textViewTopRated = findViewById(R.id.textViewTopRated);
progressBar = findViewById(R.id.progressBarLoading);
movieAdapter = new MovieAdapter();
recyclerViewPosters.setLayoutManager(new GridLayoutManager(this, getColumnCount()));
recyclerViewPosters.setAdapter(movieAdapter);
switchMaterial.setChecked(true);
myOnClick();
LiveData<List<Movie>> moviesFromLiveData = viewModel.getMovies();
moviesFromLiveData.observe(this, new Observer<List<Movie>>() {
#Override
public void onChanged(#Nullable List<Movie> movies) {
movieAdapter.setMovies(movies);
}
});
}
private void myOnClick() {
switchMaterial.setOnCheckedChangeListener((compoundButton, b) -> {
page = 1;
setMethodOfSort(b);
});
switchMaterial.setChecked(false);
textViewPopularity.setOnClickListener(view -> {
setMethodOfSort(false);
switchMaterial.setChecked(false);
});
textViewTopRated.setOnClickListener(view -> {
setMethodOfSort(true);
switchMaterial.setChecked(true);
});
movieAdapter.setOnPosterClickListener(position -> {
Movie movie = movieAdapter.getMovies().get(position);
Intent intent = new Intent(MainActivity.this, DetailActivity.class);
intent.putExtra("id", movie.getId());
startActivity(intent);
});
movieAdapter.setOnReachEndListener(() -> {
if (!isLoaning){
viewModel.deleteAllMovies();
progressBar.setVisibility(View.VISIBLE);
viewModel.loadDataImage(lang, methodOfSort, Integer.toString(page));
Log.d("isLoaning", Integer.toString(page));
}
});
recyclerViewPosters.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (!recyclerView.canScrollVertically(1)) {
Log.d("isLoaning", Integer.toString(page));
LiveData<List<Movie>> moviesFromLiveData = viewModel.getMovies();
moviesFromLiveData.observe(MainActivity.this, new Observer<List<Movie>>() {
#Override
public void onChanged(#Nullable List<Movie> movies) {
viewModel.insertMovie(movies);
movieAdapter.addMovies(movies);
page++;
isLoaning = false;
}
});
}
}
});
}
private void setMethodOfSort(boolean b){
if(b) {
methodOfSort = SORT_BY_TOP_RATED;
Log.d("setMethodOfSort", methodOfSort);
textViewPopularity.setTextColor(getResources().getColor(R.color.white));
textViewTopRated.setTextColor(getResources().getColor(R.color.teal_200));
}
else {
methodOfSort = SORT_BY_POPULARITY;
Log.d("setMethodOfSort", methodOfSort);
textViewPopularity.setTextColor(getResources().getColor(R.color.teal_200));
textViewTopRated.setTextColor(getResources().getColor(R.color.white));
}
viewModel.loadData(lang, methodOfSort ,Integer.toString(page));
}
Model:
public class MainViewModel extends AndroidViewModel {
private static MovieDatabase database;
private LiveData<List<Movie>> movies;
private LiveData<List<FavouriteMovie>> favouriteMovies;
private LiveData<String> methodOfSort;
private CompositeDisposable compositeDisposable;
private MutableLiveData<Throwable> errors;
public static final String SMALL_POSTER_SIZE = "w185";
private static final String KEY_POSTER_PATH = "poster_path";
public static final String SORT_BY_POPULARITY = "popularity.desc";
public static final String SORT_BY_TOP_RATED = "vote_average.desc";
public static final int POPULARITY = 0;
public static final int TOP_RATED = 1;
public MainViewModel(#NonNull Application application) {
super(application);
database = MovieDatabase.getInstance(getApplication());
movies = database.movieDao().getAllMovies();
favouriteMovies = database.movieDao().getAllFavouriteMovies();
errors = new MutableLiveData<>();
}
public LiveData<Throwable> getErrors() {
return errors;
}
public void clearErrors() {
errors.setValue(null);
}
public void loadData(String lang, String sort, String page) {
ApiFactory apiFactory = ApiFactory.getInstance();
ApiService apiService = apiFactory.getApiService();
compositeDisposable = new CompositeDisposable();
Disposable disposable = apiService.getMovieResponse("32f91e104228c0c9ff3630899838e82e",
lang,
sort,
"1000",
page)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<MovieResponse>() {
#Override
public void accept(MovieResponse movieResponse) throws Exception {
deleteAllMovies();
insertMovie(movieResponse.getMovies());
}
}, new Consumer<Throwable>() {
#Override
public void accept(Throwable throwable) throws Exception {
errors.setValue(throwable);
}
});
compositeDisposable.add(disposable);
}
public void loadDataImage(String lang, String sort, String page) {
ApiFactory apiFactory = ApiFactory.getInstance();
ApiService apiService = apiFactory.getApiService();
compositeDisposable = new CompositeDisposable();
Disposable disposable = apiService.getMovieResponse(
"32f91e104228c0c9ff3630899838e82e",
lang,
sort,
"1000",
page)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<MovieResponse>() {
#Override
public void accept(MovieResponse movieResponse) throws Exception {
insertMovie(movieResponse.getMovies());
}
}, new Consumer<Throwable>() {
#Override
public void accept(Throwable throwable) throws Exception {
errors.setValue(throwable);
}
});
compositeDisposable.add(disposable);
}
public Movie getMovieById(int id) {
try {
return new GetMovieTask().execute(id).get();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
public FavouriteMovie getFavouriteMovieById(int id) {
try {
return new GetFavouriteMovieTask().execute(id).get();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
public LiveData<List<FavouriteMovie>> getFavouriteMovies() {
return favouriteMovies;
}
public void deleteAllMovies() {
new DeleteMoviesTask().execute();
}
#SuppressWarnings("unchecked")
public void insertMovie(List<Movie> movie) {
new InsertTask().execute(movie);
}
public void deleteMovie(Movie movie) {
new DeleteTask().execute(movie);
}
public LiveData<List<Movie>> getMovies() {
return movies;
}
public void insertFavouriteMovie(FavouriteMovie movie) {
new InsertFavouriteTask().execute(movie);
}
public void deleteFavouriteMovie(FavouriteMovie movie) {
new DeleteFavouriteTask().execute(movie);
}
private static class DeleteFavouriteTask extends AsyncTask<FavouriteMovie, Void, Void> {
#Override
protected Void doInBackground(FavouriteMovie... movies) {
if (movies != null && movies.length > 0) {
database.movieDao().deleteFavouriteMovie(movies[0]);
}
return null;
}
}
private static class InsertFavouriteTask extends AsyncTask<FavouriteMovie, Void, Void> {
#Override
protected Void doInBackground(FavouriteMovie... movies) {
if (movies != null && movies.length > 0) {
database.movieDao().insertFavouriteMovie(movies[0]);
}
return null;
}
}
private static class DeleteTask extends AsyncTask<Movie, Void, Void> {
#Override
protected Void doInBackground(Movie... movies) {
if (movies != null && movies.length > 0) {
database.movieDao().deleteMovie(movies[0]);
}
return null;
}
}
private static class InsertTask extends AsyncTask<List<Movie>, Void, Void> {
#Override
protected Void doInBackground(List<Movie>... movies) {
if (movies != null && movies.length > 0) {
database.movieDao().insertMovie(movies[0]);
}
return null;
}
}
private static class DeleteMoviesTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... integers) {
database.movieDao().deleteAllMovies();
return null;
}
}
private static class GetMovieTask extends AsyncTask<Integer, Void, Movie> {
#Override
protected Movie doInBackground(Integer... integers) {
if (integers != null && integers.length > 0) {
return database.movieDao().getMovieById(integers[0]);
}
return null;
}
}
private static class GetFavouriteMovieTask extends AsyncTask<Integer, Void, FavouriteMovie> {
#Override
protected FavouriteMovie doInBackground(Integer... integers) {
if (integers != null && integers.length > 0) {
return database.movieDao().getFavouriteMovieById(integers[0]);
}
return null;
}
}
#Override
protected void onCleared() {
compositeDisposable.dispose();
super.onCleared();
}
}
Adapter:
public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.MovieViewHolder> {
private List<Movie> movies;
private OnPosterClickListener onPosterClickListener;
private OnReachEndListener onReachEndListener;
private onStartLoadingListener onStartLoadingListener;
public MovieAdapter(){
movies = new ArrayList<>();
}
public interface OnPosterClickListener{
void OnPosterClick(int position);
}
public interface OnReachEndListener{
void onReachEnd();
}
public interface onStartLoadingListener{
void onStartLoading();
}
public void setOnStartLoadingListener(onStartLoadingListener onStartLoadingListener) {
this.onStartLoadingListener = onStartLoadingListener;
}
public void setOnPosterClickListener(OnPosterClickListener onPosterClickListener) {
this.onPosterClickListener = onPosterClickListener;
}
public void setOnReachEndListener(OnReachEndListener onReachEndListener) {
this.onReachEndListener = onReachEndListener;
}
#NonNull
#Override
public MovieViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.movie_item, parent, false);
return new MovieViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MovieViewHolder holder, int position) {
if (movies.size() >= 20 && position > movies.size() - 4 && onReachEndListener != null){
onReachEndListener.onReachEnd();
}
Movie movie = movies.get(position);
Picasso.get().load(movie.getPosterPath()).into(holder.imageViewSmallPoster);
}
#Override
public int getItemCount() {
return movies.size();
}
class MovieViewHolder extends RecyclerView.ViewHolder{
private ImageView imageViewSmallPoster;
public MovieViewHolder(#NonNull View itemView) {
super(itemView);
imageViewSmallPoster = itemView.findViewById(R.id.imageViewSmallPoster);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(onPosterClickListener != null){
onPosterClickListener.OnPosterClick(getAdapterPosition());
}
}
});
}
}
public void clear(){
this.movies.clear();
notifyDataSetChanged();
}
public List<Movie> getMovies() {
return movies;
}
public void addMovies(List<Movie> movies){
this.movies.addAll(movies);
notifyDataSetChanged();
}
public void setMovies(List<Movie> movies) {
this.movies = movies;
notifyDataSetChanged();
}
}

Unable to update view on data change in Epoxy Controller

I am using Epoxy Controller for Recycler View. I am having trouble changing the view after data changed by the user action.
Basically I have a switch button in a view which is used inside a recycler view and I am trying to update the view on switch button state change. I am calling requestModelBuild() in setProductList() function of the epoxy controller but change is not reflected in the view.
public class SellerInventoryListEpoxyController extends EpoxyController {
private List<Product> productList = Collections.emptyList();
private Context context;
private SellerInventoryListEpoxyController.Callbacks callbacks;
public void setProductList(List<Product> productList, Context context, SellerInventoryListEpoxyController.Callbacks callbacks) {
this.productList = productList;
this.context = context;
this.callbacks = callbacks;
requestModelBuild();
}
#Override
protected void buildModels() {
for (int i = 0; i < productList.size(); i++) {
new InventoryProductDetailModel_()
.id(productList.get(i).getId())
.product(productList.get(i))
.position(i)
.listSize(productList.size())
.callbacks(callbacks)
.context(context)
.addTo(this);
}
}
public interface Callbacks {
void onViewComboClick(Product productComboList);
void onProductListingStatusChanged(Boolean newStatus, int productSellerId);
void onRecyclerViewReachEnd();
}
}
public class InventoryProductDetailModel extends EpoxyModelWithHolder<InventoryProductDetailModel.ViewHolder> implements CompoundButton.OnCheckedChangeListener {
#EpoxyAttribute
Product product;
#EpoxyAttribute
int position;
#EpoxyAttribute
int listSize;
#EpoxyAttribute
Context context;
#EpoxyAttribute(EpoxyAttribute.Option.DoNotHash)
SellerInventoryListEpoxyController.Callbacks callbacks;
#Override
protected ViewHolder createNewHolder() {
return new ViewHolder();
}
#Override
protected int getDefaultLayout() {
return R.layout.inventroy_item_layout;
}
private DrawableCrossFadeFactory factory =
new DrawableCrossFadeFactory.Builder().setCrossFadeEnabled(true).build();
#Override
public void bind(#NonNull InventoryProductDetailModel.ViewHolder holder) {
super.bind(holder);
holder.quantity.setText(String.format("Available :%d", product.getTotalStock()));
holder.brand.setText(product.getProduct().getBrandName());
holder.title.setText(product.getProduct().getTitle());
holder.category.setText(product.getProduct().getCategoryName());
holder.sku.setText(String.format("Sku: %s", product.getSku()));
holder.inventoryItemConstrainLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, ProductDetailActivity.class);
intent.putExtra("product_id", product.getId());
context.startActivity(intent);
}
});
if (product.getProductCombos() != null && product.getProductCombos().size() > 0) {
holder.variationCount.setVisibility(View.GONE);
holder.comboBtn.setVisibility(View.VISIBLE);
holder.comboBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
callbacks.onViewComboClick(product);
}
});
}
if (product.getSellerActive()) {
holder.productStatusSwitch.setText("Active");
holder.productStatusSwitch.setOnCheckedChangeListener(null);
holder.productStatusSwitch.setChecked(true);
holder.productStatusSwitch.setOnCheckedChangeListener(this);
holder.productStatusSwitch.setTextColor(context.getResources().getColor(R.color.colorAccent));
} else {
holder.productStatusSwitch.setText("Inactive");
holder.productStatusSwitch.setOnCheckedChangeListener(null);
holder.productStatusSwitch.setChecked(false);
holder.productStatusSwitch.setOnCheckedChangeListener(this);
holder.productStatusSwitch.setTextColor(Color.parseColor("#ff0000"));
}
holder.variationCount.setText(format("Variation(%d)", product.getVariantCount()));
holder.variationCount.setVisibility(View.VISIBLE);
holder.comboBtn.setVisibility(View.GONE);
loadImage(holder.productImage, Utils.getRequiredUrlForThisImage(holder.productImage, product.getProduct().getImage()));
if (position == listSize - 2) {
callbacks.onRecyclerViewReachEnd();
}
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
callbacks.onProductListingStatusChanged(isChecked, product.getId());
}
private void loadImage(ImageView imageView, String url) {
Glide.with(imageView.getContext()).asBitmap()
.load(Utils.getRequiredUrlForThisImage(imageView, url))
.apply(new RequestOptions().diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
.fitCenter())
.transition(withCrossFade(factory))
.placeholder(R.mipmap.product)
.into(imageView);
}
#Override
public void unbind(#NonNull InventoryProductDetailModel.ViewHolder holder) {
super.unbind(holder);
}
public static class ViewHolder extends EpoxyHolder {
TextView quantity, brand, title, category, variationCount, comboBtn;
ImageView productImage, btn_product_detail;
ProgressBar progressBar;
ConstraintLayout inventoryItemConstrainLayout;
private TextView sku;
private Switch productStatusSwitch;
#Override
protected void bindView(#NonNull View itemView) {
productStatusSwitch = itemView.findViewById(R.id.productStatusSwitch);
quantity = itemView.findViewById(R.id.product_qty);
brand = itemView.findViewById(R.id.product_brand);
title = itemView.findViewById(R.id.product_title);
sku = itemView.findViewById(R.id.sku);
category = itemView.findViewById(R.id.product_category);
variationCount = itemView.findViewById(R.id.variantCount);
productImage = itemView.findViewById(R.id.product_image);
btn_product_detail = itemView.findViewById(R.id.btn_product_detail);
inventoryItemConstrainLayout = itemView.findViewById(R.id.inventory_item_constrain_layout);
comboBtn = itemView.findViewById(R.id.combo_btn);
progressBar = itemView.findViewById(R.id.progressbar);
progressBar.setVisibility(View.GONE);
}
}
#Override
public int hashCode() {
super.hashCode();
return product.hashCode();
}
#Override
public boolean equals(Object o) {
return super.equals(o);
}
}
private void addProductListingChangeObserver(final Boolean newStatus, final int productSellerId) {
ProductUpdate productUpdate = new ProductUpdate();
productUpdate.setSellerActive(newStatus);
mInventoryViewModel.updateProductSeller(productSellerId, productUpdate).observe(this, new Observer<Resource<ProductSeller>>() {
#Override
public void onChanged(Resource<ProductSeller> productSellerResource) {
if (productSellerResource.status == Status.ERROR) {
progressBar.setVisibility(View.GONE);
} else if (productSellerResource.status == Status.SUCCESS) {
progressBar.setVisibility(View.GONE);
if (productSellerResource.data != null && productSellerResource.data.isSellerActive() == newStatus) {
for (int i = 0; i < productList.size(); i++) {
if (productList.get(i).getId() == productSellerId) {
productList.get(i).setSellerActive(newStatus);
break;
}
}
sellerInventoryListEpoxyController.setProductList(productList, getContext(), InventoryFragment.this);
}
} else {
progressBar.setVisibility(View.VISIBLE);
}
}
});
}
In addProductListingChangeObserver() function one object of productList is modified and new productList is passed to the EpoxyController and requestModelbuild is called but the view is not modifying as expected.

Android AutoCompeleteTextView not gives proper result

I am new in android and use Custom AutoCompleteTextView, here is code form AutoCompleteText
<com.xxxxxxxx.supports.CustomAutoComplete
android:id="#+id/edit_search"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#android:color/transparent"
android:completionThreshold="3"
android:ellipsize="end"
android:fontFamily="#font/roboto"
android:gravity="center_vertical"
android:hint="#string/search_products_colors_more"
android:imeActionId="123456"
android:imeOptions="actionSearch"
android:inputType="textCapWords"
android:paddingLeft="10dp"
android:textColor="#color/dark_text_color"
android:textColorHint="#color/light_text_color"
android:textSize="#dimen/font_14sp" />
This is list comes when I search some thing over server
and When I clicked on first item Steel Grey It shows like this.
I am not able to figure out the error, Sometime it comes and sometime not.
Please help.
Edit Update:
public class CustomAutoComplete extends android.support.v7.widget.AppCompatAutoCompleteTextView {
private static final int MESSAGE_TEXT_CHANGED = 100;
private static final int DEFAULT_AUTOCOMPLETE_DELAY = 750;
private int mAutoCompleteDelay = DEFAULT_AUTOCOMPLETE_DELAY;
private ProgressBar mLoadingIndicator;
#SuppressLint("HandlerLeak")
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
CustomAutoComplete.super.performFiltering((CharSequence) msg.obj, msg.arg1);
}
};
public CustomAutoComplete(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setLoadingIndicator(ProgressBar progressBar) {
mLoadingIndicator = progressBar;
}
public void setAutoCompleteDelay(int autoCompleteDelay) {
mAutoCompleteDelay = autoCompleteDelay;
}
#Override
protected void performFiltering(CharSequence text, int keyCode) {
if (mLoadingIndicator != null) {
mLoadingIndicator.setVisibility(View.VISIBLE);
}
mHandler.removeMessages(MESSAGE_TEXT_CHANGED);
mHandler.sendMessageDelayed(mHandler.obtainMessage(MESSAGE_TEXT_CHANGED, text), mAutoCompleteDelay);
}
#Override
public void onFilterComplete(int count) {
if (mLoadingIndicator != null) {
mLoadingIndicator.setVisibility(View.GONE);
}
super.onFilterComplete(count);
}
}
Model Class below here
public class SearchResults {
private String suggetions, suggetionId;
public SearchResults(String suggetions, String suggetionId) {
this.suggetions = suggetions;
this.suggetionId = suggetionId;
}
public String getSuggetions() {
return suggetions;
}
public String getSuggetionId() {
return suggetionId;
}
public void setSuggetionId(String suggetionId) {
this.suggetionId = suggetionId;
}}
Code in fragment class
public CustomAutoComplete edit_search;
edit_search.setThreshold(3);
edit_search.setAdapter(new SearchAdapter(getActivity(), resultList, SearchItems.this)); // 'this' is Activity instance
edit_search.setLoadingIndicator(progress_search);
edit_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
try {
getPerspective().closeKeyboard();
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
if (resultList.size() != 0) {
if (edit_search.getText().length() > 2) {
String text = resultList.get(0).getSuggetions();
Log.e(TAG, "Text : " + text);
if (text.equalsIgnoreCase("No Results!")) {
edit_search.dismissDropDown();
layout_no_result.setVisibility(View.VISIBLE);
layout_mic.setVisibility(View.GONE);
} else {
layout_no_result.setVisibility(View.GONE);
layout_mic.setVisibility(View.VISIBLE);
getPerspective().openProdcuctList("0", text.trim());
}
} else if (edit_search.getText().length() < 3 && edit_search.getText().length() > 0) {
getPerspective().showMessage("Enter minimum three characters!");
} else if (edit_search.getText().length() <= 0) {
getPerspective().showMessage("Please enter your search query!");
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
});
edit_search.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (edit_search.getText().length() == 0) {
layout_no_result.setVisibility(View.GONE);
layout_mic.setVisibility(View.VISIBLE);
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
Now Adapter class code is
public class SearchAdapter extends BaseAdapter implements Filterable {
public Context context;
private List<SearchResults> resultsList;
SearchItems searchItems;
Perspective perspective;
private LayoutInflater inflater;
public Perspective getPerspective() {
if (perspective == null)
perspective = (Perspective) context;
return perspective;
}
public SearchAdapter(Context context, List<SearchResults> resultsList, SearchItems searchItems) {
this.context = context;
this.resultsList = resultsList;
this.searchItems = searchItems;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return resultsList.size();
}
#Override
public Object getItem(int position) {
return resultsList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = inflater.inflate(R.layout.custom_search_result_row, parent, false);
viewHolder.txt_item_name = (TextView) convertView.findViewById(R.id.txt_item_name);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.txt_item_name.setText(resultsList.get(position).getSuggetions());
viewHolder.txt_item_name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String query = resultsList.get(position).getSuggetions();
Log.e("Search","Query : "+query);
// searchItems.edit_search.setText(query);
if (!query.equals("No Results!")) {
getPerspective().closeKeyboard();
searchItems.edit_search.dismissDropDown();
getPerspective().openProdcuctList("0", query);
}
}
});
return convertView;
}
class ViewHolder {
TextView txt_item_name;
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if (constraint != null) {
List<SearchResults> listSuggs = findSuggastions(context, constraint.toString());
filterResults.values = listSuggs;
filterResults.count = listSuggs.size();
}
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.count > 0) {
resultsList = (List<SearchResults>) results.values;
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
};
}
private List<SearchResults> findSuggastions(Context context, String title) {
resultsList.clear();
return resultsList = getSearchResults(title);
}
private List<SearchResults> getSearchResults(final String keyword) {
String tag_string_req = "req_top_search";
StringRequest strReq = new StringRequest(Request.Method.POST,
APIs.url_api_url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
Log.e("SearchAdapter", "Response : " + response);
JSONArray object = new JSONArray(response);
//resultsList.clear();
for (int i = 0; i < object.length(); i++) {
JSONObject jsonObject = object.getJSONObject(i);
String prod_id = jsonObject.getString("product_id");
String prod_nam = jsonObject.getString("name");
SearchResults searchSuggs = new SearchResults(prod_nam, prod_id);
resultsList.add(searchSuggs);
}
if (resultsList.size() == 1) {
String prod_nam = resultsList.get(0).getSuggetions();
if (prod_nam.equalsIgnoreCase("No Results!")) {
searchItems.edit_search.dismissDropDown();
searchItems.layout_no_result.setVisibility(View.VISIBLE);
searchItems.layout_mic.setVisibility(View.GONE);
} else {
searchItems.layout_no_result.setVisibility(View.GONE);
searchItems.layout_mic.setVisibility(View.VISIBLE);
}
}else {
getPerspective().closeKeyboard();
}
notifyDataSetChanged();
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("keyword", keyword);
return params;
}
};
strReq.setRetryPolicy(new RetryPolicy() {
#Override
public void retry(VolleyError arg0) throws VolleyError {
}
#Override
public int getCurrentTimeout() {
return 0;
}
#Override
public int getCurrentRetryCount() {
return 0;
}
});
strReq.setShouldCache(false);
Controller.getInstance().addToRequestQueue(strReq, tag_string_req);
return resultsList;
}
}
I have updated code,
Just Override toString methods and return data that you want to display.
public class SearchResults {
private String suggetions, suggetionId;
public SearchResults(String suggetions, String suggetionId) {
this.suggetions = suggetions;
this.suggetionId = suggetionId;
}
public String getSuggetions() {
return suggetions;
}
public String getSuggetionId() {
return suggetionId;
}
public void setSuggetionId(String suggetionId) {
this.suggetionId = suggetionId;
}
#Override
public final String toString()
{
return suggetions;
}
}

recycle view not showing

I'm not able to see the recycle view, not sure where It has gone wrong. It would be great if you can help me.
Fragment
public class CallDurationFragment extends Fragment {
final FirebaseDatabase database = FirebaseDatabase.getInstance();
ArrayList<CallHistroy> callList = new ArrayList<>();
ArrayList<CallHistroy> callListTemp = new ArrayList<>();
ArrayList<CallHistroy> callObject = new ArrayList<>();
ArrayList<CallHistroy> callListText = new ArrayList<>();
private CallDurationFragment.OnFragmentInteractionListener mListener;
private RecyclerView rvCall;
private RecyclerView.Adapter callAdaptor;
private RecyclerView.LayoutManager eLayoutManager;
private EditText phoneNumber;
private static final int DIALOG_DATE_PICKER = 100;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_callduration_list, container, false);
phoneNumber = (EditText) getActivity().findViewById(editTextSearchKeyPhoneNo);
Context context = getActivity();
rvCall = (RecyclerView) rootView.findViewById(R.id.rvCallDuration);
rvCall.setHasFixedSize(true);
rvCall.setLayoutManager(eLayoutManager);
eLayoutManager = new LinearLayoutManager(getActivity());
phoneNumber.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
callListTemp = getAllCallRecords();
for(int i = 0 ; i < callListTemp.size() ; i++)
if(callListTemp.get(i).getPhoneNumber().contains(s.toString()) )
callListText.add(callListTemp.get(i));
callList = calculateIncomingOutgoing();
callAdaptor = new CallDurationAdapter(getActivity(), callList);
rvCall.setAdapter(callAdaptor);
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
}
});
callList = calculateIncomingOutgoing();
callAdaptor = new CallDurationAdapter(getActivity(), callList);
rvCall.setAdapter(callAdaptor);
return rootView;
}
public ArrayList<CallHistroy> getAllCallRecords(){
DatabaseReference ref = database.getReference();
ref.child("Call").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
callObject.clear();
HashMap<String,Object> call = null;
Iterator<DataSnapshot> items = dataSnapshot.getChildren().iterator();
while(items.hasNext()){
DataSnapshot item = items.next();
Log.e("Listener",item.toString() );
call =(HashMap<String, Object>) item.getValue();
callObject.add(new CallHistroy(call.get("phoneNumber").toString(),call.get("mode").toString(),call.get("duration").toString(), call.get("date").toString(),item.getKey()));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return callObject;
}
public ArrayList<CallHistroy> calculateIncomingOutgoing(){
if(callListText.size() > 0){
callList = callListText;
}else {
callList = getAllCallRecords();
}
ArrayList<CallHistroy> callHistroyIncomingOutgoing = new ArrayList<>();
if(callList.size() > 0){
if(callList.get(0).getMode().equals("Outgoing")) {
callHistroyIncomingOutgoing.add(new CallHistroy(callList.get(0).getPhoneNumber(), "0", callList.get(0).getDuration()));
}else{
callHistroyIncomingOutgoing.add(new CallHistroy(callList.get(0).getPhoneNumber(), callList.get(0).getDuration(), "0"));
}
}
for( int i = 1 ; i < callList.size() ; i++){
boolean setValue = false;
for (int j = 0; j < callHistroyIncomingOutgoing.size() ;j++){
if( callHistroyIncomingOutgoing.get(j).getPhoneNumber().equals(callList.get(i).getPhoneNumber())){
setValue = true;
int incoming = Integer.parseInt(callHistroyIncomingOutgoing.get(j).getIncomingDuration());
int outgoing = Integer.parseInt( callHistroyIncomingOutgoing.get(j).getOutgoingDuration());
int duration = Integer.parseInt( callList.get(i).getDuration());
if(callList.get(i).getMode().equals("Outgoing")) {
callHistroyIncomingOutgoing.get(j).updateDuration(String.valueOf(incoming), String.valueOf(outgoing + duration));
}else{
callHistroyIncomingOutgoing.get(j).updateDuration(String.valueOf(incoming + duration), String.valueOf(outgoing));
}
}
}
if(!setValue) {
if(callList.get(i).getMode() == "Outgoing") {
callHistroyIncomingOutgoing.add(new CallHistroy(callList.get(i).getPhoneNumber(), "0", callList.get(i).getDuration()));
}else{
callHistroyIncomingOutgoing.add(new CallHistroy(callList.get(i).getPhoneNumber(), callList.get(i).getDuration(), "0"));
}
}
}
return callHistroyIncomingOutgoing;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof CallListFragment.OnFragmentInteractionListener) {
mListener = (CallDurationFragment.OnFragmentInteractionListener) context;
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void onPause(){
super.onPause();
}
#Override
public void onDestroyView(){
super.onDestroyView();
}
#Override
public void onDestroy(){
super.onDestroy();
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
Adaptor
RecyclerView.Adapter<CallDurationAdapter.ViewHolder> {
private List<CallHistroy> mCalls;
private Context mContext;
public CallDurationAdapter(Context context, List<CallHistroy> calls) {
mCalls = calls;
mContext = context;
}
private Context getContext() {
return mContext;
}
#Override
public CallDurationAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
// Inflate the custom layout
View callDurationView = inflater.inflate(R.layout.item_call_duration_details, parent, false);
// Return a new holder instance
ViewHolder viewHolder = new ViewHolder(callDurationView);
return viewHolder;
}
#Override
public void onBindViewHolder(CallDurationAdapter.ViewHolder viewHolder, final int position) {
// Get the data model based on position
final CallHistroy ch = mCalls.get(position);
// Set item views based on your views and data model
viewHolder._phoneNoTextView.setText(ch.getPhoneNumber());
viewHolder._incomingTextView.setText(ch.getIncomingDuration());
viewHolder._outgoingTextView.setText(ch.getOutgoingDuration());
final String key = ch.getKey();
}
#Override
public int getItemCount() {
return mCalls.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView _phoneNoTextView;
public TextView _incomingTextView;
public TextView _outgoingTextView;
public ViewHolder(View itemView) {
super(itemView);
_phoneNoTextView = (TextView) itemView.findViewById(R.id.rvs_duration_phone_no);
_incomingTextView = (TextView) itemView.findViewById(R.id.rvs_duration_outing_total_call);
_outgoingTextView = (TextView) itemView.findViewById(R.id.rvs_duration_incoming_total_call);
}
}
}
Activity
public class CallDurationActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_call_duration);
CallDurationFragment newFragment = new CallDurationFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.recordFragmentContainer, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
public void refreshCallDuration(View v) {
Intent intent = new Intent(this, CallDurationActivity.class);
startActivity(intent);
}
protected void onPause() {
super.onPause();
}
protected void onStop() {
super.onStop();
}
protected void onDestroy() {
super.onDestroy();
}
public void onBackCallDuration(View v) {
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
}
Object
public class CallHistroy implements Comparable<CallHistroy> {
String phoneNumber;
String mode;
String duration;
String date;
String key;
String incomingDuration;
String outgoingDuration;
int totalIncoming;
int totalOutgoing;
public CallHistroy(String _phontNumber, String _incomingDuration, String _outgoingDuration ){
setPhoneNumber( _phontNumber );
setIncomingDuration( _incomingDuration );
setOutgoingDuration( _outgoingDuration );
}
public CallHistroy(String _date, int _totalIncoming, int _totalOutgoing ){
setDate(_date);
setTotalIncoming( _totalIncoming );
setTotalOutgoing( _totalOutgoing );
}
public void updateCall(int _totalIncoming, int _totalOutgoing){
setTotalIncoming( _totalIncoming );
setTotalOutgoing( _totalOutgoing );
}
public void updateDuration(String _incomingDuration, String _outgoingDuration){
setOutgoingDuration( _incomingDuration );
setIncomingDuration( _outgoingDuration );
}
public CallHistroy(String _phoneNumber, String _mode, String _duration, String _date ){
setPhoneNumber( _phoneNumber );
setDuration( _duration );
setDate( _date );
setMode( _mode );
}
public CallHistroy(String _phoneNumber, String _mode, String _duration, String _date, String _key ){
setPhoneNumber( _phoneNumber );
setDuration( _duration );
setDate( _date );
setMode( _mode );
setKey( _key );
}
public String getIncomingDuration() {
return incomingDuration;
}
public String getOutgoingDuration() {
return outgoingDuration;
}
public int getTotalIncoming() {
return totalIncoming;
}
public int getTotalOutgoing() {
return totalOutgoing;
}
public void setIncomingDuration(String incomingDuration) {
this.incomingDuration = incomingDuration;
}
public void setOutgoingDuration(String outgoingDuration) {
this.outgoingDuration = outgoingDuration;
}
public void setTotalIncoming(int totalIncoming) {
this.totalIncoming = totalIncoming;
}
public void setTotalOutgoing(int totalOutgoing) {
this.totalOutgoing = totalOutgoing;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getPhoneNumber() {
return phoneNumber;
}
public String getDate() {
return date;
}
public String getMode() {
return mode;
}
public String getDuration() {
return duration;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public void setDate(String date) {
this.date = date;
}
public void setDuration(String duration) {
this.duration = duration;
}
public void setMode(String mode) {
this.mode = mode;
}
#Override
public int compareTo(#NonNull CallHistroy callHistroyObject) {
String[] part = callHistroyObject.date.split("/");
String[] part1 = date.split("/");
int date = Integer.parseInt(part[0]);
int month = Integer.parseInt(part[1]);
String _year = part[2];
int year = Integer.parseInt(_year.substring(0,4));
int date1 = Integer.parseInt(part1[0]);
int month1 = Integer.parseInt(part1[1]);
String _year1 = part1[2];
int year1 = Integer.parseInt(_year1.substring(0,4));
if(year > year1)
return -1;
else if(month > month1)
return -1;
else if(date >date1)
return -1;
else
return 0;
}
}
You're setting your layout manager before it's created
rvCall.setLayoutManager(eLayoutManager);
eLayoutManager = new LinearLayoutManager(getActivity());
should be
eLayoutManager = new LinearLayoutManager(getActivity());
rvCall.setLayoutManager(eLayoutManager);

AlerDialog call from other class

I'm trying to call my alertdialog from another class in same file. Where do i have wrong here? Just trying to extends the AlertDialog, but i'm not sure how to do this, i don't want to be in my public main class, trying that and work but i need to be in separable class if this is possible.
class MyDialog extends AlertDialog {
public static Context context;
public static int theme;
protected MyDialog(Context context, int theme) {
super(context, theme);
MyDialog.context = context;
theme = THEME_HOLO_DARK;
MyDialog.theme = theme;
}
public void onCreateAlertDialog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("Auto Start")
.setMessage("Start playing after: 30 sec")
.setIcon(R.drawable.info)
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(context, "Auto start cancaled!", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
}
);
alertDialog.show();
}
}
I call it from main class like this:
Context context = MyDialog.context;
int i = MyDialog.theme;
MyDialog md = new MyDialog(context, i);
md.onCreateAlertDialog();
I think that it comes from the context variable that you didn't initialize it.
You should get it from the activity your are calling the dialog from :
class MyActivity extends Activity{
...
Context context = this;
MyDialog md = new MyDialog(context, i);
...
}
You are using AlertDialog.Builder which will always return an instance of the AlertDialog class when you build it. You would have to override the static builder to return an instance of your class but this is not really possible.
What you want to do is extend the Dialog class and create your own AlertDialog implementation as demonstrated in the HoloEverywhere library.
https://github.com/ChristopheVersieux/HoloEverywhere/blob/master/library/src/com/WazaBe/HoloEverywhere/app/AlertDialog.java
public class AlertDialog extends Dialog implements DialogInterface {
public static class Builder {
private final AlertController.AlertParams P;
public Builder(Context context) {
this(context, resolveDialogTheme(context, 0));
}
public Builder(Context context, int theme) {
P = new AlertController.AlertParams(new ContextThemeWrapper(
context, resolveDialogTheme(context, theme)));
P.mTheme = theme;
}
public AlertDialog create() {
final AlertDialog dialog = new AlertDialog(P.mContext, P.mTheme);
P.apply(dialog.mAlert);
dialog.setCancelable(P.mCancelable);
if (P.mCancelable) {
dialog.setCanceledOnTouchOutside(true);
}
dialog.setOnCancelListener(P.mOnCancelListener);
if (P.mOnKeyListener != null) {
dialog.setOnKeyListener(P.mOnKeyListener);
}
return dialog;
}
public Context getContext() {
return P.mContext;
}
public Builder setAdapter(final ListAdapter adapter,
final OnClickListener listener) {
P.mAdapter = adapter;
P.mOnClickListener = listener;
return this;
}
public Builder setCancelable(boolean cancelable) {
P.mCancelable = cancelable;
return this;
}
public Builder setCheckedItem(int checkedItem) {
P.mCheckedItem = checkedItem;
return this;
}
public Builder setCursor(final Cursor cursor,
final OnClickListener listener, String labelColumn) {
P.mCursor = cursor;
P.mLabelColumn = labelColumn;
P.mOnClickListener = listener;
return this;
}
public Builder setCustomTitle(View customTitleView) {
P.mCustomTitleView = customTitleView;
return this;
}
public Builder setIcon(Drawable icon) {
P.mIcon = icon;
return this;
}
public Builder setIcon(int iconId) {
P.mIconId = iconId;
return this;
}
public Builder setIconAttribute(int attrId) {
TypedValue out = new TypedValue();
P.mContext.getTheme().resolveAttribute(attrId, out, true);
P.mIconId = out.resourceId;
return this;
}
public Builder setInverseBackgroundForced(boolean useInverseBackground) {
P.mForceInverseBackground = useInverseBackground;
return this;
}
public Builder setItems(CharSequence[] items,
final OnClickListener listener) {
P.mItems = items;
P.mOnClickListener = listener;
return this;
}
public Builder setItems(int itemsId, final OnClickListener listener) {
P.mItems = P.mContext.getResources().getTextArray(itemsId);
P.mOnClickListener = listener;
return this;
}
public Builder setMessage(CharSequence message) {
P.mMessage = message;
return this;
}
public Builder setMessage(int messageId) {
P.mMessage = P.mContext.getText(messageId);
return this;
}
public Builder setMultiChoiceItems(CharSequence[] items,
boolean[] checkedItems,
final OnMultiChoiceClickListener listener) {
P.mItems = items;
P.mOnCheckboxClickListener = listener;
P.mCheckedItems = checkedItems;
P.mIsMultiChoice = true;
return this;
}
public Builder setMultiChoiceItems(Cursor cursor,
String isCheckedColumn, String labelColumn,
final OnMultiChoiceClickListener listener) {
P.mCursor = cursor;
P.mOnCheckboxClickListener = listener;
P.mIsCheckedColumn = isCheckedColumn;
P.mLabelColumn = labelColumn;
P.mIsMultiChoice = true;
return this;
}
public Builder setMultiChoiceItems(int itemsId, boolean[] checkedItems,
final OnMultiChoiceClickListener listener) {
P.mItems = P.mContext.getResources().getTextArray(itemsId);
P.mOnCheckboxClickListener = listener;
P.mCheckedItems = checkedItems;
P.mIsMultiChoice = true;
return this;
}
public Builder setNegativeButton(CharSequence text,
final OnClickListener listener) {
P.mNegativeButtonText = text;
P.mNegativeButtonListener = listener;
return this;
}
public Builder setNegativeButton(int textId,
final OnClickListener listener) {
P.mNegativeButtonText = P.mContext.getText(textId);
P.mNegativeButtonListener = listener;
return this;
}
public Builder setNeutralButton(CharSequence text,
final OnClickListener listener) {
P.mNeutralButtonText = text;
P.mNeutralButtonListener = listener;
return this;
}
public Builder setNeutralButton(int textId,
final OnClickListener listener) {
P.mNeutralButtonText = P.mContext.getText(textId);
P.mNeutralButtonListener = listener;
return this;
}
public Builder setOnCancelListener(OnCancelListener onCancelListener) {
P.mOnCancelListener = onCancelListener;
return this;
}
public Builder setOnItemSelectedListener(
final AdapterView.OnItemSelectedListener listener) {
P.mOnItemSelectedListener = listener;
return this;
}
public Builder setOnKeyListener(OnKeyListener onKeyListener) {
P.mOnKeyListener = onKeyListener;
return this;
}
public Builder setOnPrepareListViewListener(
OnPrepareListViewListener listener) {
P.mOnPrepareListViewListener = listener;
return this;
}
public Builder setPositiveButton(CharSequence text,
final OnClickListener listener) {
P.mPositiveButtonText = text;
P.mPositiveButtonListener = listener;
return this;
}
public Builder setPositiveButton(int textId,
final OnClickListener listener) {
P.mPositiveButtonText = P.mContext.getText(textId);
P.mPositiveButtonListener = listener;
return this;
}
public Builder setRecycleOnMeasureEnabled(boolean enabled) {
P.mRecycleOnMeasure = enabled;
return this;
}
public Builder setSingleChoiceItems(CharSequence[] items,
int checkedItem, final OnClickListener listener) {
P.mItems = items;
P.mOnClickListener = listener;
P.mCheckedItem = checkedItem;
P.mIsSingleChoice = true;
return this;
}
public Builder setSingleChoiceItems(Cursor cursor, int checkedItem,
String labelColumn, final OnClickListener listener) {
P.mCursor = cursor;
P.mOnClickListener = listener;
P.mCheckedItem = checkedItem;
P.mLabelColumn = labelColumn;
P.mIsSingleChoice = true;
return this;
}
public Builder setSingleChoiceItems(int itemsId, int checkedItem,
final OnClickListener listener) {
P.mItems = P.mContext.getResources().getTextArray(itemsId);
P.mOnClickListener = listener;
P.mCheckedItem = checkedItem;
P.mIsSingleChoice = true;
return this;
}
public Builder setSingleChoiceItems(ListAdapter adapter,
int checkedItem, final OnClickListener listener) {
P.mAdapter = adapter;
P.mOnClickListener = listener;
P.mCheckedItem = checkedItem;
P.mIsSingleChoice = true;
return this;
}
public Builder setTitle(CharSequence title) {
P.mTitle = title;
return this;
}
public Builder setTitle(int titleId) {
P.mTitle = P.mContext.getText(titleId);
return this;
}
public Builder setView(View view) {
P.mView = view;
P.mViewSpacingSpecified = false;
return this;
}
public Builder setView(View view, int viewSpacingLeft,
int viewSpacingTop, int viewSpacingRight, int viewSpacingBottom) {
P.mView = view;
P.mViewSpacingSpecified = true;
P.mViewSpacingLeft = viewSpacingLeft;
P.mViewSpacingTop = viewSpacingTop;
P.mViewSpacingRight = viewSpacingRight;
P.mViewSpacingBottom = viewSpacingBottom;
return this;
}
public AlertDialog show() {
AlertDialog dialog = create();
dialog.show();
return dialog;
}
}
public static final int THEME_HOLO_DARK = 1;
public static final int THEME_HOLO_LIGHT = 2;
static int resolveDialogTheme(Context context, int resid) {
if (resid == THEME_HOLO_DARK) {
return R.style.Holo_Theme_Dialog_Alert;
} else if (resid == THEME_HOLO_LIGHT) {
return R.style.Holo_Theme_Dialog_Alert_Light;
} else if (resid >= 0x01000000) {
return resid;
} else {
TypedValue outValue = new TypedValue();
context.getTheme().resolveAttribute(R.attr.alertDialogTheme,
outValue, true);
return outValue.resourceId;
}
}
private final AlertController mAlert;
protected AlertDialog(Context context) {
this(context, false, null, resolveDialogTheme(context, 0));
}
protected AlertDialog(Context context, boolean cancelable,
OnCancelListener cancelListener) {
this(context, cancelable, cancelListener,
resolveDialogTheme(context, 0));
}
protected AlertDialog(Context context, boolean cancelable,
OnCancelListener cancelListener, int theme) {
super(context, resolveDialogTheme(context, theme));
setCancelable(cancelable);
setOnCancelListener(cancelListener);
mAlert = new AlertController(context, this, getWindow());
}
protected AlertDialog(Context context, int theme) {
this(context, false, null, theme);
}
public Button getButton(int whichButton) {
return mAlert.getButton(whichButton);
}
public ListView getListView() {
return mAlert.getListView();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAlert.installContent();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (mAlert.onKeyDown(keyCode, event)) {
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (mAlert.onKeyUp(keyCode, event)) {
return true;
}
return super.onKeyUp(keyCode, event);
}
#Deprecated
public void setButton(CharSequence text, Message msg) {
setButton(BUTTON_POSITIVE, text, msg);
}
#Deprecated
public void setButton(CharSequence text, final OnClickListener listener) {
setButton(BUTTON_POSITIVE, text, listener);
}
public void setButton(int whichButton, CharSequence text, Message msg) {
mAlert.setButton(whichButton, text, null, msg);
}
public void setButton(int whichButton, CharSequence text,
OnClickListener listener) {
mAlert.setButton(whichButton, text, listener, null);
}
#Deprecated
public void setButton2(CharSequence text, Message msg) {
setButton(BUTTON_NEGATIVE, text, msg);
}
#Deprecated
public void setButton2(CharSequence text, final OnClickListener listener) {
setButton(BUTTON_NEGATIVE, text, listener);
}
#Deprecated
public void setButton3(CharSequence text, Message msg) {
setButton(BUTTON_NEUTRAL, text, msg);
}
#Deprecated
public void setButton3(CharSequence text, final OnClickListener listener) {
setButton(BUTTON_NEUTRAL, text, listener);
}
public void setCustomTitle(View customTitleView) {
mAlert.setCustomTitle(customTitleView);
}
public void setIcon(Drawable icon) {
mAlert.setIcon(icon);
}
public void setIcon(int resId) {
mAlert.setIcon(resId);
}
public void setIconAttribute(int attrId) {
TypedValue out = new TypedValue();
getContext().getTheme().resolveAttribute(attrId, out, true);
mAlert.setIcon(out.resourceId);
}
public void setInverseBackgroundForced(boolean forceInverseBackground) {
mAlert.setInverseBackgroundForced(forceInverseBackground);
}
public void setMessage(CharSequence message) {
mAlert.setMessage(message);
}
#Override
public void setTitle(CharSequence title) {
super.setTitle(title);
mAlert.setTitle(title);
}
public void setView(View view) {
mAlert.setView(view);
}
public void setView(View view, int viewSpacingLeft, int viewSpacingTop,
int viewSpacingRight, int viewSpacingBottom) {
mAlert.setView(view, viewSpacingLeft, viewSpacingTop, viewSpacingRight,
viewSpacingBottom);
}
}

Categories

Resources