I am trying to sort the list of custom objects and display in Recyclerview. After displaying the items in recyclerview. I am sorting the list in the Activity and calling adapter.notifyDataSetChanged() but its not working.
Code in MainActivity.java:
Collections.sort(beerDataList, new Comparator<BeerData>() {
#Override
public int compare(BeerData o1, BeerData o2) {
return o1.getAbv().compareToIgnoreCase(o2.getAbv());
}
});
adapter.notifyDataSetChanged();
Adapter code:
public class BeerListAdapter extends RecyclerView.Adapter<BeerListAdapter.MyViewHolder> {
private static ClickListener clickListener;
private Context context;
private LayoutInflater inflater;
private List<BeerData> beerDataList;
private List<BeerData> copyList;
public BeerListAdapter(Context context) {
this.context = context;
inflater = LayoutInflater.from(context);
beerDataList = new ArrayList<>();
copyList = new ArrayList<>();
}
public void setList(List<BeerData> beerDataList) {
if (this.beerDataList.isEmpty()) {
this.beerDataList.addAll(beerDataList);
copyList.addAll(beerDataList);
}
notifyDataSetChanged();
}
public void filter(String query) {
beerDataList.clear();
if (query.isEmpty()) {
beerDataList.addAll(copyList);
} else {
for (BeerData beerData : copyList) {
if (beerData.getName().replaceAll("[\\s]", "").toLowerCase().contains(query.replaceAll("[\\s]", "").toLowerCase())) {
beerDataList.add(beerData);
}
}
}
notifyDataSetChanged();
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.custom_beer_row, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.beerName.setText(beerDataList.get(position).getName());
holder.styleName.setText(beerDataList.get(position).getStyle());
holder.alcoholContent.setText("Alcohol Content: " + beerDataList.get(position).getAbv());
holder.quantity.setText(beerDataList.get(position).getQuantity().toString());
}
#Override
public int getItemCount() {
return beerDataList.size();
}
public void setOnItemClickListener(ClickListener clickListener) {
BeerListAdapter.clickListener = clickListener;
}
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView beerName, alcoholContent, styleName, quantity;
ImageView add, minus;
MyViewHolder(View itemView) {
super(itemView);
beerName = itemView.findViewById(R.id.beerName);
alcoholContent = itemView.findViewById(R.id.alcoholContent);
styleName = itemView.findViewById(R.id.beerStyle);
quantity = itemView.findViewById(R.id.quantity);
add = itemView.findViewById(R.id.add);
minus = itemView.findViewById(R.id.minus);
add.setOnClickListener(this);
minus.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.add:
clickListener.onAddClick(getAdapterPosition(), v);
break;
case R.id.minus:
clickListener.onMinusClick(getAdapterPosition(), v);
break;
}
}
}
public interface ClickListener {
void onAddClick(int position, View v);
void onMinusClick(int position, View v);
}
}
Here is my MainActivity:
public class MainActivity extends AppCompatActivity implements SearchView.OnQueryTextListener, LoginResultCallBack {
private static final String TAG = MainActivity.class.getSimpleName();
#Inject
MyApplication application;
LoginViewModel loginViewModel;
#BindView(R.id.beerListRecyclerView)
RecyclerView recyclerView;
#BindView(R.id.progressBar)
ProgressBar progressBar;
private BeerListAdapter adapter;
private List<BeerData> beerDataList;
private Menu menu;
private String sortType = "unsorted";
private Disposable networkDisposable;
List<BeerData> originalList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
((MyApplication) getApplication()).getComponent().inject(this);
loginViewModel = ViewModelProviders.of(this,new LoginViewModelFactory(application,this)).get(LoginViewModel.class);
adapter = new BeerListAdapter(this);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
recyclerView.setAdapter(adapter);
adapter.setOnItemClickListener(new BeerListAdapter.ClickListener() {
#Override
public void onAddClick(int position, View v) {
addItem(position);
}
#Override
public void onMinusClick(int position, View v) {
removeItem(position);
}
});
}
public void fetchData() {
progressBar.setVisibility(View.VISIBLE);
loginViewModel.fetchData();
loginViewModel.result.observe(this, new Observer<NetworkResponse>() {
#Override
public void onChanged(#Nullable NetworkResponse networkResponse) {
progressBar.setVisibility(View.GONE);
assert networkResponse != null;
if (networkResponse.getPostData() != null) {
beerDataList = new ArrayList<>();
originalList = networkResponse.getPostData();
beerDataList = networkResponse.getPostData();
Log.e(TAG, "Response: " + networkResponse.getPostData().get(0).getAbv());
progressBar.setVisibility(View.GONE);
adapter.setList(networkResponse.getPostData());
} else {
Log.e(TAG, "Response: " + networkResponse.getError().getLocalizedMessage());
progressBar.setVisibility(View.GONE);
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
this.menu = menu;
MenuItem searchItem = menu.findItem(R.id.searchBar);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setQueryHint("Search Beer");
searchView.setOnQueryTextListener(this);
searchView.setIconified(false);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.cart:
Log.e(TAG, "cart clicked");
break;
case R.id.sort:
if (beerDataList != null) {
if (sortType.equalsIgnoreCase("unsorted")) {
Log.e(TAG,beerDataList.size()+" Size");
Collections.sort(beerDataList, new Comparator<BeerData>() {
#Override
public int compare(BeerData o1, BeerData o2) {
return o1.getAbv().compareToIgnoreCase(o2.getAbv());
}
});
adapter.notifyDataSetChanged();
sortType = "ascend";
menu.getItem(2).setTitle(R.string.unsorted);
} else if (sortType.equalsIgnoreCase("ascend")) {
Log.e(TAG,beerDataList.size()+" Size");
Collections.sort(beerDataList, new Comparator<BeerData>() {
#Override
public int compare(BeerData o1, BeerData o2) {
return o2.getAbv().compareToIgnoreCase(o1.getAbv());
}
});
adapter.notifyDataSetChanged();
sortType = "descend";
menu.getItem(2).setTitle(R.string.view_original);
} else {
Log.e(TAG,beerDataList.size()+" Size");
beerDataList.clear();
beerDataList.addAll(originalList);
adapter.notifyDataSetChanged();
sortType = "unsorted";
menu.getItem(2).setTitle(R.string.sort);
}
}
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onQueryTextSubmit(String query) {
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.filter(newText);
return true;
}
#Override
protected void onResume() {
super.onResume();
networkDisposable = ReactiveNetwork.observeNetworkConnectivity(application)
.subscribeOn(Schedulers.io())
.filter(ConnectivityPredicate.hasState(NetworkInfo.State.CONNECTED))
.filter(ConnectivityPredicate.hasType(ConnectivityManager.TYPE_WIFI))
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<Connectivity>() {
#Override
public void accept(final Connectivity connectivity) {
// do something
if (connectivity.isAvailable()) {
fetchData();
} else {
Toast.makeText(MainActivity.this, R.string.internet_issue, Toast.LENGTH_LONG).show();
}
}
});
}
private void addItem(int position) {
int quantity = beerDataList.get(position).getQuantity();
quantity++;
beerDataList.get(position).setQuantity(quantity);
menu.getItem(1).setIcon(ContextCompat.getDrawable(MainActivity.this, R.drawable.ic_cart_full));
adapter.notifyDataSetChanged();
}
private void removeItem(int position) {
if (beerDataList.get(position).getQuantity() > 0) {
int quantity = beerDataList.get(position).getQuantity();
quantity--;
if (quantity == 0)
menu.getItem(1).setIcon(ContextCompat.getDrawable(MainActivity.this, R.drawable.ic_cart_empty));
beerDataList.get(position).setQuantity(quantity);
adapter.notifyDataSetChanged();
}
}
private void safelyDispose(Disposable... disposables) {
for (Disposable subscription : disposables) {
if (subscription != null && !subscription.isDisposed()) {
subscription.dispose();
}
}
}
#Override protected void onPause() {
super.onPause();
safelyDispose(networkDisposable);
}
#Override
public void onSuccess(String message) {
}
#Override
public void onError(String message) {
}
#Override
public void showProgress() {
}
#Override
public void hideProgress() {
}
}
What am I doing wrong here ?
You're not passing the sorted list to your adapter. You're just calling notifyDataSetChanged() which just tells the adapter that there is new data in its class and to use the baerDataList that is currently set within the class to refresh the list. Try this in your main activity.
Collections.sort(beerDataList, new Comparator<BeerData>() {
#Override
public int compare(BeerData o1, BeerData o2) {
return o1.getAbv().compareToIgnoreCase(o2.getAbv());
}
});
adapter.setBeerDataList(beerDataList);
And setBeerDataList() in your adapter class.
private List<BeerData> beerDataList;
public void setBeerDataList(List<BeerData> sortedBeerDataList){
this.beerDataList = sortedBeerDataList;
notifyDataSetChanged();
}
Put sort function in MainActivity to BeerListAdapter:
private void sortBeer() {
Collections.sort(beerDataList, new Comparator<BeerData>() {
#Override
public int compare(BeerData o1, BeerData o2) {
return o1.getAbv().compareToIgnoreCase(o2.getAbv());
}
});
notifyDataSetChanged();
}
then call adapter.sortBeer() when do sort action
Related
Hello friend a lot of search but not working plz help me.
my probem is delete all history from adaptor using on toolbar delete icon how to remove adaptor data
below code first show adaptor and mainactivity
public void removehistory(View view)
button click to remove items from adaptor how to solve this problem sorry for bad english and advance thanks
HistoryAdaptor
public class HistoryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<Object> data;
private GenCallback<HistoryModel> clickListener;
private static final int NATIVE_AD = 1;
private static final int HISTORY_ITEM = 2;
private LayoutInflater inflater;
// private Button removedata;
public HistoryAdapter() {
this.data = new ArrayList<>();
inflater = (LayoutInflater) App.getInstance().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view;
switch (viewType) {
case NATIVE_AD:
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.ad_unified, null, false);
return new NativeAdHolder(view);
case HISTORY_ITEM:
default:
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_history, null, false);
return new ViewHolder(view);
}
// return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_history, null, false));
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
switch (getItemViewType(position)) {
case NATIVE_AD:
((NativeAdHolder) holder).bind((UnifiedNativeAd) data.get(position));
break;
case HISTORY_ITEM:
default:
((ViewHolder) holder).bind((HistoryModel) data.get(position));
break;
}
}
#Override
public int getItemViewType(int position) {
if (data.get(position) instanceof UnifiedNativeAd) {
return NATIVE_AD;
} else {
return HISTORY_ITEM;
}
}
#Override
public int getItemCount() {
return data.size();
}
public void addItem(Object obj, int pos) {
this.data.add(pos, obj);
notifyItemInserted(pos);
}
public void updateData(ArrayList<HistoryModel> list) {
this.data.clear();
this.data.addAll(list);
notifyDataSetChanged();
}
public void clear() {
if (this.data != null && this.data.size() != 0) {
this.data.clear();
notifyDataSetChanged();
}
}
public void setClickListener(GenCallback<HistoryModel> clickListener) {
this.clickListener = clickListener;
}
public void showStarredOnly() {
/*Iterator<Object> iterator = data.iterator();
int pos = 0;
while (iterator.hasNext()) {
if (iterator.next() instanceof HistoryModel) {
HistoryModel historyModel = (HistoryModel) iterator.next();
if (!historyModel.isStarred()) {
iterator.remove();
// notifyItemRemoved(pos);
}
}
pos++;
}
notifyDataSetChanged();*/
}
public class ViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.tvFromLang)
TextView tvFromLang;
#BindView(R.id.tvFromText)
TextView tvFromText;
#BindView(R.id.tvToLang)
TextView tvToLang;
#BindView(R.id.tvToText)
TextView tvToText;
#BindView(R.id.ivStar)
ImageView ivStar;
#BindView(R.id.llMain)
CardView llMain;
#BindView(R.id.tvDate)
TextView tvDate;
public ViewHolder(#NonNull View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
llMain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (clickListener != null) {
clickListener.onCallback((HistoryModel) data.get(getAdapterPosition()));
}
}
});
llMain.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
int pos = getAdapterPosition();
HistoryModel historyModel = (HistoryModel) data.get(pos);
boolean isStar = historyModel.isStarred();
String from = historyModel.getFromLang();
String to = historyModel.getToLang();
Dialogs.INSTANCE.showActionsDialog(llMain.getContext(), isStar, from, to, new HistoryActionCallback() {
#Override
public void onClickCopyFrom() {
Utils.copyText(historyModel.getFromText());
Logger.logFabric(Constants.Events.COPY_FROM);
}
#Override
public void onClickCopyTo() {
Utils.copyText(historyModel.getToText());
Logger.logFabric(Constants.Events.COPY_TO);
}
#Override
public void onClickStar() {
Logger.logFabric(Constants.Events.MARKED_AS_FAV);
historyModel.setStarred(!isStar);
notifyItemChanged(pos);
RoomRepository.getNew().updateHistoryItem(historyModel);
// notifyDataSetChanged();
}
#Override
public void onClickDelete() {
String message = "Are you sure you want to delete?";
Dialogs.INSTANCE.showConfirmationDialog(view.getContext(), message, new View.OnClickListener() {
#Override
public void onClick(View view) {
RoomRepository.getNew().deleteHistoryRecord(historyModel.getTimeStamp());
data.remove(pos);
notifyItemRemoved(pos);
Dialogs.INSTANCE.dismissDialog();
Logger.logFabric(Constants.Events.ITEM_DELETED);
}
});
}
});
return false;
}
});
}
public void bind(HistoryModel item) {
StringBuilder builder = new StringBuilder();
builder.append(item.getFromLang()).append("(").append(item.getFromCode()).append(")");
tvFromLang.setText(builder);
tvFromText.setText(item.getFromText());
builder.setLength(0);
builder.append(item.getToLang()).append("(").append(item.getToCode()).append(")");
tvToLang.setText(builder);
tvToText.setText(item.getToText());
String date = Utils.formatDate(item.getTimeStamp(), "EEE, MMM d, yyyy");
tvDate.setText(date);
ivStar.setVisibility(item.isStarred() ? View.VISIBLE : View.GONE);
}
MainActivity
public class HistoryActivity extends AppCompatActivity {
private HistoryAdapter mAdapter;
private ArrayList<Object> data;
private Activity mCurrentActivity;
private RecyclerView rvHistory;
private Button clearh;
private GenCallback<HistoryModel> clickListener;
private ArrayList<HistoryModel> datamodel = new ArrayList<>();
private ArrayList<String> arrayList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
rvHistory = findViewById(R.id.rvHistory);
ImageView imgb = findViewById(R.id.imgback);
initAdapter();
getAdapter();
imgb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
HistoryActivity.super.onBackPressed();
}
});
}
private void getAdapter() {
RoomRepository.getNew().getAllHistory(mCallback);
}
private void initAdapter() {
mAdapter = new HistoryAdapter();
LinearLayoutManager layoutManager = new LinearLayoutManager(mCurrentActivity);
rvHistory.setLayoutManager(layoutManager);
rvHistory.setAdapter(mAdapter);
}
private IRoomDataHandler mCallback = new RoomDataHandler() {
#Override
public void onGetAllHistory(ArrayList<HistoryModel> list) {
// if (isSafe()) {
mAdapter.updateData(list);
// showLoader(false);
// checkForNoData();
// if (AdUtils.getInstance().getNativeAd() != null) {
//
// }
}
#Override
public void onError(String error) {
// showLoader(false);
// checkForNoData();
}
};
public void removehistory(View view) {
//problem is here
mAdapter.notifyItemRemoved(i);
}
}
call clear() method from on click oh that button like this.
public void removehistory(View view) {
//problem is here
mAdapter.clear()
}
After searching for RecyclerView items in Android, always open first item of RecyclerView When I opened the searched item, it is opening the first item of RecyclerView not the searched one. Even if search and find the items successfuly.
MainActivity.java
public class MainActivityDalil extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private Adapter adapter;
private List<Pets> petsList;
ApiInterface apiInterface;
Adapter.RecyclerViewClickListener listener;
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_dalil);
apiInterface = ApiClient.getApiClient().create(ApiInterface.class);
progressBar = findViewById(R.id.progress);
recyclerView = findViewById(R.id.recyclerView);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
listener = new Adapter.RecyclerViewClickListener() {
#Override
public void onRowClick(View view, final int position) {
Intent intent = new Intent(MainActivityDalil.this, ViewActivity.class);
intent.putExtra("id", petsList.get(position).getId());
intent.putExtra("name", petsList.get(position).getName());
intent.putExtra("species", petsList.get(position).getSpecies());
intent.putExtra("breed", petsList.get(position).getBreed());
intent.putExtra("gender", petsList.get(position).getGender());
intent.putExtra("picture", petsList.get(position).getPicture());
intent.putExtra("birth", petsList.get(position).getBirth());
startActivity(intent);
}
#Override
public void onLoveClick(View view, int position) {
final int id = petsList.get(position).getId();
final Boolean love = petsList.get(position).getLove();
final ImageView mLove = view.findViewById(R.id.love);
if (love){
mLove.setImageResource(R.drawable.likeof);
petsList.get(position).setLove(false);
updateLove("update_love", id, false);
adapter.notifyDataSetChanged();
} else {
mLove.setImageResource(R.drawable.likeon);
petsList.get(position).setLove(true);
updateLove("update_love", id, true);
adapter.notifyDataSetChanged();
}
}
};
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivityDalil.this, EditorActivity.class));
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
final SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
MenuItem searchMenuItem = menu.findItem(R.id.action_search);
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getComponentName())
);
searchView.setQueryHint("Search...");
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(final String query) {
adapter.getFilter().filter(query);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return false;
}
});
searchMenuItem.getIcon().setVisible(false, false);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
// if (id == R.id.action_settings) {
// return true;
// }
return super.onOptionsItemSelected(item);
}
public void getPets(){
Call<List<Pets>> call = apiInterface.getPets();
call.enqueue(new Callback<List<Pets>>() {
#Override
public void onResponse(Call<List<Pets>> call, Response<List<Pets>> response) {
progressBar.setVisibility(View.GONE);
petsList = response.body();
Log.i(MainActivity.class.getSimpleName(), response.body().toString());
adapter = new Adapter(petsList, MainActivityDalil.this, listener);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
#Override
public void onFailure(Call<List<Pets>> call, Throwable t) {
Toast.makeText(MainActivityDalil.this, "rp :"+
t.getMessage().toString(),
Toast.LENGTH_SHORT).show();
}
});
}
public void updateLove(final String key, final int id, final Boolean love){
Call<Pets> call = apiInterface.updateLove(key, id, love);
call.enqueue(new Callback<Pets>() {
#Override
public void onResponse(Call<Pets> call, Response<Pets> response) {
Log.i(MainActivity.class.getSimpleName(), "Response "+response.toString());
String value = response.body().getValue();
String message = response.body().getMassage();
if (value.equals("1")){
Toast.makeText(MainActivityDalil.this, message, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivityDalil.this, message, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<Pets> call, Throwable t) {
Toast.makeText(MainActivityDalil.this, t.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
protected void onResume() {
super.onResume();
getPets();
}
}
Customfilter.java
public class CustomFilter extends Filter {
Adapter adapter;
ArrayList<Pets> filterList;
public CustomFilter(ArrayList<Pets> filterList, Adapter adapter)
{
this.adapter=adapter;
this.filterList=filterList;
}
//FILTERING OCURS
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results=new FilterResults();
//CHECK CONSTRAINT VALIDITY
if(constraint != null && constraint.length() > 0)
{
//CHANGE TO UPPER
constraint=constraint.toString().toUpperCase();
//STORE OUR FILTERED PLAYERS
ArrayList<Pets> filteredPets=new ArrayList<>();
for (int i=0;i<filterList.size();i++)
{
//CHECK
if(filterList.get(i).getName().toUpperCase().contains(constraint))
{
//ADD PLAYER TO FILTERED PLAYERS
filteredPets.add(filterList.get(i));
}
}
results.count=filteredPets.size();
results.values=filteredPets;
}else
{
results.count=filterList.size();
results.values=filterList;
}
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
adapter.pets= (ArrayList<Pets>) results.values;
//REFRESH
adapter.notifyDataSetChanged();
}
Adapter.java
public class Adapter extends RecyclerView.Adapter<Adapter.MyViewHolder> implements Filterable {
List<Pets> pets, petsFilter;
private Context context;
private RecyclerViewClickListener mListener;
CustomFilter filter;
public Adapter(List<Pets> pets, Context context, RecyclerViewClickListener listener) {
this.pets = pets;
this.petsFilter = pets;
this.context = context;
this.mListener = listener;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
return new MyViewHolder(view, mListener);
}
#SuppressLint("CheckResult")
#Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
holder.mName.setText(pets.get(position).getName());
holder.mType.setText(pets.get(position).getBreed() + " / "
+ pets.get(position).getSpecies());
holder.mDate.setText(pets.get(position).getBirth());
RequestOptions requestOptions = new RequestOptions();
requestOptions.skipMemoryCache(true);
requestOptions.diskCacheStrategy(DiskCacheStrategy.NONE);
requestOptions.placeholder(R.drawable.logo);
requestOptions.error(R.drawable.logo);
Glide.with(context)
.load(pets.get(position).getPicture())
.apply(requestOptions)
.into(holder.mPicture);
final Boolean love = pets.get(position).getLove();
if (love){
holder.mLove.setImageResource(R.drawable.likeon);
} else {
holder.mLove.setImageResource(R.drawable.likeof);
}
}
#Override
public int getItemCount() {
return pets.size();
}
#Override
public Filter getFilter() {
if (filter==null) {
filter=new CustomFilter((ArrayList<Pets>) petsFilter,this);
}
return filter;
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private RecyclerViewClickListener mListener;
private CircleImageView mPicture;
private ImageView mLove;
private TextView mName, mType, mDate;
private RelativeLayout mRowContainer;
public MyViewHolder(View itemView, RecyclerViewClickListener listener) {
super(itemView);
mPicture = itemView.findViewById(R.id.picture);
mName = itemView.findViewById(R.id.name);
mType = itemView.findViewById(R.id.type);
mLove = itemView.findViewById(R.id.love);
mDate = itemView.findViewById(R.id.date);
mRowContainer = itemView.findViewById(R.id.row_container);
mListener = listener;
mRowContainer.setOnClickListener(this);
mLove.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.row_container:
mListener.onRowClick(mRowContainer, getAdapterPosition());
break;
case R.id.love:
mListener.onLoveClick(mLove, getAdapterPosition());
break;
default:
break;
}
}
}
public interface RecyclerViewClickListener {
void onRowClick(View view, int position);
void onLoveClick(View view, int position);
}
}
What am I missing?
Hi I have a problem with click on the cardview, in practice since I added a searchview on the toolbar to search for items on the list I create, selecting an object in the list does not allow me to go to change parameters through the edit class
you would be so kind as to help me solve this problem and help me understand where I'm wrong
RoomAdapter
public class RoomAdapter extends RecyclerView.Adapter<RoomAdapter.TicketHolder> implements Filterable {
//List<TicketEntity> ticketEntity = new ArrayList<>();
private List<TicketEntity> ticketEntity;
private List<TicketEntity> ticketEntitySearch;
private Context mCtx;
public RoomAdapter(List<TicketEntity> ticketEntity){
this.ticketEntity = ticketEntity;
// this.mCtx = mCtx;
ticketEntitySearch = new ArrayList<>(ticketEntity);
}
#Override
public TicketHolder onCreateViewHolder(#NonNull ViewGroup parent, int i) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_recyclerview, parent, false);
return new TicketHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull TicketHolder holder, int position) {
TicketEntity currenTicket = ticketEntity.get(position);
holder.mTextticket.setText(currenTicket.getNumticket());
holder.mTextredattore.setText(currenTicket.getRedattore());
holder.mTexttarga.setText(currenTicket.getTarga());
holder.mTextdataA.setText(currenTicket.getDopen());
holder.mTextmanutenzioneG.setText(currenTicket.getMateriale());
holder.mTextdataC.setText(currenTicket.getDclosed());
}
#Override
public int getItemCount() {
return ticketEntity.size();
}
public void setTicketEntity(List<TicketEntity> ticketEntity){
this.ticketEntity = ticketEntity;
notifyDataSetChanged();
}
void setTickets(List<TicketEntity> tickets){
ticketEntity = tickets;
notifyDataSetChanged();
}
#Override
public Filter getFilter() {
return ticketFilter;
}
private Filter ticketFilter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
List<TicketEntity>filteredList = new ArrayList<>();
if (constraint == null || constraint.length() == 0){
filteredList.addAll(ticketEntitySearch);
}else{
String filterPattern = constraint.toString().toLowerCase().trim();
for (TicketEntity item : ticketEntitySearch){
if(item.getNumticket().toLowerCase().contains(filterPattern)){
filteredList.add(item);
}
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
ticketEntity.clear();
ticketEntity.addAll((List)results.values);
notifyDataSetChanged();
}
};
class TicketHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView mTextticket,mTextredattore,mTexttarga,mTextdataA,mTextmanutenzioneG,mTextdataC;
Context mCtx;
//todo Costructor
public TicketHolder(#NonNull View itemView) {
super(itemView);
mTextticket = itemView.findViewById(R.id.txt_ticket);
mTextredattore = itemView.findViewById(R.id.txt_redattore);
mTexttarga = itemView.findViewById(R.id.txt_targa);
mTextdataA = itemView.findViewById(R.id.txt_dataA);
mTextmanutenzioneG = itemView.findViewById(R.id.txt_materiale);
mTextdataC = itemView.findViewById(R.id.txt_dataC);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
TicketEntity ticket = ticketEntity.get(getAdapterPosition());
Intent intent = new Intent(mCtx,ModificaActivity.class);
intent.putExtra("ticket", ticket);
mCtx.startActivity(intent);
}
}
/*public TicketEntity getTicketSwipe(int position){
return ticketEntity.get(position);
}
*/
}
Visualizza
package alessandro.mystudio.ticketfirebase;
public class Visualizza extends AppCompatActivity {
RecyclerView mRecyclerView;
Toolbar mToolbar;
List<TicketEntity> tickets;
RoomAdapter adapter;
private AppDatabase appDatabase;
private Context mCtx;
//private static final String TAG = "Visualizza";
//public static final int ADD_TICKET_REQUEST = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recyclerview);
mToolbar = findViewById(R.id.toolbarLayout);
setSupportActionBar(mToolbar);
appDatabase = AppDatabase.getDatabase(this);
BuildRecyclearView();
new getAll().execute();
new ItemTouchHelper(simpleCallback).attachToRecyclerView(mRecyclerView);
}
//TODO METODO DI SWIPE DELETE SULLA CARDVIEW
ItemTouchHelper.SimpleCallback simpleCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.RIGHT)
{
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, #NonNull RecyclerView.ViewHolder viewHolder1) {
return false;
}
#Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
if(tickets !=null){
TicketEntity swipedTicket = tickets.get(viewHolder.getAdapterPosition());
if(swipedTicket != null){
swipeToDelete(swipedTicket, viewHolder);
}
}
}
};
//TODO MESSAGGIO ALERT DIALOG DI CONFERMA OPPURE DI ANNULLARE
private void swipeToDelete( final TicketEntity swipedTicket, final RecyclerView.ViewHolder viewHolder) {
new AlertDialog.Builder(Visualizza.this)
.setMessage("Delete Ticket?")
.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
// TODO: 28/09/2018 delete note
// Item swiped.
int pos = viewHolder.getAdapterPosition();
// Remove from database
new deleteTicket(pos).execute(tickets.get(pos));
adapter.notifyItemRemoved(viewHolder.getAdapterPosition());
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
// TODO: 28/09/2018 Undo swipe and restore swipedNote
mRecyclerView.getAdapter().notifyItemChanged(viewHolder.getAdapterPosition());
}
})
.setCancelable(false)
.create().show();
}
//TODO Costruzione della RecyclerView
public void BuildRecyclearView() {
//todo dichiarazione adapter e chiamiamo il suo costruttore passandogli i parametri necessari
mRecyclerView = findViewById(R.id.miorecyclerView);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
}
//TODO VISUALIZZARE TUTTI I TICKET
private class getAll extends AsyncTask<Void, Void, Void>
{
#Override
protected Void doInBackground(Void... voids) {
tickets = (List<TicketEntity>) appDatabase.ticketDao().getAll();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
adapter = new RoomAdapter(tickets);
mRecyclerView.setAdapter(adapter);
}
}
//TODO MESSAGGIO DI ALERDIALOG
public void showMessage(String title,String Message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setIcon(R.drawable.ic_error);
builder.setMessage(Message);
builder.show();
}
//TODO Procedura ToolBar Menu & SearchView
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.my_menu, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) searchItem.getActionView();
//searchView.setImeOptions(EditorInfo.IME_ACTION_DONE);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return false;
}
});
return true;
}
//TODO DELETE TICKET
private class deleteTicket extends AsyncTask<TicketEntity, Void, Void>
{
int pos;
public deleteTicket(int pos) {
this.pos = pos;
}
#Override
protected Void doInBackground(TicketEntity... ticketEntities) {
appDatabase.ticketDao().deleteTicket(ticketEntities[0].getId());
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
tickets.remove(pos);
adapter.notifyItemRemoved(pos);
}
}
}
I want to select an item by position in adapter programmatically
in my project i have an activity that get categories , now i want to select an item form this adapter automatic.
final result is :
after Home activity have been lunched when user clicks on the button and lunch the second activity that getting my categories from web service in the adapter and then select an item by position at adapter and run third activity that shown the content of the item.
Here is my codes
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class FragmentCategory extends Fragment {
private View root_view, parent_view;
private RecyclerView recyclerView;
private SwipeRefreshLayout swipe_refresh;
private AdapterCategory mAdapter;
private Call<CallbackCategories> callbackCall = null;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
root_view = inflater.inflate(R.layout.fragment_category, null);
parent_view = getActivity().findViewById(R.id.main_content);
swipe_refresh = (SwipeRefreshLayout) root_view.findViewById(R.id.swipe_refresh_layout_category);
recyclerView = (RecyclerView) root_view.findViewById(R.id.recyclerViewCategory);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setHasFixedSize(true);
//set data and list adapter
mAdapter = new AdapterCategory(getActivity(), new ArrayList<Category>());
recyclerView.setAdapter(mAdapter);
// on item list clicked
mAdapter.setOnItemClickListener(new AdapterCategory.OnItemClickListener() {
#Override
public void onItemClick(View v, Category obj, int position) {
ActivityCategoryDetails.navigate((ActivityMain) getActivity(), v.findViewById(R.id.lyt_parent), obj);
}
});
// on swipe list
swipe_refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mAdapter.resetListData();
requestAction();
}
});
requestAction();
return root_view;
}
private void displayApiResult(final List<Category> categories) {
mAdapter.setListData(categories);
swipeProgress(false);
if (categories.size() == 0) {
showNoItemView(true);
}
}
private void requestCategoriesApi() {
API api = RestAdapter.createAPI();
callbackCall = api.getAllCategories();
callbackCall.enqueue(new Callback<CallbackCategories>() {
#Override
public void onResponse(Call<CallbackCategories> call, Response<CallbackCategories> response) {
CallbackCategories resp = response.body();
if (resp != null && resp.status.equals("ok")) {
displayApiResult(resp.categories);
} else {
onFailRequest();
}
}
#Override
public void onFailure(Call<CallbackCategories> call, Throwable t) {
if (!call.isCanceled()) onFailRequest();
}
});
}
private void onFailRequest() {
swipeProgress(false);
if (NetworkCheck.isConnect(getActivity())) {
showFailedView(true, getString(R.string.failed_text));
} else {
showFailedView(true, getString(R.string.no_internet_text));
}
}
private void requestAction() {
showFailedView(false, "");
swipeProgress(true);
showNoItemView(false);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
requestCategoriesApi();
}
}, Constant.DELAY_TIME);
}
#Override
public void onDestroy() {
super.onDestroy();
swipeProgress(false);
if(callbackCall != null && callbackCall.isExecuted()){
callbackCall.cancel();
}
}
private void showFailedView(boolean flag, String message) {
View lyt_failed = (View) root_view.findViewById(R.id.lyt_failed_category);
((TextView) root_view.findViewById(R.id.failed_message)).setText(message);
if (flag) {
recyclerView.setVisibility(View.GONE);
lyt_failed.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
lyt_failed.setVisibility(View.GONE);
}
((Button) root_view.findViewById(R.id.failed_retry)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
requestAction();
}
});
}
private void showNoItemView(boolean show) {
View lyt_no_item = (View) root_view.findViewById(R.id.lyt_no_item_category);
((TextView) root_view.findViewById(R.id.no_item_message)).setText(R.string.no_category);
if (show) {
recyclerView.setVisibility(View.GONE);
lyt_no_item.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
lyt_no_item.setVisibility(View.GONE);
}
}
private void swipeProgress(final boolean show) {
if (!show) {
swipe_refresh.setRefreshing(show);
return;
}
swipe_refresh.post(new Runnable() {
#Override
public void run() {
swipe_refresh.setRefreshing(show);
}
});
}
}
`
Update : AdapterCategory Codes
public class AdapterCategory extends RecyclerView.Adapter<AdapterCategory.ViewHolder> {
private List<Category> items = new ArrayList<>();
private Context ctx;
private OnItemClickListener mOnItemClickListener;
public interface OnItemClickListener {
void onItemClick(View view, Category obj, int position);
}
public void setOnItemClickListener(final OnItemClickListener mItemClickListener) {
this.mOnItemClickListener = mItemClickListener;
}
// Provide a suitable constructor (depends on the kind of dataset)
public AdapterCategory(Context context, List<Category> items) {
this.items = items;
ctx = context;
}
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView name;
public TextView post_count;
public LinearLayout lyt_parent;
public ViewHolder(View v) {
super(v);
name = (TextView) v.findViewById(R.id.name);
post_count = (TextView) v.findViewById(R.id.post_count);
lyt_parent = (LinearLayout) v.findViewById(R.id.lyt_parent);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_category, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
final Category c = items.get(position);
holder.name.setText(Html.fromHtml(c.title));
holder.post_count.setText(c.post_count+"");
holder.lyt_parent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(view, c, position);
}
}
});
}
public void setListData(List<Category> items){
this.items = items;
notifyDataSetChanged();
}
public void resetListData() {
this.items = new ArrayList<>();
notifyDataSetChanged();
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return items.size();
}
}
when i just use the imageRecyclerViewAdapter.notifyDataSetChanged(); it did not work anyway.
imageRecyclerViewAdapter = new ImageRecyclerViewAdapter(MainActivity.this,imagesList);
recyclerView.setAdapter(imageRecyclerViewAdapter);
if i did this , it will be work.
so how should i do .
my code following.
public class ImageRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
public static final int TYPE_ITEM = 0;
public static final int TYPE_FOOTER = 1;
private boolean hasFooter;//设置是否显示Footer
private boolean hasMoreData;//设置是否可以继续加载数据
private List<ImageFuli> images;
private Context context;
public ImageRecyclerViewAdapter(Context context, List<ImageFuli> images) {
this.images = images;
this.context = context;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if(viewType == TYPE_FOOTER){//底部 加载view
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.footer_progress, parent, false);
return new FooterViewHolder(view);
} else {
View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.image_list, null);
ImageViewHolder ivh = new ImageViewHolder(layoutView);
return ivh;
}
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if(holder instanceof FooterViewHolder) {
if(hasMoreData){
((FooterViewHolder) holder).mProgressView.setVisibility(View.VISIBLE);
} else {
((FooterViewHolder) holder).mProgressView.setVisibility(View.GONE);
}
} else {
ImageViewHolder imageViewHolder = (ImageViewHolder) holder;
ImageFuli imageFuli= images.get(position);
imageViewHolder.imageView.setOriginalSize(imageFuli.getWidth(), imageFuli.getHeight());
Glide.with(context)
.load(imageFuli.getUrl())
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(imageViewHolder.imageView);
ViewCompat.setTransitionName(imageViewHolder.imageView,imageFuli.getUrl());
}
}
#Override
public int getItemCount() {
return this.images.size() + (hasFooter ? 1 : 0);
}
#Override
public int getItemViewType(int position) {
if (position == getBasicItemCount() && hasFooter) {
return TYPE_FOOTER;
}
return TYPE_ITEM;//0
}
private int getBasicItemCount() {
return images.size();
}
public boolean hasFooter() {
return hasFooter;
}
public void setHasFooter(boolean hasFooter) {
if(this.hasFooter != hasFooter) {
this.hasFooter = hasFooter;
notifyDataSetChanged();
}
}
public boolean hasMoreData() {
return hasMoreData;
}
public void setHasMoreData(boolean isMoreData) {
if(this.hasMoreData != isMoreData) {
this.hasMoreData = isMoreData;
notifyDataSetChanged();
}
}
public void setHasMoreDataAndFooter(boolean hasMoreData, boolean hasFooter) {
if(this.hasMoreData != hasMoreData || this.hasFooter != hasFooter) {
this.hasMoreData = hasMoreData;
this.hasFooter = hasFooter;
notifyDataSetChanged();
}
}
public class ImageViewHolder extends RecyclerView.ViewHolder {
private RatioImageView imageView;
public ImageViewHolder(View itemView) {
super(itemView);
imageView = (RatioImageView) itemView.findViewById(R.id.image);
}
}
public class FooterViewHolder extends RecyclerView.ViewHolder {
public final View mProgressView;
public FooterViewHolder(View view) {
super(view);
mProgressView = View.inflate(context,R.layout.footer_progress, null);
}
}
}
and the mainActivity
public class MainActivity extends AppCompatActivity {
private StaggeredGridLayoutManager gaggeredGridLayoutManager;
private List<ImageFuli> imagesList = new ArrayList<ImageFuli>();
private ImageRecyclerViewAdapter imageRecyclerViewAdapter;
private RecyclerView recyclerView;
private SwipeRefreshLayout swipeRefreshLayout;
private boolean onLoading = false;
private int loadImageCount = 15;
private int loadTimes=1;
#TargetApi(Build.VERSION_CODES.M)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
getImagesDataFromHttp();
}
private void init() {
recyclerView = (RecyclerView)findViewById(R.id.content);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.refresher);
swipeRefreshLayout.setColorSchemeColors(R.color.colorPrimary);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
getImagesDataFromHttp();
}
});
recyclerView.setHasFixedSize(true);
imageRecyclerViewAdapter = new ImageRecyclerViewAdapter(MainActivity.this, imagesList);
recyclerView.setAdapter(imageRecyclerViewAdapter);
gaggeredGridLayoutManager = new StaggeredGridLayoutManager(2, 1);
recyclerView.setLayoutManager(gaggeredGridLayoutManager);
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
}
});
}
private void getImagesDataFromHttp() {
HttpUtil.httpRequestToGank(ApiUrl.gankApiUrl+(loadImageCount+5*loadTimes)+"/1" , new HttpUtil.HttpUtilCallBack() {
#Override
public void onFinsh(String response) {
try {
imagesList = ResponseHandleUtil.HandleResponseFromHttp(response, MainActivity.this);
loadTimes++;
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
// imageRecyclerViewAdapter = new ImageRecyclerViewAdapter(MainActivity.this, imagesList);
// recyclerView.setAdapter(imageRecyclerViewAdapter);
//imageRecyclerViewAdapter.notifyDataSetChanged();
recyclerView.getAdapter().notifyDataSetChanged();
imageRecyclerViewAdapter.setHasFooter(false);
if (swipeRefreshLayout.isRefreshing()) {
swipeRefreshLayout.setRefreshing(false);
}
}
});
}
#Override
public void onError(Exception e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, "加载失败!", Toast.LENGTH_SHORT).show();
if (swipeRefreshLayout.isRefreshing()) {
swipeRefreshLayout.setRefreshing(false);
}
}
});
}
});
}
}
get the adapter of your recyclerview
mRecyclerView.getAdapter().notifyDataSetChanged();
because i change the imagelist's reference .so adapter.notifyDataSetChanged can not work any more.