I have already tried many solution from this site. But still does not get the working solution.
This is my Fragment class. I have set the Adpater in this class.
public class FeedFragment extends Fragment {
RecyclerView recyclerView;
Context context;
FloatingActionButton addFeedButton;
private ArrayList<Feed> feeds;
FeedService feedService;
FeedRecyclerViewAdapter feedRecyclerViewAdapter;
TextView noDataTextView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_feed, container, false);
noDataTextView = view.findViewById(R.id.no_data_textView);
addFeedButton = view.findViewById(R.id.feed_floating_button);
System.out.println(getRole());
if (getRole().equals("ROLE_ADMIN")) {
addFeedButton.setVisibility(View.VISIBLE);
} else {
addFeedButton.setVisibility(View.GONE);
}
addFeedButton.setOnClickListener(v -> {
AddFeedFragment addFeedFragment = new AddFeedFragment();
FragmentManager fragmentManager = Objects.requireNonNull(getActivity()).getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_for_fragments, addFeedFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
});
recyclerView = view.findViewById(R.id.feedRecyclerView);
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(linearLayoutManager);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
initializeData();
return view;
}
public void initializeData() {
feedService = APIUtils.getFeedService();
feedService.getFeeds(AuthenticationToken()).enqueue(new Callback<List<Feed>>() {
#Override
public void onResponse(Call<List<Feed>> call, Response<List<Feed>> response) {
if (response.isSuccessful()) {
if (response != null) {
feeds = new ArrayList<>(response.body());
if(feeds.isEmpty()){
noDataTextView.setVisibility(View.VISIBLE);
}
else {
feedRecyclerViewAdapter = new FeedRecyclerViewAdapter(getActivity(), feeds);
recyclerView.setAdapter(feedRecyclerViewAdapter);
}
}
} else {
Toast.makeText(getContext(), "Unauthorized", Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<List<Feed>> call, Throwable t) {
Toast.makeText(getContext(), t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
private String AuthenticationToken() {
PrefManager prefManager = new PrefManager(getContext());
return prefManager.Authorization();
}
private String getRole() {
PrefManager prefManager = new PrefManager(getContext());
return prefManager.getRole();
}
}
And this is my Adapter class.
public class FeedRecyclerViewAdapter extends RecyclerView.Adapter<FeedRecyclerViewAdapter.FeedViewHolder> {
private ArrayList<Feed> feeds;
private Context context;
FeedService feedService;
ProfileService profileService;
public FeedRecyclerViewAdapter(Context context, ArrayList<Feed> feeds) {
this.feeds = feeds;
this.context = context;
}
public static class FeedViewHolder extends RecyclerView.ViewHolder {
CardView feedCardView;
TextView textViewTitle, textViewDescription, textViewPostBy, textViewPostDate, textViewMobile;
TextView textViewOption;
ImageView imageView,callButtonView;
public FeedViewHolder(#NonNull #NotNull View itemView) {
super(itemView);
feedCardView = itemView.findViewById(R.id.feedCardView);
imageView=itemView.findViewById(R.id.user_photo);
callButtonView=itemView.findViewById(R.id.callButton);
textViewTitle = itemView.findViewById(R.id.feedTitle);
textViewDescription = itemView.findViewById(R.id.feedDescription);
textViewPostBy = itemView.findViewById(R.id.postBy);
textViewPostDate = itemView.findViewById(R.id.posDate);
textViewMobile = itemView.findViewById(R.id.mobile);
textViewOption = itemView.findViewById(R.id.three_dot);
}
}
#NonNull
#NotNull
#Override
public FeedRecyclerViewAdapter.FeedViewHolder onCreateViewHolder(#NonNull #NotNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.feed_custom_layout, parent, false);
FeedViewHolder fvh = new FeedViewHolder(view);
return fvh;
}
#Override
public void onBindViewHolder(#NonNull #NotNull FeedViewHolder holder, int position) {
final long itemId = feeds.get(position).getId();
final String profilePicName=feeds.get(position).getUser().getProfile().getProfilePic();
profileService= APIUtils.getProfileService();
profileService.loadProfile(AuthenticationToken(),profilePicName).enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
System.out.println(response.code());
if(response.isSuccessful()){
try {
byte[] bytes=response.body().bytes();
Bitmap bitmap= BitmapFactory.decodeByteArray(bytes,0,bytes.length);
Glide.with(context).asBitmap()
.load(bitmap)
.apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.ALL))
.placeholder(R.drawable.account_circle).into(holder.imageView);
} catch (IOException e) {
e.printStackTrace();
}
}
else{
Toast.makeText(context,"Load failed",Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(context,t.getMessage(),Toast.LENGTH_LONG).show();
}
});
holder.textViewTitle.setText(feeds.get(position).getFeedTitle());
holder.textViewDescription.setText(feeds.get(position).getFeedDescription());
holder.textViewPostBy.setText(feeds.get(position).getUser().getFullName());
holder.textViewPostDate.setText(feeds.get(position).getPostDate());
holder.textViewMobile.setText(feeds.get(position).getUser().getMobile());
holder.callButtonView.setOnClickListener(v -> {
String phone=feeds.get(position).getUser().getMobile();
String dialCall="tel:"+phone;
Intent intent=new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse(dialCall));
context.startActivity(intent);
});
ItemAnimation.animateFadeIn(holder.itemView, position);
if(getRole().equals("ROLE_ADMIN")){
holder.textViewOption.setOnClickListener(v -> {
PopupMenu popupMenu = new PopupMenu(context, holder.textViewOption);
popupMenu.inflate(R.menu.update_delete_menu);
popupMenu.setOnMenuItemClickListener(item -> {
switch (item.getItemId()) {
case R.id.popup_update:
AlertDialog.Builder builder= new AlertDialog.Builder(v.getContext());
builder.setTitle(R.string.dialog_feed_update_title);
builder.setPositiveButton(R.string.dialog_yes, (dialog, which) -> {
Intent intent = new Intent(context, FeedUpdateActivity.class);
intent.putExtra("feedId", itemId);
context.startActivity(intent);
});
builder.setNegativeButton(R.string.dialog_no, (dialog, which) -> {
Toast.makeText(context.getApplicationContext(),"Canceled",Toast.LENGTH_LONG).show();
});
builder.create().show();
break;
case R.id.popup_delete:
AlertDialog.Builder builder1 = new AlertDialog.Builder(v.getContext());
builder1.setTitle(R.string.dialog_delete_title);
builder1.setPositiveButton(R.string.dialog_yes, (dialog, which) -> {
feedService = APIUtils.getFeedService();
feedService.deleteFeed(itemId, AuthenticationToken()).enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
Toast.makeText(context.getApplicationContext(), "Deleted", Toast.LENGTH_LONG).show();
notifyDataSetChanged();
} else {
Toast.makeText(context.getApplicationContext(), "Delete Failed", Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(context.getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show();
}
});
});
builder1.setNegativeButton(R.string.dialog_no, (dialog, which) -> {
Toast.makeText(context.getApplicationContext(), "Canceled", Toast.LENGTH_LONG).show();
});
builder1.create().show();
break;
}
return false;
});
popupMenu.show();
});
}
else{
holder.textViewOption.setVisibility(View.GONE);
}
}
#Override
public void onAttachedToRecyclerView(#NotNull RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public int getItemCount() {
return feeds.size();
}
private String AuthenticationToken() {
PrefManager prefManager = new PrefManager(context.getApplicationContext());
return prefManager.Authorization();
}
private String getRole() {
PrefManager prefManager = new PrefManager(context.getApplicationContext());
return prefManager.getRole();
}
}
Here I have called the notifyDataSetChange. But it can not refresh the arraylist set in the Fragment class. How can I refresh that arraylist in fragment after the deletion is completed in Adapter class.
You can use DiffUtil to load data into the recyclerview adapter. For the on click listener you can implement that method in the fragment itself(create interface in the adapter class, implement method in fragment, and pass instance of the interface to the adapter's constructor). Now you can manipulate the data as much as you want by changing the original list.
Related
How can I refresh the RecyclerView after adding a new item, Note that I'm using a hub connection to send and receive messages from the back-end side, and I'm trying to use notifyItemRangeChanged to refresh the RecyclerView but it does not work,
Here is the adapter class:
public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.ViewHolder> {
public static final int MSG_TYPE_LEFT = 0;
public static final int MSG_TYPE_RIGHT = 1;
public static int i = 0;
private Context mContext;
private List<Chat> mChat;
private String imageurl;
public MessageAdapter(Context mContext, List<Chat> mChat, String imageurl) {
this.mContext = mContext;
this.mChat = mChat;
this.imageurl = imageurl;
}
#NonNull
#Override
public MessageAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if(viewType == MSG_TYPE_RIGHT){
View view = LayoutInflater.from(mContext).inflate(R.layout.chat_item_right, parent, false);
return new MessageAdapter.ViewHolder(view);
}else{
View view = LayoutInflater.from(mContext).inflate(R.layout.chat_item_left, parent, false);
return new MessageAdapter.ViewHolder(view);
}
}
#Override
public void onBindViewHolder(#NonNull MessageAdapter.ViewHolder holder, int position) {
Chat chat = mChat.get(position);
holder.show_message.setText(chat.getMessage());
holder.profile_image.setImageResource(R.mipmap.ic_launcher);
holder.setItem_on_click_listener(new item_on_click_listener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
Toast.makeText(mContext, "Clicked", Toast.LENGTH_LONG).show();
}
});
}
#Override
public int getItemCount() {
return mChat.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener{
public TextView show_message;
public ImageView profile_image;
private item_on_click_listener item_on_click_listener;
public ViewHolder(View itemView) {
super(itemView);
show_message = itemView.findViewById(R.id.show_message);
profile_image = itemView.findViewById(R.id.profile_image);
}
public void setItem_on_click_listener(item_on_click_listener item_on_click_listener){
this.item_on_click_listener = item_on_click_listener;
}
#Override
public void onClick(View view) {
item_on_click_listener.onClick(view, getAdapterPosition(), false);
}
#Override
public boolean onLongClick(View view) {
item_on_click_listener.onClick(view, getAdapterPosition(), false);
return true;
}
}
#Override
public int getItemViewType(int position) {
i = position;
if(mChat.get(position).getSender() == "Sender Name"){
return MSG_TYPE_RIGHT;
}
else{
return MSG_TYPE_LEFT;
}
}
#Override
public void onAttachedToRecyclerView(#NonNull RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
recyclerView.refreshDrawableState();
}
}
Here is the main-activity class:
public class MainActivity extends AppCompatActivity {
Button sendBtn;
ArrayList<String> messagesList = new ArrayList<>();
HubConnection hubConnection;
EditText edt_text;
TextView txt_received;
MessageAdapter messageAdapter;
List<Chat> mChat;
RecyclerView recyclerView;
public void readMessages(String sender, String receiver, String message){
Chat chat = new Chat(sender, receiver, message);
mChat.add(chat);
messageAdapter = new MessageAdapter(MainActivity.this, mChat, "default");
recyclerView.setAdapter(messageAdapter);
messageAdapter.notifyItemRangeChanged(messageAdapter.getItemCount(), mChat.size());
}
#SuppressLint("WrongThread")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
linearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(linearLayoutManager);
mChat = new ArrayList<>();
messageAdapter = new MessageAdapter(MainActivity.this, mChat, "default");
recyclerView.setAdapter(messageAdapter);
sendBtn = findViewById(R.id.send_btn);
edt_text = findViewById(R.id.edt_text);
try {
hubConnection = HubConnectionBuilder.create("URL").build();
hubConnection.start();
AtomicReference<String> state = new AtomicReference<>("");
hubConnection.start().subscribe(() -> {
state.set("Connect");
},
error -> {
state.set("error");
});
hubConnection.on("SendMessage", (param1, param2, param3, param4) -> {
readMessages("Sender Name", "Receiver Name", "Message");
}, String.class, String.class, String.class, Integer.class);
}
catch (Exception e){
String exMessage = e.getMessage();
}
sendBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
if(edt_text.getText().toString().length() > 0){
if(hubConnection.getConnectionState() == HubConnectionState.DISCONNECTED){
hubConnection.start();
}
hubConnection.send("Method Name", "param1", "param2", "param3", "param4");
hubConnection.on("ReceiveMessage", (param1, param2, param3 , param4) -> {
readMessages("Sender Name", "Receiver Name", "Message");
}, String.class, String.class, String.class, Integer.class);
}
else{
edt_text.setHint("Can not be empty");
}
}catch (Exception ex){
String message ;
message = ex.getMessage();
}
}
});
}
}
Can anyone help me, please?
notifyItemRangeChanged will work if you add/remove the data in same instance of Adapter or any other notify method for that matter. The problem here is you are creating a new Adapter every time inside your readMessages method.
Create adapter only once and notify it as needed .. Since you already created the messageAdapter inside onCreate you can use the same instance.
public void readMessages(String sender, String receiver, String message){
Chat chat = new Chat(sender, receiver, message);
mChat.add(chat);
messageAdapter.notifyItemRangeChanged(messageAdapter.getItemCount(), mChat.size());
}
I have BottomNavigationView where i display fragments and i have adapter named FavoriteRecViewAdapter related on FavoritFragment.java, i need to reload FavoritFragment if one of favorites was deleted
I have BottomNavigationView where i display fragments and i have adapter named FavoriteRecViewAdapter related on FavoritFragment.java, i need to reload FavoritFragment if one of favorites was deleted
sorry for spam stackoverflow forced me ;)
FavoritFragment.java :
public class FavoriFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private List<Favorite> favorites;
private RecyclerView favoriteRecView;
private FloatingActionButton fabAddFavorite;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public FavoriFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment FavoriFragment.
*/
// TODO: Rename and change types and number of parameters
public static FavoriFragment newInstance(String param1, String param2) {
FavoriFragment fragment = new FavoriFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_favori, container, false);
favoriteRecView = (RecyclerView) rootView.findViewById(R.id.favoriteRecView);
fabAddFavorite = rootView.findViewById(R.id.fabAddFavorite);
favorites = new ArrayList<>();
Retrofit retrofit = RetrofitClientInstance.getRetrofitInstance(getContext());
final FavoriteAPI favoriteAPI = retrofit.create(FavoriteAPI.class);
Call<List<Favorite>> call = favoriteAPI.getFavorites();
call.enqueue(new Callback<List<Favorite>>() {
#Override
public void onResponse(Call<List<Favorite>> call, Response<List<Favorite>> response) {
if(response.code() != 200) {
Toast.makeText(getContext(), "Something wrong", Toast.LENGTH_SHORT).show();
} else {
List<Favorite> favoriteList = response.body();
for(Favorite favorite : favoriteList) {
favorites.add(favorite);
}
initData(favorites);
}
}
#Override
public void onFailure(Call<List<Favorite>> call, Throwable t) {
}
});
fabAddFavorite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getContext(), AddFavoriActivity.class);
getContext().startActivity(intent);
}
});
return rootView;
}
private void initData(List<Favorite> favorites) {
FavoriteRecViewAdapter favoriteRecViewAdapter = new FavoriteRecViewAdapter(favorites, getContext());
favoriteRecView.setAdapter(favoriteRecViewAdapter);
favoriteRecView.setLayoutManager(new LinearLayoutManager(getContext()));
}
}
FavoriteRecViewAdapter.java :
public class FavoriteRecViewAdapter extends RecyclerView.Adapter<FavoriteRecViewAdapter.viewHolder>{
private List<Favorite> favorites;
private Context mContext;
public FavoriteRecViewAdapter(List<Favorite> favorites, Context mContext) {
this.favorites = favorites;
this.mContext = mContext;
}
public FavoriteRecViewAdapter(List<Favorite> favorites) {
this.favorites = favorites;
}
#NonNull
#Override
public viewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.favorites_list_item, parent, false);
return new viewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull viewHolder holder, int position) {
holder.favoriteLibelle.setText(favorites.get(position).getCarte().getLibelle());
holder.favoriteNumero.setText(String.valueOf(favorites.get(position).getCarte().getNumero()));
holder.favoriteComments.setText(favorites.get(position).getComments());
holder.favoriteDate.setText(favorites.get(position).getDate());
holder.deleteFavoriteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String msg = "are your sure ! you want to delete " +
favorites.get(holder.getAdapterPosition()).getCarte().getLibelle() +
" from favorites";
new MaterialAlertDialogBuilder(mContext)
.setTitle("Delete favorite")
.setMessage(msg)
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
})
.setPositiveButton("Yes delete it", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Retrofit retrofit = RetrofitClientInstance.getRetrofitInstance(mContext);
final FavoriteAPI favoriteAPI = retrofit.create(FavoriteAPI.class);
Call<String> call = favoriteAPI.deleteFavorite(
favorites.get(holder.getAdapterPosition()).getId()
);
call.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
if(response.code() == 204) {
showSnackBarSuccess("Favorite was delete successfully");
} else{
showSnackBarError("Some thing wrong please try again !");
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
}
});
}
})
.show();
}
});
}
#Override
public int getItemCount() {
return favorites.size();
}
public class viewHolder extends RecyclerView.ViewHolder{
private TextView favoriteLibelle;
private TextView favoriteNumero;
private TextView favoriteComments;
private TextView favoriteDate;
private Button deleteFavoriteBtn;
public viewHolder(#NonNull View itemView) {
super(itemView);
favoriteLibelle = itemView.findViewById(R.id.favoriteLibelle);
favoriteNumero = itemView.findViewById(R.id.favoriteNumero);
favoriteComments = itemView.findViewById(R.id.favoriteComments);
favoriteDate = itemView.findViewById(R.id.favoriteDate);
deleteFavoriteBtn = itemView.findViewById(R.id.deleteFavoriteBtn);
}
}
private void showSnackBarError(String msg) {
Snackbar.make(((Activity) mContext).findViewById(android.R.id.content), msg, Snackbar.LENGTH_SHORT)
.setTextColor(ContextCompat.getColor(mContext,R.color.white))
.setBackgroundTint(ContextCompat.getColor(mContext,R.color.danger))
.show();
}
private void showSnackBarSuccess(String msg) {
Snackbar.make(((Activity) mContext).findViewById(android.R.id.content), msg, Snackbar.LENGTH_SHORT)
.show();
}
}
Thanks for any help ;)
I found many solution bute they searching in only given list aor may they search through searchview.But In my case I have to search using edite text. search from editText in recyclerview where i am getting items from API using retrofit.here is my code of recyclerview adapter and the class..
i want to filter list of collectionpoint on the basis of name .
thanx in advance
private List<CollectionPoint> collectionPointList;
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView collectionPointId, collectionPointName;
private int collectionPointID;
MyViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
collectionPointId = (TextView) itemView.findViewById(R.id.txtCollectionPointID);
collectionPointName = (TextView) itemView.findViewById(R.id.txtCollectionPointName);
}
#Override
public void onClick(View v) {
Intent intent = new Intent(itemView.getContext(), Appointments.class);`
intent.putExtra("CollectionPointID", collectionPointID);
Appointments.CollectionPointID = collectionPointID;
FragmentProcedure.CollectionPointID = collectionPointID;
itemView.getContext().startActivity(intent);
}
}
public CollectionPointAdapter(List<CollectionPoint> collectionPointList1) {
this.collectionPointList = collectionPointList1;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.collectionpointlistitems, viewGroup, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
CollectionPoint collectionPoint = collectionPointList.get(position);
holder.collectionPointId.setText("ID - " + String.valueOf(collectionPoint.getID()));
holder.collectionPointName.setText(collectionPoint.getName());
holder.collectionPointID = collectionPointList.get(position).getID();
}
#Override
public int getItemCount() {
return collectionPointList.size();
}
public void filterList(ArrayList<CollectionPoint> filteredList) {
collectionPointList = filteredList;
notifyDataSetChanged();
}
Activity :
RecyclerView recyclerView;
public static GetCollectionPointByUserIDResponse getCollectionPointByUserIDResponse = new GetCollectionPointByUserIDResponse();
private List<CollectionPoint> collectionPointList = new ArrayList<>();
CollectionPointAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_collection_point);
getCollectionPoints();
recyclerView = findViewById(R.id.collectionPointRecyclerView);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.addItemDecoration(new DividerItemDecoration(getApplicationContext(), LinearLayoutManager.VERTICAL));
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
TextView logout = findViewById(R.id.logout);
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(CollectionPoints.this, Login.class);
startActivity(intent);
}
});
EditText editText = findViewById(R.id.search);
/* editText.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) {
}
#Override
public void afterTextChanged(Editable s) {
filter(s.toString());
}
});*/
}
private void filter(String text) {
ArrayList<CollectionPoint> filteredList = new ArrayList<>();
for (CollectionPoint item : filteredList) {
if (item.getName().toLowerCase().contains(text.toLowerCase())) {
filteredList.add(item);
}
}
mAdapter.filterList(filteredList);
}
private void getCollectionPoints() {
GetCollectionPointByUserIDResquest request = new GetCollectionPointByUserIDResquest();
request.Token = Login.session.Token;
request.SessionID = Login.session.ID;
request.UserID = Login.loginResponse.UserInfo.get(0).ID;
request.MethodName = "GetCollectionPointBuUserID";
BusinessService businessService = APIClient.getClient().create(BusinessService.class);
Call<GetCollectionPointByUserIDResponse> call = businessService.GetCollectionPointBuUserID(request);
call.enqueue(new Callback<GetCollectionPointByUserIDResponse>() {
#Override
public void onResponse(Call<GetCollectionPointByUserIDResponse> call, Response<GetCollectionPointByUserIDResponse> response) {
try {
if (response.isSuccessful()) {
getCollectionPointByUserIDResponse = response.body();
assert getCollectionPointByUserIDResponse != null;
if (getCollectionPointByUserIDResponse.ResponseCode == 1) {
collectionPointList = new ArrayList<>(getCollectionPointByUserIDResponse.getCollectionpoint());
CollectionPointAdapter collectionPointAdapter = new CollectionPointAdapter(collectionPointList);
recyclerView.setAdapter(collectionPointAdapter);
} else if (getCollectionPointByUserIDResponse.ResponseCode == 6) {
Intent intent = new Intent(CollectionPoints.this, Login.class);
startActivity(intent);
} else {
Toast.makeText(CollectionPoints.this, getCollectionPointByUserIDResponse.ResponseMessage, Toast.LENGTH_LONG).show();
}
}
} catch (Exception e) {
Toast.makeText(CollectionPoints.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<GetCollectionPointByUserIDResponse> call, Throwable t) {
Toast.makeText(CollectionPoints.this, t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
You can filter Recyclerview items from editText by calling filter method in addTextChangedListener and passing arraylist to your Adapter class like below code :
Private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(yourLayout);
context = YourActivity.this;
editText_filter.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
try {
if (CollectionPointAdapter != null)
//Calling Adapter method
CollectionPointAdapter.getFilter().filter(editable);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void setNoDataVisible(int size) { //IF results empty handle UI from adapter.
try {
if (size == 0) {
txtView_noData.setVisibility(View.VISIBLE);
} else {
txtView_noData.setVisibility(View.GONE);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void getCollectionPoints() {
GetCollectionPointByUserIDResquest request = new GetCollectionPointByUserIDResquest();
request.Token = Login.session.Token;
request.SessionID = Login.session.ID;
request.UserID = Login.loginResponse.UserInfo.get(0).ID;
request.MethodName = "GetCollectionPointBuUserID";
BusinessService businessService = APIClient.getClient().create(BusinessService.class);
Call<GetCollectionPointByUserIDResponse> call = businessService.GetCollectionPointBuUserID(request);
call.enqueue(new Callback<GetCollectionPointByUserIDResponse>() {
#Override
public void onResponse(Call<GetCollectionPointByUserIDResponse> call, Response<GetCollectionPointByUserIDResponse> response) {
try {
if (response.isSuccessful()) {
getCollectionPointByUserIDResponse = response.body();
assert getCollectionPointByUserIDResponse != null;
if (getCollectionPointByUserIDResponse.ResponseCode == 1) {
collectionPointList = new ArrayList<>(getCollectionPointByUserIDResponse.getCollectionpoint());
//Here You're passing List to Adatper, so that we can filter it.
CollectionPointAdapter collectionPointAdapter = new CollectionPointAdapter(context, collectionPointList);
recyclerView.setAdapter(collectionPointAdapter);
} else if (getCollectionPointByUserIDResponse.ResponseCode == 6) {
Intent intent = new Intent(CollectionPoints.this, Login.class);
startActivity(intent);
} else {
Toast.makeText(CollectionPoints.this, getCollectionPointByUserIDResponse.ResponseMessage, Toast.LENGTH_LONG).show();
}
}
} catch (Exception e) {
Toast.makeText(CollectionPoints.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<GetCollectionPointByUserIDResponse> call, Throwable t) {
Toast.makeText(CollectionPoints.this, t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
Change your Adapter like below code :
public class CollectionPointAdapter extends RecyclerView.Adapter<CollectionPointAdapter.MyViewHolder> implements Filterable {
private Context mContext;
private ArrayList<CollectionPoint> collectionPointResults;
private ArrayList<CollectionPoint> mFilteredList;
public CollectionPointAdapter(Context mContext, ArrayList<CollectionPoint> collectionPointResults) {
this.mContext = mContext;
this.collectionPointResults = collectionPointResults;
this.mFilteredList = collectionPointResults;
}
#Override
public int getItemCount() {
return mFilteredList.size();
}
#Override
public long getItemId(int position) {
return position;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.item_list_yours, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, final int position) {
try {
holder.collectionPointId.setText("ID - " + String.valueOf(mFilteredList.get(position).getID()));
holder.collectionPointName.setText(mFilteredList.get(position).getName());
} catch (Exception e) {
e.printStackTrace();
}
}
//Filter the adapter interface
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
try {
String charString = charSequence.toString();
if (charString.isEmpty()) {
mFilteredList = collectionPointResults;
} else {
ArrayList<RefLeadsgivenResult> filteredList = new ArrayList<>();
for (RefLeadsgivenResult row : collectionPointResults) {
if (row.getName().toLowerCase().contains(charString)) { //Searching by Name
filteredList.add(row);
}
}
mFilteredList = filteredList;
}
} catch (IndexOutOfBoundsException ie) {
ie.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
FilterResults filterResults = new FilterResults();
filterResults.values = mFilteredList;
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
try {
mFilteredList = (ArrayList<RefLeadsgivenResult>) filterResults.values;
notifyDataSetChanged();
((YourActivity) mContext).setNoDataVisible(mFilteredList.size());
} catch (Exception e) {
e.printStackTrace();
}
}
};
}
class MyViewHolder extends RecyclerView.ViewHolder {
public final View mView;
#BindView(R.id.collectionPointId)
TextView collectionPointId;
#BindView(R.id.collectionPointName)
TextView collectionPointName;
public MyViewHolder(View itemView) {
super(itemView);
mView = itemView;
ButterKnife.bind(this, itemView);
}
}
}
I want to pass a string value from my adapter class to my fragment. I tried storing the string in a bundle. To retrieve the value i used Bundle b = getArguments(); b.getString("key") the problem is im getting a null pointer exception. Below is the code that saves the string in a bundle. So my question is how can i pass a string value from adapterA to fragmentB.
Thanks in advance.
Adapter.java
public class ToDoRecyclerViewAdapter extends RecyclerView.Adapter<ToDoRecyclerViewAdapter.ViewHolder> {
private Context context;
private List<Aktivnost_> mValues;
private final OnListFragmentInteractionListener mListener;
public ToDoRecyclerViewAdapter td;
public ToDoRecyclerViewAdapter(List<Aktivnost_ > items, Context context, OnListFragmentInteractionListener listener) {
mValues = items;
mListener = listener;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.fragment_todo, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.mItem = mValues.get(position);
holder.mContentView.setText(mValues.get(position).getNaziv());
holder.mDateView.setText(mValues.get(position).getDatum());
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (null != mListener) {
mListener.onListFragmentInteraction(holder.mItem);
Intent i = new Intent(context.getApplicationContext(), PodrobnostiActivity.class);
i.putExtra("task_id", mValues.get(position).getId_());
context.getApplicationContext().startActivity(i);
Toast.makeText(v.getContext(), "task - " + mValues.get(position).getId_(), Toast.LENGTH_SHORT).show();
}
}
});
holder.mView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(final View v) {
AlertDialog.Builder adb = new AlertDialog.Builder(v.getContext());
CharSequence meni[] = new CharSequence[] {"DOING", "FINISHED"};
adb.setItems(meni, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if(i == 0) {
Bundle b = new Bundle();
DoingFragment d = new DoingFragment();
mValues.get(i).setStanje("doing");
b.putString("doing", mValues.get(i).getStanje());
d.setArguments(b);
} else {
mValues.get(i).setStanje("koncano");
}
}
});
AlertDialog alertDialog = adb.create();
alertDialog.setCancelable(true);
alertDialog.show();
return true;
}
});
}
#Override
public int getItemCount() {
return mValues.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mContentView;
public final TextView mDateView;
public long id;
public Aktivnost_ mItem;
public ViewHolder(View view) {
super(view);
mView = view;
this.id = id;
mDateView = (TextView) view.findViewById(R.id.Date);
mContentView = (TextView) view.findViewById(R.id.content);
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}
And i want to get the value i set in bundle in this fragment.
Fragment.java
public class DoingFragment extends Fragment {
DoingFragmentRecyclerViewAdapter mAdapter;
private OnListFragmentInteractionListener mListener;
public DoingFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_doingfragment_list, container, false);
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.list_doing);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.addItemDecoration(new DividerItemDecoration(getContext(), LinearLayoutManager.VERTICAL));
mAdapter = new DoingFragmentRecyclerViewAdapter(listAktivnosti(),mListener);
recyclerView.setAdapter(mAdapter);
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnListFragmentInteractionListener) {
mListener = (OnListFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnListFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnListFragmentInteractionListener {
void onListFragmentInteraction1(Aktivnost_ item);
}
AppDatabase db;
public void openDB() {
db = new AppDatabase(getContext());
db.open();
}
Aktivnost_ ak;
List<Aktivnost_> array;
public List<Aktivnost_> listAktivnosti() {
array = new ArrayList<>();
openDB();
Bundle b = getArguments();
Cursor cursor = db.getAllRows(b.getString("doing"));
while(cursor.moveToNext()) {
ak = new Aktivnost_();
ak.setId_(cursor.getLong(cursor.getColumnIndex("_id")));
ak.setNaziv(cursor.getString(cursor.getColumnIndex("naziv")));
ak.setDatum(cursor.getString(cursor.getColumnIndex("datum")));
ak.setFk_projekt(cursor.getInt(cursor.getColumnIndex("fk_projekt")));
ak.setUdeleženci(cursor.getString(cursor.getColumnIndex("udelezenci")));
ak.setStanje(cursor.getString(cursor.getColumnIndex("stanje")));
array.add(ak);
}
return array;
}
}
From the code, I can see you are only setting the Bundle parameters in Fragment object, but not using that fragment object further.
You need to display that fragment object first, then it will reflect into your target fragment.
My recyclerview is not updating correctly after the back button is
pressed.
The recyclerview works fine before the back button is pressed
The data is properly updated (seen in the log) but the recyclerview does not reflect the change
The purpose of the handler is to poll the database for a notification (working fine)
The notification toast is displayed everytime
I am not receiving any errors
If I can provide any other information to help do not hesitate to ask.
Main:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_room);
recView = (RecyclerView) findViewById(R.id.recyclerViewMessages);
linearLayoutManager = new LinearLayoutManager(this) {};
linearLayoutManager.setReverseLayout(true);
recView.setLayoutManager(linearLayoutManager);
listData = (ArrayList) MessagingData.getMessageListData();
adapter = new RecyclerViewAdapterMessaging(listData, this);
recView.setAdapter(adapter);
adapter.setItemClickCallback(this);
final Handler h = new Handler();
final int delay = 2000; //milliseconds
h.postDelayed(new Runnable(){
public void run(){
Notify_Message_Async notify_message_async = new Notify_Message_Async(ctx);
notify_message_async.execute(NOTIFICATION, message_id);
System.out.println(global.getNotification());
if(global.getNotification()==1){
Toast.makeText(ctx, "Notified",
Toast.LENGTH_LONG).show();
try {
refresh_receive();
} catch (ExecutionException e) {
Toast.makeText(ctx, "catch",
Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (InterruptedException e) {
Toast.makeText(ctx, "catch",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
h.postDelayed(this, delay);
}
}, delay);
}
public void refresh_receive() throws ExecutionException, InterruptedException {
String method = "receive_message";
Receive_Live_Message_Async receive_live_message_async = new Receive_Live_Message_Async(this);
receive_live_message_async.execute(method, message_id).get();// Setup the message
adapter.setListData((ArrayList)MessagingData.getMessageListData());
adapter.notifyDataSetChanged();
global.setNotification(0);//reset notification
}
Adapter:
public class RecyclerViewAdapterMessaging extends RecyclerView.Adapter<RecyclerViewAdapterMessaging.Holder> {
private View v;
private List<List_Item_Messaging> listData;
private LayoutInflater inflater;
Global global = new Global();
private ItemClickCallback itemClickCallback;
Context context;
public interface ItemClickCallback {
void onItemClick(View v, int p);
void onSecondaryIconClick(int p);
}
public void setItemClickCallback(final ItemClickCallback itemClickCallback) {
this.itemClickCallback = itemClickCallback;
}
public RecyclerViewAdapterMessaging(List<List_Item_Messaging> listData, Context c) {
inflater = LayoutInflater.from(c);
context = c;
this.listData = listData;
}
#Override
public int getItemViewType(int position) {//0 for self... /1 for Other
List_Item_Messaging item = listData.get(position);
//ENSURE GLOBAL USERNAME NOT NULL
String other_username = item.getMessage_username();
if (other_username == null) {
((Activity) context).finish();
}
if (item.getMessage_username().trim().equals(global.getUserName())) {
System.out.println("The usernames are the same");
return 0;
} else {
System.out.println("The usernames are the NOT same");
return 1;
}
}
#Override
public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType) {
case 0:
View view = inflater.inflate(R.layout.chat_thread, parent, false);// Self
v = view;
break;
case 1:
View view2 = inflater.inflate(R.layout.chat_thread_other, parent, false);// Not self
int width2 = global.getScreenWidth();
v = view2;
break;
}
return new Holder(v);
}
#Override
public void onBindViewHolder(Holder holder, int position) {
List_Item_Messaging item = listData.get(position);
holder.conversation.setText(item.getMessage_conversation());
}
public void setListData(ArrayList<List_Item_Messaging> exerciseList) {
this.listData.clear();
this.listData.addAll(exerciseList);
}
#Override
public int getItemCount() {
return listData.size();
}
class Holder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView thumbnail;
//ImageView secondaryIcon;
TextView conversation;
View message_container;
public Holder(View itemView) {
super(itemView);
conversation = (TextView) itemView.findViewById(R.id.conversation_textview);
message_container = itemView.findViewById(R.id.message_container);
message_container.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.message_container) {
itemClickCallback.onItemClick(v, getAdapterPosition());
} else {
itemClickCallback.onSecondaryIconClick(getAdapterPosition());
}
}
}
public void clearItems() {
listData.clear();
this.notifyDataSetChanged();
}
}
I have referenced the following to no solution:
notifyDataSetChanged not working on RecyclerView
smoothScrollToPosition after notifyDataSetChanged not working in android
adapter.notifyDataSetChange() not working after called from onResume()
change a little in your code
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_room);
recView = (RecyclerView) findViewById(R.id.recyclerViewMessages);
linearLayoutManager = new LinearLayoutManager(this) {};
linearLayoutManager.setReverseLayout(true);
recView.setLayoutManager(linearLayoutManager);
// change here
if (listData != null)
listData.clear();
else listData = new <> ArrayList();
listData.addAdd((ArrayList)MessagingData.getMessageListData());
adapter = new RecyclerViewAdapterMessaging(listData, this);
recView.setAdapter(adapter);
adapter.setItemClickCallback(this);
final Handler h = new Handler();
final int delay = 2000; //milliseconds
then make a small change here
public void refresh_receive() throws ExecutionException, InterruptedException {
String method = "receive_message";
Receive_Live_Message_Async receive_live_message_async = new Receive_Live_Message_Async(this);
receive_live_message_async.execute(method, message_id).get();// Setup the message
// changing here
dataList.clear();
dataList.addAdd((ArrayList)MessagingData.getMessageListData())
adapter.setListData(dataList);
adapter.notifyDataSetChanged();
global.setNotification(0);//reset notification
}
another problem in your code, you are using receive_live_message_async AsyncTask
put your update code in onPostExecute
public class receive_live_message_async extends AsyncTask {
#Override
protected Object doInBackground(Object[] objects) {
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(Object o) {
// call your refresh_receive(); here
super.onPostExecute(o);
}
}
similarly when you are call receive_live_message_async.execute(); update your recyclerView in onPostExecute
#Override
protected void onPostExecute(Object o) {
dataList.clear();
dataList.addAll((ArrayList)MessagingData.getMessageListData());
adapter.notifyDataSetChanged();
super.onPostExecute(o);
}