I wish to retrieve all the data but not only the last 2 sets.
Is there any solutions to retrieve every data from firebase?
Is is because the for loop or array list is having problem?
=================================================
Updated Photo
I'm trying to retrieve the data [matricno,password and temp]
But the output is only the two sets data inside key [Mdl3FODHWV6zv9d2rNr]
When i try to click on each CardView, the data output is the only the third output photo for three of these CardView.
Output:
=================================================
Userlist1.java
public class userlist1 extends AppCompatActivity {
RecyclerView recyclerView;
DatabaseReference database,ab;
MyAdapter1 myAdapter1;
ArrayList<Report1> list;
String uid;
private FirebaseAuth auth;
private FirebaseUser user;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_userlist1);
user = auth.getInstance().getCurrentUser();
uid = user.getUid();
recyclerView = findViewById(R.id.userlist1);
SharedPreferences sharedPreferences = getSharedPreferences("myKey", MODE_PRIVATE);
String key = sharedPreferences.getString("key","");
String temp = sharedPreferences.getString("temp","");
database = FirebaseDatabase.getInstance().getReference("Class Information");
ab = database.child(uid).child("Student Attend").child(key).child("Attendance");
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
list = new ArrayList<>();
myAdapter1 = new MyAdapter1(this,list);
recyclerView.setAdapter(myAdapter1);
ab.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for(DataSnapshot dataSnapshot : snapshot.getChildren()){
Report1 report1 = dataSnapshot.getValue(Report1.class);
list.add(report1);
}
myAdapter1.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
MyAdapter1.java:
public class MyAdapter1 extends RecyclerView.Adapter<MyAdapter1.MyViewHolder> {
Context context;
ArrayList<Report1> list;
public MyAdapter1(Context context, ArrayList<Report1> list) {
this.context = context;
this.list = list;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.item1,parent,false);
return new MyViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
Report1 report1 = list.get(position);
holder.matricno.setText(report1.getMatricno());
holder.password.setText(report1.getPassword());
holder.temp.setText(report1.getTemp());
}
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getItemCount() {
return list.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder{
TextView matricno, password, temp;
public View view;
public MyViewHolder(#NonNull View itemView){
super(itemView);
matricno = itemView.findViewById(R.id.tvmno);
password = itemView.findViewById(R.id.tvpassword);
temp = itemView.findViewById(R.id.tvtemperature);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View itemView) {
Toast.makeText(itemView.getContext(), "Data added into database", Toast.LENGTH_SHORT).show();
}
});
}
}
}
Report1.java:
public class Report1 {
public String matricno;
public String password;
public String temp;
public Report1(){
}
public String getMatricno() {
return matricno;
}
public String getPassword() {
return password;
}
public String getTemp() {
return temp;
}
}
================================================================
Updated New Code
Userlist.java
public class userlist extends AppCompatActivity {
RecyclerView recyclerView;
DatabaseReference database, ab;
MyAdapter myAdapter;
ArrayList<Report> list;
String uid;
private FirebaseAuth auth;
private FirebaseUser user;
Menu menu;
private SearchView searchView = null;
private SearchView.OnQueryTextListener queryTextListener;
SharedPreferences sharedpreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_userlist);
user = auth.getInstance().getCurrentUser();
uid = user.getUid();
recyclerView = findViewById(R.id.userlist);
searchView = findViewById(R.id.action_search);
SharedPreferences sharedPreferences = getSharedPreferences("myKey", MODE_PRIVATE);
String key = sharedPreferences.getString("key","");
String temp = sharedPreferences.getString("temp","");
database = FirebaseDatabase.getInstance().getReference("Class Information");
ab = database.child(uid).child("Student Attend");
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
list = new ArrayList<>();
myAdapter = new MyAdapter(this, list);
recyclerView.setAdapter(myAdapter);
ab.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
Report report = dataSnapshot.getValue(Report.class);
list.add(report);
}
myAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
// Associate searchable configuration with the SearchView
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
searchView = (SearchView) menu.findItem(R.id.action_search)
.getActionView();
searchView.setSearchableInfo(searchManager
.getSearchableInfo(getComponentName()));
searchView.setMaxWidth(Integer.MAX_VALUE);
// listening to search query text change
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
// filter recycler view when query submitted
myAdapter.getFilter().filter(query);
return false;
}
#Override
public boolean onQueryTextChange(String query) {
// filter recycler view when text is changed
myAdapter.getFilter().filter(query);
return false;
}
});
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_dateascending:
Collections.sort(list, Report.ReportDateOldestComparator);
Toast.makeText(userlist.this, "Sort by Date [Oldest - Latest]", Toast.LENGTH_SHORT).show();
myAdapter.notifyDataSetChanged();
return true;
case R.id.menu_descending:
Collections.sort(list, Report.ReportDateLatestComparator);
Toast.makeText(userlist.this, "Sort by Date [Latest - Oldest]", Toast.LENGTH_SHORT).show();
myAdapter.notifyDataSetChanged();
return true;
case R.id.action_search:
// Not implemented here
return false;
default:
break;
}
searchView.setOnQueryTextListener(queryTextListener);
return super.onOptionsItemSelected(item);
}
}
MyAdapter.java
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder>implements Filterable {
Context context;
ArrayList<Report> list;
ArrayList<Report> listfilter;
SharedPreferences sharedpreferences;
public MyAdapter(Context context, ArrayList<Report> list) {
this.context = context;
this.list = list;
this.listfilter = list;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.item,parent,false);
return new MyViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
Report report = list.get(position);
holder.time.setText(report.getTime());
holder.duration.setText(report.getDuration());
holder.info.setText(report.getInfo());
}
#Override
public int getItemCount() {
return list.size();
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
if (charString.isEmpty()) {
list = listfilter;
} else {
List<Report> filteredList = new ArrayList<>();
for (Report row : listfilter) {
// name match condition. this might differ depending on your requirement
// here we are looking for name or phone number match
if (row.getInfo().toLowerCase().contains(charString.toLowerCase()) || row.getTime().contains(charSequence)) {
filteredList.add(row);
}
}
list = (ArrayList<Report>) filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = list;
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
list = (ArrayList<Report>) filterResults.values;
notifyDataSetChanged();
}
};
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView duration, time, info;
public View view;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
time = itemView.findViewById(R.id.tvtemp);
duration = itemView.findViewById(R.id.tvfirstName);
info = itemView.findViewById(R.id.tvmatno);
SharedPreferences sharedPreferences = context.getSharedPreferences("myKey", Context.MODE_PRIVATE);
String key = sharedPreferences.getString("key","");
String temp = sharedPreferences.getString("temp","");
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View itemView) {
sharedpreferences = context.getSharedPreferences("myKey", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("key", key);
editor.putString("temp", temp);
editor.apply();
Intent intent = new Intent(itemView.getContext(), userlist1.class);
itemView.getContext().startActivity(intent);// pass key to next activity;
Toast.makeText(itemView.getContext(), "Data retrieved from database", Toast.LENGTH_SHORT).show();
}
});
}
}
}
Report.java
public class Report {
public String duration;
public String time;
public String info;
public Report(){
}
public void setDuration(String duration) {
this.duration = duration;
}
public void setTime(String time) {
this.time = time;
}
public void setInfo(String info) {
this.info = info;
}
public String getDuration() {
return duration;
}
public String getTime() {
return time;
}
public String getInfo() {
return info;
}
public static Comparator<Report> ReportDateOldestComparator = new Comparator<Report>() {
#Override
public int compare(Report o1, Report o2) {
return o1.getTime().compareTo(o2.getTime());
}
};
public static Comparator<Report> ReportDateLatestComparator = new Comparator<Report>() {
#Override
public int compare(Report o1, Report o2) {
return o2.getTime().compareTo(o1.getTime());
}
};
}
If you want to load the Attendance from all child nodes under Student Attend, you first need to load the data from all those nodes:
ab = database.child(uid).child("Student Attend");
...
ab.addListenerForSingleValueEvent(new ValueEventListener() {
...
Since we'll load data from a higher level in the database, we'll need to navigate across the key and "Attendance" in your onDataChange method now:
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
// 👇 loop over `key` level children
for(DataSnapshot childSnapshot : snapshot.getChildren()) {
// 👇 loop over Attendance children
for(DataSnapshot dataSnapshot : childSnapshot.child("Attendance").getChildren()){
Report1 report1 = dataSnapshot.getValue(Report1.class);
list.add(report1);
}
}
myAdapter1.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException(); // 👈 never ignore errors
}
Related
I have a RecyclerView thats populated from my Firebase Database. The list is quite long so I want the user to be able to search the list. But when the user types the first character into the SearchView, nothing at all is returned.
This is the onCreateView in my FavouriteFragment UPDATED
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.fragment_favourites, container, false);
mAuth = FirebaseAuth.getInstance();
current_user_id = mAuth.getCurrentUser().getUid();
recyclerView = (RecyclerView) view.findViewById(R.id.route_favourites);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
search = (SearchView) view.findViewById(R.id.search);
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference().child("BusRoute");
rootRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot datasnapshot : dataSnapshot.getChildren()){
String key = datasnapshot.getKey();
Query query = rootRef.child(key).orderByChild("route").equalTo(newText);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
favouritesAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
return true;
}
});
favouritesAdapter = new FavouritesAdapter(getDataSetHistory(), getActivity());
favouritesAdapter.notifyDataSetChanged();
recyclerView.setAdapter(favouritesAdapter);
getBusRoutes();
return view;
}
This is my favouritesAdapter:
public class FavouritesAdapter extends RecyclerView.Adapter<FavouritesAdapter.ViewHolder> implements Filterable {
private List<BusRoute> favourites;
private List<BusRoute> searchList;
private Context context;
public static class ViewHolder extends RecyclerView.ViewHolder{
TextView routeTextView, originTextView, destinationTextView;
ImageView addFavouritesButton;
ViewHolder(View v){
super(v);
this.routeTextView = v.findViewById(R.id.route);
this.destinationTextView = v.findViewById(R.id.destination);
this.originTextView = v.findViewById(R.id.origin);
this.addFavouritesButton = v.findViewById(R.id.addToFavourites);
addFavouritesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String route = routeTextView.getText().toString();
System.out.println("clicked");
System.out.println(route);
//addToFavourites(route);
}
});
}
#NonNull
#Override
public FavouritesAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int i) {
View view = LayoutInflater.from(context).inflate(R.layout.favourite_card, parent, false);
return new FavouritesAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull FavouritesAdapter.ViewHolder viewHolder, int i) {
BusRoute bus = favourites.get(i);
viewHolder.originTextView.setText(String.valueOf(bus.getOrigin()));
viewHolder.destinationTextView.setText(String.valueOf(bus.getDestination()));
viewHolder.routeTextView.setText(String.valueOf(bus.getRoute()));
}
public FavouritesAdapter(ArrayList<BusRoute> favourites, Context context){
this.context = context;
this.favourites = favourites;
searchList = new ArrayList<>(favourites);
}
#Override
public int getItemCount() {
System.out.println(favourites);
return favourites.size();
}
#Override
public Filter getFilter() {
return favouriteFilter;
}
private Filter favouriteFilter = new Filter(){
#Override
protected FilterResults performFiltering(CharSequence constraint) {
System.out.println("filter results");
List<BusRoute> filteredList = new ArrayList<>();
if(constraint==null || constraint.length()==0){
filteredList.addAll(searchList);
}else{
String filterPattern = constraint.toString().toLowerCase().trim();
for(BusRoute br : searchList){
if(br.getRoute().toLowerCase().contains(filterPattern)){
filteredList.add(br);
}else{
System.out.println("nothing here");
}
}
}
System.out.println("set filter results");
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
favourites.clear();
favourites.addAll((List)results.values);
notifyDataSetChanged();
}
};
}
I just want to have a filterable search bar but cannot get it working! I'd appreciate any help at all!
In publish results method. Don't clear your array list. That is the reason for empty data
Try this
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String query = charSequence.toString();
List<String> filtered = new ArrayList<>();
if (query.isEmpty()) {
filtered = items;
} else {
for (String movie : items) {
if (movie.toLowerCase().contains(query.toLowerCase())) {
filtered.add(movie);
}
}
}
FilterResults results = new FilterResults();
results.count = filtered.size();
results.values = filtered;
return results;
}
I am creating an app I using search view in fragment to search recycler view ArrayList data but below method not showing the result
Not show my filter result in recycler view
How to show filter result in recycle view in the fragment.
anyone tell me what changes below code to fix this problem
please help me
Fragment
import in.getagf.pickuplines.Model.dataAdapter;
import in.getagf.pickuplines.Model.dataItem;
/**
* A simple {#link Fragment} subclass.
*/
public class LatestFragment extends Fragment {
private View myView;
private DatabaseReference RootRef, AdsRef;
private AdView adView;
private RecyclerView mRecyclerView;
dataAdapter mDataAdapter;
private RecyclerView.LayoutManager mDataLayoutManager;
public LatestFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
myView = inflater.inflate(R.layout.fragment_latest, container, false);
RootRef = FirebaseDatabase.getInstance().getReference().child("App_Data");
AdsRef = FirebaseDatabase.getInstance().getReference().child("Apps Link").child("AdsUnitID");
mRecyclerView = (RecyclerView) myView.findViewById(R.id.latest_recyclerView);
mDataLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mDataLayoutManager);
mDataAdapter = new dataAdapter(getDataSetLines(), getActivity());
mRecyclerView.setAdapter(mDataAdapter);
getResult.clear();
// offlinedata();
receiverData();
return myView;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.home, menu);
MenuItem item = menu.findItem(R.id.action_search);
SearchView sv = (SearchView) MenuItemCompat.getActionView(item);
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String newtext) {
mDataAdapter.getFilter().filter(newtext);
return false;
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle item selection
switch (item.getItemId()) {
case R.id.action_search:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void receiverData()
{
RootRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
if (dataSnapshot.exists() && !dataSnapshot.child("category").getValue().toString().equals("Good Night"))
{
String Lines = dataSnapshot.child("lines").getValue().toString();
String Pic = dataSnapshot.child("pic").getValue().toString();
String visite_id = dataSnapshot.getKey();
dataItem obj = new dataItem(visite_id, Lines, Pic);
getResult.add(obj);
mDataAdapter.notifyDataSetChanged();
}
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
AdsRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
String fB_Latest = dataSnapshot.child("fB_Latest").getValue(String.class);
// Facebook Banner Ads
adView = new AdView(getActivity(), fB_Latest, AdSize.BANNER_HEIGHT_50);
LinearLayout adContainer = (LinearLayout) myView.findViewById(R.id.latest_facebook_ads);
adContainer.addView(adView);
adView.loadAd();
// end
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public void onDestroy() {
if (adView != null) {
adView.destroy();
}
super.onDestroy();
}
private ArrayList<dataItem> getResult = new ArrayList<dataItem>();
private List<dataItem> getDataSetLines() {
return getResult;
}
}
dataAdapter
/**
* Created by Vinay Singh on 16/02/2019.
*/
public class dataAdapter extends RecyclerView.Adapter<DataViewHolders>
implements Filterable {
private List<dataItem> myList;
private List<dataItem> myListFull;
private Context context;
public dataAdapter(List<dataItem> myList, Context context) {
this.myList = myList;
this.context = context;
myListFull = new ArrayList<>(myList);
}
#Override
public DataViewHolders onCreateViewHolder(ViewGroup viewGroup, int position) {
View layoutView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_view, null, false);
RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layoutView.setLayoutParams(lp);
DataViewHolders rcv = new DataViewHolders(layoutView);
return rcv;
}
#Override
public void onBindViewHolder(DataViewHolders holder, int position) {
String lines = myList.get(position).getLines();
holder.mLines.setText(myList.get(position).getLines());
holder.mVisit_id.setText(myList.get(position).getVisite_id());
if (myList.get(position).getPic().equals("default")) {
Picasso.get().load(R.drawable.app_logo).into(holder.mImage);
}else if (myList.get(position).getPic().equals("Funny"))
{
Picasso.get().load(R.drawable.funny).into(holder.mImage);
}
else if (myList.get(position).getPic().equals("Romantic"))
{
Picasso.get().load(R.drawable.romantic).into(holder.mImage);
}
else if (myList.get(position).getPic().equals("Chat Tips"))
{
Picasso.get().load(R.drawable.chat).into(holder.mImage);
}
else if (myList.get(position).getPic().equals("Good Morning"))
{
Picasso.get().load(R.drawable.goodmorning).into(holder.mImage);
}
else if (myList.get(position).getPic().equals("Motivation"))
{
Picasso.get().load(R.drawable.motivation).into(holder.mImage);
}
else if (myList.get(position).getPic().equals("Shayri"))
{
Picasso.get().load(R.drawable.shayari).into(holder.mImage);
}
else if (myList.get(position).getPic().equals("WhatsApp"))
{
Picasso.get().load(R.drawable.whatsapp).into(holder.mImage);
}
else if (myList.get(position).getPic().equals("Jokes"))
{
Picasso.get().load(R.drawable.jokes).into(holder.mImage);
}
else if (myList.get(position).getPic().equals("Good Night"))
{
Picasso.get().load(R.drawable.goodnight).into(holder.mImage);
}
else if (myList.get(position).getPic().equals("Chatting"))
{
Picasso.get().load(R.drawable.chatting).into(holder.mImage);
}
else
{
Picasso.get().load(R.drawable.app_logo).into(holder.mImage);
}
}
#Override
public int getItemCount() {
return this.myList.size();
}
#Override
public Filter getFilter() {
return myListFilter;
}
private Filter myListFilter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String charString = constraint.toString();
if (charString.isEmpty())
{
myListFull = myList;
}
else
{
List<dataItem> filteredList = new ArrayList<>();
for (dataItem item : myListFull)
{
if (item.getLines().contains(charString)){
filteredList.add(item);
}
}
myListFull = filteredList;
}
FilterResults results = new FilterResults();
results.values = myListFull;
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
myList.clear();
myList.addAll((List) results.values);
notifyDataSetChanged();
}
};
}
List<dataItem> filteredList = new ArrayList<>();
for (dataItem item : myList) // myListFull wrong
{
if (item.getLines().contains(charString)){
filteredList.add(item);
}
}
myListFull = filteredList;
First Remove this code in your fragment
private ArrayList<dataItem> getResult = new ArrayList<dataItem>();
private List<dataItem> getDataSetLines() {
return getResult;
}
}
and intialized ArrayList in above of onCreateView method and change this code in onCreateView method
mDataAdapter = new dataAdapter(getResult, getContext());
Now add this code in your Adapter
List<dataItem> filteredList = new ArrayList<>();
for (dataItem item : myList) // myListFull wrong
{
if (item.getLines().contains(charString)){
filteredList.add(item);
}
}
myListFull = filteredList;
In your myListFull ArrayList to not add data of myList.
I hope this can help You!
Thank You.
My app cannot get the right position to perform the task that user choose from ContextMenu.
MainActivity.java
public class Main3Activity extends AppCompatActivity {
private RecyclerView recyclerView;
private List<foodmodel> result;
private foodadapter adapter;
private FirebaseDatabase database;
private DatabaseReference ref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
database = FirebaseDatabase.getInstance();
ref = database.getReference("Food");
result = new ArrayList<>();
recyclerView = (RecyclerView)findViewById(R.id.food_list);
recyclerView.setHasFixedSize(true);
LinearLayoutManager lim = new LinearLayoutManager(this);
lim.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(lim);
adapter = new foodadapter(result);
recyclerView.setAdapter(adapter);
updateList();
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId())
{
case 0:
removeFood(item.getItemId());
break;
case 1:
changeFood(item.getItemId());
break;
}
return super.onContextItemSelected(item);
}
private void updateList()
{
ref.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
result.add(dataSnapshot.getValue(foodmodel.class));
adapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
foodmodel food = dataSnapshot.getValue(foodmodel.class);
int index = getItemIndex(food);
result.set(index,food);
adapter.notifyItemChanged(index);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
foodmodel food = dataSnapshot.getValue(foodmodel.class);
int index = getItemIndex(food);
result.remove(index);
adapter.notifyItemRemoved(index);
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private int getItemIndex(foodmodel food){
int index = -1;
for(int i = 0; i < result.size();i++)
{
if (result.get(i).key.equals(food.key))
{
index = i;
break;
}
}
return index;
}
private void removeFood(int pos){
foodmodel food = result.get(pos);
String key = food.getKey();
food.u_time="remove";
Map<String,Object> foodValue = food.toMap();
Map<String,Object> newFood = new HashMap<>();
newFood.put(key,foodValue);
ref.updateChildren(newFood);
}
private void changeFood(int pos){
foodmodel food = result.get(pos);
food.u_time="change";
Map<String,Object> foodValue = food.toMap();
Map<String,Object> newFood = new HashMap<>();
newFood.put(food.key,foodValue);
ref.updateChildren(newFood);
}
}
foodadapter.java
public class foodadapter extends RecyclerView.Adapter<foodadapter.foodviewholder> {
private List<foodmodel>list;
public foodadapter(List<foodmodel> list) {
this.list = list;
}
#Override
public foodviewholder onCreateViewHolder(ViewGroup parent, int viewType) {
return new foodviewholder(LayoutInflater.from(parent.getContext()).inflate(R.layout.view_item,parent,false));
}
#Override
public void onBindViewHolder(foodviewholder holder, int position) {
foodmodel food = list.get(position);
holder.txtname.setText(food.u_food);
holder.txtdate.setText(food.u_date);
holder.txttime.setText(food.u_time);
}
#Override
public int getItemCount() {
return list.size();
}
public class foodviewholder extends RecyclerView.ViewHolder implements OnCreateContextMenuListener {
TextView txtname,txtdate,txttime;
Button btn;
public foodviewholder(View itemView) {
super(itemView);
txtname = (TextView)itemView.findViewById(R.id.text_food);
txtdate = (TextView)itemView.findViewById(R.id.text_date);
txttime = (TextView)itemView.findViewById(R.id.text_time);
btn = (Button)itemView.findViewById(R.id.btntest);
itemView.setOnCreateContextMenuListener(this);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.add(0, 0, 0, "Delete");
menu.add(0, 1, 0, "Change");
}
}
}
foomodel.java
public class foodmodel {
String u_food,u_date,u_time,key;
public foodmodel(){}
public foodmodel(String u_food,String u_date,String u_time, String key) {
this.u_food = u_food;
this.u_date = u_date;
this.u_time = u_time;
this.key = key;
}
public Map<String,Object> toMap(){
HashMap<String,Object> result = new HashMap<>();
result.put("u_food",u_food);
result.put("u_time",u_time);
result.put("u_date",u_date);
result.put("key",key);
return result;
}
public String getU_food() {
return u_food;
}
public void setU_food(String u_food) {
this.u_food = u_food;
}
public String getU_date() {
return u_date;
}
public void setU_date(String u_date) {
this.u_date = u_date;
}
public String getU_time() {
return u_time;
}
public void setU_time(String u_time) {
this.u_time = u_time;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
}
The flow of the app supposed like
display recyclerview that retrieve from Firebases
user choose the item from the list
contextmenu pop up
user choose delete or change
if delete, then the u_time of food becomes "remove"
if change, then the u_time of food becomes "change"
the step from 1-4 works fine. but after that the app cannot get position to perform task correctly.
For example, if user choose "delete" on third item, but the first item will be changed. After that, user choose "change" on forth item, the second item changed. Is there any problem of my code?
Replace your code like :
MainActivity.java
public class Main3Activity extends AppCompatActivity {
private RecyclerView recyclerView;
private List<foodmodel> result;
private foodadapter adapter;
private FirebaseDatabase database;
private DatabaseReference ref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
database = FirebaseDatabase.getInstance();
ref = database.getReference("Food");
result = new ArrayList<>();
recyclerView = (RecyclerView)findViewById(R.id.food_list);
recyclerView.setHasFixedSize(true);
LinearLayoutManager lim = new LinearLayoutManager(this);
lim.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(lim);
adapter = new foodadapter(result);
recyclerView.setAdapter(adapter);
updateList();
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId())
{
case 0:
if(adapter.curPos>-1){
removeFood(adapter.curPos);
}
break;
case 1:
if(adapter.curPos>-1){
changeFood(adapter.curPos);
}
break;
}
return super.onContextItemSelected(item);
}
private void updateList()
{
ref.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
result.add(dataSnapshot.getValue(foodmodel.class));
adapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
foodmodel food = dataSnapshot.getValue(foodmodel.class);
int index = getItemIndex(food);
result.set(index,food);
adapter.notifyItemChanged(index);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
foodmodel food = dataSnapshot.getValue(foodmodel.class);
int index = getItemIndex(food);
result.remove(index);
adapter.notifyItemRemoved(index);
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private int getItemIndex(foodmodel food){
int index = -1;
for(int i = 0; i < result.size();i++)
{
if (result.get(i).key.equals(food.key))
{
index = i;
break;
}
}
return index;
}
private void removeFood(int pos){
foodmodel food = result.get(pos);
String key = food.getKey();
food.u_time="remove";
Map<String,Object> foodValue = food.toMap();
Map<String,Object> newFood = new HashMap<>();
newFood.put(key,foodValue);
ref.updateChildren(newFood);
}
private void changeFood(int pos){
foodmodel food = result.get(pos);
food.u_time="change";
Map<String,Object> foodValue = food.toMap();
Map<String,Object> newFood = new HashMap<>();
newFood.put(food.key,foodValue);
ref.updateChildren(newFood);
}
}
foodadapter.java
public class foodadapter extends RecyclerView.Adapter<foodadapter.foodviewholder> {
private List<foodmodel>list;
public int curPos=-1;
public foodadapter(List<foodmodel> list) {
this.list = list;
}
#Override
public foodviewholder onCreateViewHolder(ViewGroup parent, int viewType) {
return new foodviewholder(LayoutInflater.from(parent.getContext()).inflate(R.layout.view_item,parent,false));
}
#Override
public void onBindViewHolder(foodviewholder holder, int position) {
foodmodel food = list.get(position);
holder.txtname.setText(food.u_food);
holder.txtdate.setText(food.u_date);
holder.txttime.setText(food.u_time);
}
#Override
public int getItemCount() {
return list.size();
}
public class foodviewholder extends RecyclerView.ViewHolder implements OnCreateContextMenuListener {
TextView txtname,txtdate,txttime;
Button btn;
public foodviewholder(View itemView) {
super(itemView);
txtname = (TextView)itemView.findViewById(R.id.text_food);
txtdate = (TextView)itemView.findViewById(R.id.text_date);
txttime = (TextView)itemView.findViewById(R.id.text_time);
btn = (Button)itemView.findViewById(R.id.btntest);
itemView.setOnCreateContextMenuListener(this);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
curPos=getAdapterPosition();
}});
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.add(0, 0, 0, "Delete");
menu.add(0, 1, 0, "Change");
}
}
}
I have an adapter class where I am able to load all video from Firebase. But the problem is I can't load both, image and video in one RecyclerView
See what I have done:
I am using toro library to auto play video if your wondering and ExoPlayer to play video
This is my adapter class
public class MainFeedAdapter extends RecyclerView.Adapter<TestAdapter.MyViewHolder> {
private static final String TAG = "MainfeedAdapter";
private List<Photo> moviesList;
private DatabaseReference mReference;
private Context mContext;
private String currentUsername = "";
private int mLayoutResource;
private LayoutInflater mInflater;
private Photo photo;
private MyViewHolder mHolder;
public class MyViewHolder extends RecyclerView.ViewHolder implements ToroPlayer{
static final int LAYOUT_RES = R.layout.main_list;
private ExoPlayerViewHelper helper;
private CircleImageView profile_image;
//private String likeString;
private TextView username,time,caption,likes,comment,stars;
private SquareImageView image;
private LikeButton mHeart,Star;
private UserAccountSettings userAccountSettings = new UserAccountSettings();
private User user = new User();
private StringBuilder users;
private String mLIkeString;
private String mStarString;
private boolean likeByCurrentUSer;
private boolean starbycurrentuser;
private DatabaseReference mNotification;
private ImageView commentBubble;
private Uri mediaUri;
#BindView(R.id.main_post_image2)
PlayerView playerView;
private CardView video;
public MyViewHolder(View view) {
super(view);
profile_image = (CircleImageView)view.findViewById(R.id.post_profile_photo);
username = (TextView) view.findViewById(R.id.main_username);
time = (TextView) view.findViewById(R.id.main_image_time_posted);
caption = (TextView) view.findViewById(R.id.main_image_caption);
likes = (TextView) view.findViewById(R.id.main_likes);
comment = (TextView) view.findViewById(R.id.main_showcomments);
image = (SquareImageView) view.findViewById(R.id.main_post_image);
mHeart = (LikeButton) view.findViewById(R.id.main_heart);
Star = (LikeButton) view.findViewById(R.id.main_star);
stars= (TextView)view.findViewById(R.id.stars);
commentBubble = (ImageView)view.findViewById(R.id.main_comments) ;
mNotification = FirebaseDatabase.getInstance().getReference().child("notification");
mReference = FirebaseDatabase.getInstance().getReference();
ButterKnife.bind(this, itemView);
video = (CardView)view.findViewById(R.id.video_posts);
}
#NonNull
#Override
public View getPlayerView() {
return playerView;
}
#NonNull
#Override
public PlaybackInfo getCurrentPlaybackInfo() {
return helper != null ? helper.getLatestPlaybackInfo() : new PlaybackInfo();
}
#Override
public void initialize(#NonNull Container container, #Nullable PlaybackInfo playbackInfo) {
if (helper == null) {
helper = new SimpleExoPlayerViewHelper(container, this, mediaUri);
}
helper.initialize(playbackInfo);
}
// called from Adapter to setup the media
void bind( Uri item, List<Photo> payloads) {
if (item != null) {
mediaUri = item;
}else {
video.setVisibility(View.GONE);
}
}
#Override
public void play() {
if (helper != null) helper.play();
}
#Override
public void pause() {
if (helper != null) helper.pause();
}
#Override
public boolean isPlaying() {
return helper != null && helper.isPlaying();
}
#Override
public void release() {
if (helper != null) {
helper.release();
helper = null;
}
}
#Override
public boolean wantsToPlay() {
return ToroUtil.visibleAreaOffset(this, itemView.getParent()) >= 0.85;
}
#Override
public int getPlayerOrder() {
return getAdapterPosition();
}
#Override
public void onSettled(Container container) {
}
}
public TestAdapter(List<Photo> moviesList) {
this.moviesList = moviesList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.main_list, parent, false);
mContext = parent.getContext();
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
photo = moviesList.get(position);
mHolder = holder;
holder.users = new StringBuilder();
getCurrentUsername();
getLikesString(mHolder);
getStarString(mHolder);
holder.bind(Uri.parse(photo.getVideo_path()),moviesList);
//get the profile image and username
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference
.child(mContext.getString(R.string.dbname_user_account_settings))
.orderByChild(mContext.getString(R.string.field_user_id))
.equalTo(getItem(position).getUser_id());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
// currentUsername = singleSnapshot.getValue(UserAccountSettings.class).getUsername();
Log.d(TAG, "onDataChange: found user: "
+ singleSnapshot.getValue(UserAccountSettings.class).getUsername());
holder.username.setText(singleSnapshot.getValue(UserAccountSettings.class).getUsername());
holder.username.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating to profile of: " +
holder.user.getUsername());
Intent intent = new Intent(mContext, Profile_Activity.class);
intent.putExtra(mContext.getString(R.string.calling_activity),
mContext.getString(R.string.home_activity));
intent.putExtra(mContext.getString(R.string.intent_user), holder.user);
mContext.startActivity(intent);
}
});
imageLoader.displayImage(singleSnapshot.getValue(UserAccountSettings.class).getProfile_photo(),
holder.profile_image);
holder.profile_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating to profile of: " +
holder.user.getUsername());
Intent intent = new Intent(mContext, Profile_Activity.class);
intent.putExtra(mContext.getString(R.string.calling_activity),
mContext.getString(R.string.home_activity));
intent.putExtra(mContext.getString(R.string.intent_user), holder.user);
mContext.startActivity(intent);
}
});
holder.userAccountSettings = singleSnapshot.getValue(UserAccountSettings.class);
holder.comment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((HomeActivity)mContext).onCommentThreadSelected(getItem(position),mContext.getString(R.string.home_activity));
//another thing?
((HomeActivity)mContext).hideLayout();
}
});
holder.commentBubble.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((HomeActivity)mContext).onCommentThreadSelected(getItem(position),mContext.getString(R.string.home_activity));
//another thing?
((HomeActivity)mContext).hideLayout();
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Query userQuery = mReference
.child(mContext.getString(R.string.dbname_users))
.orderByChild(mContext.getString(R.string.field_user_id))
.equalTo(getItem(position).getUser_id());
userQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
Log.d(TAG, "onDataChange: found user: " +
singleSnapshot.getValue(User.class).getUsername());
holder.user = singleSnapshot.getValue(User.class);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private boolean rechedendoflist(int position){
return position == getItemCount() -1;\
}
#Override
public int getItemCount() {
return moviesList.size();
}
public Photo getItem(int position) {
return moviesList.get(position);
}
private void getCurrentUsername(){
Log.d(TAG, "getCurrentUser: ");
Log.d(TAG, "getCurrentUsername: retrieving user account settings");
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference
.child(mContext.getString(R.string.dbname_users))
.orderByChild(mContext.getString(R.string.field_user_id))
.equalTo(FirebaseAuth.getInstance().getCurrentUser().getUid());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
currentUsername = singleSnapshot.getValue(UserAccountSettings.class).getUsername();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Please help me guys!. Thanks in Advance!.
TheRecyclerView has ability to show items in multiple types.
In your case you can define two ViewType. one for Images and another for Videos.
Search about RecyclerView with multiple view types.
Take a look at here and this.
Also here is a question and answers about it.
I have a problem with my application. Actually, I'm totally stuck. I have a list of countries with implemented clicklistener and searchview. In a situation when I click on a given element without searching the list, everything displays correctly and shows information about a given country. But when I search the list and click on the element, the application goes to the information about the random country. I dont know why this is happening. I have no error. Only a warning:
W/IInputConnectionWrapper: finishComposingText on inactive InputConnection
MainActivity
public static final String EXTRA_COUNTRY_NAME = "country_name";
public static final String EXTRA_COUNTRY_REGION = "country_region";
public static final String EXTRA_COUNTRY_NATIVE_NAME = "country_nativename";
public static final String EXTRA_COUNTRY_NAME_LANGUGES= "country_namelanguages";
private RecyclerView recyclerView;
private DataAdapter dataAdapter;
private List<ModelJsona> dataArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
}
private void initViews(){
recyclerView=(RecyclerView) findViewById(R.id.card_recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
loadJSON();
}
private void loadJSON(){
dataArrayList = new ArrayList<>();
Retrofit retrofit=new Retrofit.Builder().baseUrl("https://restcountries.eu/").addConverterFactory(GsonConverterFactory.create()).build();
RequestInterface requestInterface=retrofit.create(RequestInterface.class);
Call<List<ModelJsona>> call= requestInterface.getJSON();
call.enqueue(new Callback<List<ModelJsona>>() {
#Override
public void onResponse(Call<List<ModelJsona>> call, Response<List<ModelJsona>> response) {
dataArrayList = response.body();
dataAdapter=new DataAdapter(getApplicationContext(),dataArrayList);
recyclerView.setAdapter(dataAdapter);
dataAdapter.setOnitemClickListener(MainActivity.this);
}
#Override
public void onFailure(Call<List<ModelJsona>> call, Throwable t) {
Log.e("Error",t.getMessage());
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
MenuItem search = menu.findItem(R.id.search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(search);
search(searchView);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
private void search(SearchView searchView) {
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
dataAdapter.getFilter().filter(newText);
if (dataAdapter !=null)dataAdapter.getFilter().filter(newText);
return true;
}
});
}
#Override
public void onItemClick(int position) {
Intent detailsIntent = new Intent(this,Details.class);
ModelJsona click = dataArrayList.get(position);
detailsIntent.putExtra(EXTRA_COUNTRY_NAME,click.getName());
detailsIntent.putExtra(EXTRA_COUNTRY_REGION,click.getRegion());
detailsIntent.putExtra(EXTRA_COUNTRY_NATIVE_NAME,click.getNativeName());
detailsIntent.putExtra(EXTRA_COUNTRY_NAME_LANGUGES,click.getLanguages().get(0).getName());
startActivity(detailsIntent);
}
}
DataAdapter
private Context context;
private List<ModelJsona> dataList;
private List<ModelJsona> filtr;
private OnitemClickListener mListener;
public interface OnitemClickListener {
void onItemClick (int position);
}
public void setOnitemClickListener (OnitemClickListener listener)
{
mListener=listener;
}
public DataAdapter(Context context, List<ModelJsona> dataList) {
this.context = context;
this.dataList = dataList;
this.filtr= dataList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_row, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.country_name.setText(filtr.get(position).getName());
holder.country_region.setText(filtr.get(position).getRegion());
holder.country_nativename.setText(filtr.get(position).getNativeName());
holder.country_languagename.setText(filtr.get(position).getLanguages().get(0).getName());
}
#Override
public int getItemCount() {
return filtr.size();
}
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
if (charString.isEmpty()) {
filtr = dataList;
} else {
ArrayList<ModelJsona> listadoprzeszukiwan = new ArrayList<>();
for (ModelJsona wyszukiwarka : dataList) {
if (
wyszukiwarka.getName().contains(charString) ||
wyszukiwarka.getName().toLowerCase().contains(charString) ||
wyszukiwarka.getRegion().contains(charString) ||
wyszukiwarka.getRegion().toLowerCase().contains(charString) ||
wyszukiwarka.getNativeName().contains(charString) ||
wyszukiwarka.getNativeName().toLowerCase().contains(charString) ||
wyszukiwarka.getTopLevelDomain().contains(charString))
{
listadoprzeszukiwan.add(wyszukiwarka);
}
}
filtr = listadoprzeszukiwan;
}
FilterResults wynikiszukania = new FilterResults();
wynikiszukania.values = filtr;
return wynikiszukania;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults wynikiszukania) {
filtr = (ArrayList<ModelJsona>) wynikiszukania.values;
notifyDataSetChanged();
}
};
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView country_name, country_region, country_languagename,country_nativename;
public MyViewHolder(View itemView) {
super(itemView);
country_name = (TextView) itemView.findViewById(R.id.country_name);
country_region = (TextView) itemView.findViewById(R.id.country_region);
country_nativename = (TextView) itemView.findViewById(R.id.country_nativename);
country_languagename= (TextView) itemView.findViewById(R.id.country_languagename);
itemView.setOnClickListener((new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListener !=null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
mListener.onItemClick(position);
}
}
}
}));
}
}
}
i see that you get the position in filter list refer to different object with same position value in dataList because after filtering filter list become reference to result but still dataList hold all data.
you can replace itemView click listner by this:
itemView.setOnClickListener((new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListener !=null){
int position = getAdapterPosition();
String name = filtr.get(position).getName();
for (int i=0 ; i <dataList.size() ; i++ ){
if(name.equals(dataList.get(i).getName()){
position = i;
break;
}
}
if (position != RecyclerView.NO_POSITION) {
mListener.onItemClick(position);
}
}
}
}));