Android pass jsonObject to another activity by clicking on recyclerview - android

I'm making an app in Android.
I'm getting JSON data containing pokemons name from URL(http://kerast.com/pokemon/pokemons.json) using retrofit. The names and types display in a recyclerView and after clicking on one another Activity opens and display attack, defense and moves.
So far I've been able to open a new activity but have no idea how to pass the object. I suppose there is no need to reload the json by re writing the same code twice for each activity ?
Here is my class :
public class Pokemon {
private String name;
private String type;
private Integer attack;
private Integer defense;
private Integer evolveLevel;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setType(String type) {
this.type = type;
}
public String getType() {
return type;
}
public Integer getattack() { return attack; }
public Integer getdefense() { return defense; }
public Integer getEvolveLevel() { return evolveLevel; }
}
My DataAdpater :
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> implements Filterable {
private ArrayList<Pokemon> mArrayList;
private ArrayList<Pokemon> mFilteredList;
public DataAdapter(ArrayList<Pokemon> arrayList) {
mArrayList = arrayList;
mFilteredList = arrayList;
}
#Override
public DataAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_row, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(DataAdapter.ViewHolder viewHolder, int i) {
viewHolder.tv_name.setText(mFilteredList.get(i).getName());
viewHolder.tv_version.setText(mFilteredList.get(i).getName());
viewHolder.tv_api_level.setText(mFilteredList.get(i).getType());
}
#Override
public int getItemCount() {
return mFilteredList.size();
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
if (charString.isEmpty()) {
mFilteredList = mArrayList;
} else {
ArrayList<Pokemon> filteredList = new ArrayList<>();
for (Pokemon marraylist : mArrayList) {
if (marraylist.getName().toLowerCase().contains(charString) || marraylist.getType().toLowerCase().contains(charString)) {
filteredList.add(marraylist);
}
}
mFilteredList = filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = mFilteredList;
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
mFilteredList = (ArrayList<Pokemon>) filterResults.values;
notifyDataSetChanged();
}
};
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView tv_name,tv_version,tv_api_level;
public ViewHolder(View view) {
super(view);
tv_name = (TextView)view.findViewById(R.id.tv_name);
tv_version = (TextView)view.findViewById(R.id.tv_version);
tv_api_level = (TextView)view.findViewById(R.id.tv_api_level);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext(), Main2Activity.class);
intent.putExtra("attack", Pokemon);
view.getContext().startActivity(intent);
}
});
}
}
}
And finally my MainActivity :
public class MainActivity extends AppCompatActivity {
public static final String BASE_URL = "http://kerast.com";
private RecyclerView mRecyclerView;
private ArrayList<Pokemon> mArrayList;
private DataAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
initViews();
loadJSON();
}
private void initViews(){
mRecyclerView = (RecyclerView)findViewById(R.id.card_recycler_view);
mRecyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(layoutManager);
}
private void loadJSON(){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
RequestInterface request = retrofit.create(RequestInterface.class);
Call<JSONResponse> call = request.getJSON();
call.enqueue(new Callback<JSONResponse>() {
#Override
public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
JSONResponse jsonResponse = response.body();
mArrayList = new ArrayList<>(Arrays.asList(jsonResponse.getPokemons()));
mAdapter = new DataAdapter(mArrayList);
mRecyclerView.setAdapter(mAdapter);
}
#Override
public void onFailure(Call<JSONResponse> call, Throwable t) {
Log.d("Error",t.getMessage());
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
MenuItem search = menu.findItem(R.id.search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(search);
search(searchView);
return true;
}
private void search(SearchView searchView) {
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
mAdapter.getFilter().filter(newText);
return true;
}
});
}
}
So how can I get only Attack Defense and evolveLevel to be display in the second Activity ?

implement the Serializable interface Pokemon implements Serializable
and
then you can pass object instances in the intent extra using the putExtra()
//send :
intent.putExtra("Pokemon", obj);
//retrieve :
getIntent().getSerializableExtra("MyClass");

Well answer by akshay is correct but i think this will better way to do it. We can use Parcelable class instead of Serializable.
Refer the following link for difference b/w parcelable and serializale
and to create a POJO class paracelable i use online creator.
Rest is the same
//Sending data
intent.putExtra("String name", object);
//Receving end
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
Pokemon pokemon = (Pokemon) bundle.getParcelable("String name")
}

Related

Only get to retrieve last datasets in firebase through recyclerview

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
}

Recyclerview Search Filter not working android

My title is coming from retrofit.when I type anything in searchview it doesnt show any result/Suggestion when typed. here is the ss ---> enter image description here
im referring this blog --> https://velmm.com/android-recyclerview-search-filter-example/
help will be appreciated...thanks in advance
Search activity:
public class Search extends AppCompatActivity {
SearchView searchView;
RecyclerView recyclerView;
SearchAdapter slAdapter;
List<StartLearning.SlModel> movieList;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
searchView=findViewById(R.id.searchView);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
searchView.onActionViewExpanded();
searchView.setIconified(true);
recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
slAdapter = new SearchAdapter();
recyclerView.setAdapter(slAdapter);
movieList = new ArrayList<>();
SLApiSevice service = SLApiClient.getRetrofitInstance().create(SLApiSevice.class);
retrofit2.Call<List<StartLearning.SlModel>> call = service.getMySlmodel();
call.enqueue(new Callback<List<StartLearning.SlModel>>() {
#Override
public void onResponse(retrofit2.Call<List<StartLearning.SlModel>> call, Response<List<StartLearning.SlModel>> response) {
movieList = response.body();
Log.d("TAG","Response = "+movieList);
slAdapter.setMovieList(getApplicationContext(),movieList);
}
#Override
public void onFailure(retrofit2.Call<List<StartLearning.SlModel>> call, Throwable t) {
Log.d("TAG","Response = "+t.toString());
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu1, menu);
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);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
slAdapter.getFilter().filter(query);
return false;
}
#Override
public boolean onQueryTextChange(String query) {
slAdapter.getFilter().filter(query);
return false;
}
});
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId() ==android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
super.onBackPressed();
}}
Search Adapter
public class SearchAdapter extends RecyclerView.Adapter<SearchAdapter.CustomViewHolder> implements Filterable {
List<StartLearning.SlModel> Slmdel;
List<StartLearning.SlModel> Slmdel1;
Context context;
public SearchAdapter() {
}
public void setMovieList(Context context, final List<StartLearning.SlModel> movieList){
this.context = context;
if(this.Slmdel == null){
this.Slmdel = movieList;
this.Slmdel1 = movieList;
notifyItemChanged(0, Slmdel1.size());
} else {
final DiffUtil.DiffResult result = DiffUtil.calculateDiff(new DiffUtil.Callback() {
#Override
public int getOldListSize() {
return SearchAdapter.this.Slmdel.size();
}
#Override
public int getNewListSize() {
return movieList.size();
}
#Override
public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
return SearchAdapter.this.Slmdel.get(oldItemPosition).getTitle() == movieList.get(newItemPosition).getTitle();
}
#Override
public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {
StartLearning.SlModel newMovie = SearchAdapter.this.Slmdel.get(oldItemPosition);
StartLearning.SlModel oldMovie = movieList.get(newItemPosition);
return newMovie.getTitle() == oldMovie.getTitle() ;
}
});
this.Slmdel = movieList;
this.Slmdel1 = movieList;
result.dispatchUpdatesTo(this);
}
}
public SearchAdapter(Context context,List<StartLearning.SlModel> employees) {
this.Slmdel = employees;
this.context=context;
}
#Override
public SearchAdapter.CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.startlearning_item, parent, false);
return new SearchAdapter.CustomViewHolder(itemView);
}
#Override
public void onBindViewHolder(SearchAdapter.CustomViewHolder holder, int position) {
holder.textView.setText(String.valueOf(position+1)+". ");
holder.employeeName.setText(Slmdel.get(position).getTitle());
}
#Override
public int getItemCount() {
if(Slmdel != null){
return Slmdel1.size();
} else {
return 0;
}
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
if (charString.isEmpty()) {
Slmdel1 = Slmdel;
} else {
List<StartLearning.SlModel> filteredList = new ArrayList<>();
for (StartLearning.SlModel movie : Slmdel) {
if (movie.getTitle().toLowerCase().contains(charString.toLowerCase())) {
filteredList.add(movie);
}
}
Slmdel1 = filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = Slmdel1;
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
Slmdel1 = (ArrayList<StartLearning.SlModel>) filterResults.values;
notifyDataSetChanged();
}
};
}
public class CustomViewHolder extends RecyclerView.ViewHolder {
public TextView employeeName;
TextView textView;
public CustomViewHolder(View view) {
super(view);
employeeName = (TextView) view.findViewById(R.id.Sl2);
textView=view.findViewById(R.id.Sl1);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, NextSLactivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("title", Slmdel.get(getAdapterPosition()).getTitle());
intent.putExtra("idSLnext", Slmdel.get(getAdapterPosition()).getId());
//Log.e("ashwini",WAmdel.get(getAdapterPosition()).getId());
context.startActivity(intent);
}
});
}
}
}
List:
public class SlModel
{
#SerializedName("id")
#Expose
private String id;
#SerializedName("title")
#Expose
private String title;
public SlModel(String id, String title) {
this.id = id;
this.title = title;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Override
public String toString() {
return "SlModel{" +
"title='" + title + '\'' +
'}';
}
}}
package zon.searchview.com;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.viewHolder> implements Filterable {
Context context;
ArrayList<ItemModel> arrayList,arrayListFiltered;
public CustomAdapter(Context context, ArrayList<ItemModel> arrayList) {
this.context = context;
this.arrayList = arrayList;
this.arrayListFiltered = arrayList;
}
#Override
public viewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(context).inflate(R.layout.item_list, viewGroup, false);
return new viewHolder(view);
}
#Override
public void onBindViewHolder(viewHolder viewHolder, int position) {
viewHolder.name.setText(arrayListFiltered.get(position).getName());
viewHolder.image.setImageResource(arrayListFiltered.get(position).getImage());
}
#Override
public int getItemCount() {
return arrayListFiltered.size();
}
public class viewHolder extends RecyclerView.ViewHolder {
TextView name;
ImageView image;
public viewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.name);
image = (ImageView) itemView.findViewById(R.id.image);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context,arrayListFiltered.get(getAdapterPosition()).getName(),Toast.LENGTH_LONG).show();
}
});
}
}
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
ArrayList<ItemModel> arrayListFilter = new ArrayList<ItemModel>();
if(constraint == null|| constraint.length() == 0) {
results.count = arrayList.size();
results.values = arrayList;
} else {
for (ItemModel itemModel : arrayList) {
if(itemModel.getName().toLowerCase().contains(constraint.toString().toLowerCase())) {
arrayListFilter.add(itemModel);
}
}
results.count = arrayListFilter.size();
results.values = arrayListFilter;
}
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
arrayListFiltered = (ArrayList<ItemModel>) results.values;
notifyDataSetChanged();
if(arrayListFiltered.size() == 0) {
Toast.makeText(context, "Not Found", Toast.LENGTH_LONG).show();
}
}
};
return filter;`enter code here`
}
}
For more visit this:- https://www.11zon.com/zon/android/filter-recyclerview-with-searchview.php

how to search arraylist data in recyclerview in fragment

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.

SearchView for RecyclerView not working

I have implemented searchview filter for recyclerview in fragment like below but when I am entering the query in searchview nothing happens .
My Fragment class: DiscussionForum.java
public class DiscussionForum extends Fragment implements ForumAdapter.ForumAdapterListener {
private TextView socname;
private EditText messageinput;
private SearchView search;
// SearchView searchView;
private FloatingActionButton messagesend;
ProgressDialog progressDialog;
private static final String TAG = "Discussion Forum";
private RecyclerView recyclerView;
private List<ForumData> forumlist;
private ForumAdapter mAdapter;
private OnFragmentInteractionListener mListener;
private LinearLayout list;
private String sendurl, geturl;
public DiscussionForum() {
// Required empty public constructor
}
public static DiscussionForum newInstance(String param1, String param2) {
DiscussionForum fragment = new DiscussionForum();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_discussion_forum, container, false);
onButtonPressed("Discussion Forum");
forumlist = new ArrayList<>();
recyclerView = view.findViewById(R.id.listviewforum);
list = view.findViewById(R.id.list);
search = view.findViewById(R.id.search);
int resId = R.anim.layout_animation_fall_down;
LayoutAnimationController animation = AnimationUtils.loadLayoutAnimation(getContext(), resId);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setLayoutAnimation(animation);
mAdapter = new ForumAdapter(getContext(), forumlist, this);
progressDialog = new ProgressDialog(getContext());
progressDialog.setCancelable(false);
geturl = "";
fetchforumdata(getActivity().getIntent().getStringExtra("id"));
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
mAdapter.getFilter().filter(newText);
return true;
}
});
return view;
}
private void fetchforumdata(final String id1) {
progressDialog.setMessage("Loading...");
showDialog();
StringRequest request = new StringRequest(Request.Method.GET,
geturl + id1,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Log.d("tag2","id"+id1);
Log.d(TAG, "Response Prop: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("errors");
if (!error) {
JSONObject dataobj = jObj.getJSONObject("data");
JSONArray ticketarray = dataobj.getJSONArray("result");
if (ticketarray.length() == 0) {
list.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
List<ForumData> items = new Gson().fromJson(ticketarray.toString(), new TypeToken<List<ForumData>>() {
}.getType());
forumlist.clear();
forumlist.addAll(items);
recyclerView.setAdapter(mAdapter);
}
} else {
// String errorMsg = jObj.getString("error_msg");
Toast.makeText(getContext(),
"Try again or report an issue", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error in getting json
Log.e(TAG, "Error: " + error.getMessage());
Toast.makeText(getContext(), "Error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
hideDialog();
}
});
MyApplication.getInstance().addToRequestQueue(request);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(String title) {
if (mListener != null) {
mListener.onFragmentInteraction(title);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
private void showDialog() {
if (!progressDialog.isShowing())
progressDialog.show();
}
private void hideDialog() {
if (progressDialog.isShowing())
progressDialog.dismiss();
}
#Override
public void onDocumentSelected(String id) {
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(String title);
}}
My Adapter Class :ForumAdapter
public class ForumAdapter extends RecyclerView.Adapter<ForumAdapter.MyViewHolder> implements Filterable {
private Context context;
private List<ForumData> ticketlist;
private List<ForumData> filterlist;
private ForumAdapterListener listener;
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView username,createdat,forummessage,flatno,category,likes,subcount;
ImageView edit;
public MyViewHolder(View view) {
super(view);
username=view.findViewById(R.id.user_name2);
createdat=view.findViewById(R.id.date2);
edit = view.findViewById(R.id.profile_icon2);
forummessage=view.findViewById(R.id.forum_message);
flatno=view.findViewById(R.id.flat_no);
category=view.findViewById(R.id.category);
likes=view.findViewById(R.id.likes_data);
subcount=view.findViewById(R.id.count_data);
}
}
public ForumAdapter(Context context, List<ForumData> ticketlist, ForumAdapterListener listener) {
this.context = context;
this.listener = listener;
this.ticketlist = ticketlist;
this.filterlist=ticketlist;
}
#Override
public ForumAdapter.MyViewHolder onCreateViewHolder( ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.discussion_forum_item, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder( ForumAdapter.MyViewHolder holder, int position) {
final ForumData contact = ticketlist.get(position);
holder.username.setText(contact.getUsername());
holder.flatno.setText(contact.getFlattitle());
holder.forummessage.setText(contact.getMessage());
holder.createdat.setText(contact.getCreated_at());
holder.category.setText(contact.getCategory());
holder.likes.setText(contact.getLikes());
holder.subcount.setText(contact.getSubcount());
Glide.with(context)
.load(url+".jpg")
.apply(new RequestOptions().circleCrop().placeholder(R.drawable.man).error(R.drawable.man))
.into(holder.edit);
}
});
}
#Override
public int getItemCount() {
return ticketlist.size();
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
if (charString.isEmpty()) {
filterlist = ticketlist;
} else {
List<ForumData> filteredList = new ArrayList<>();
for (ForumData row : ticketlist) {
// name match condition. this might differ depending on your requirement
// here we are looking for name or phone number match
if (row.getUsername().toLowerCase().contains(charString.toLowerCase()) || row.getCategory().contains(charSequence)) {
filteredList.add(row);
}
}
filterlist = filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = filterlist;
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filterlist = (ArrayList<ForumData>) results.values;
notifyDataSetChanged();
}
}
;
}
public interface ForumAdapterListener {
void onDocumentSelected(String contact);
}}
I have gone through many solutions like here , here ,here
But I am unable to figure out what is wrong with my code . Please help me figure out where the exact problem is.
There are multiple issues with your Adapter implementation. If I understand your code correctly you want to keep a reference to a list of unfiltered items (List<ForumData> ticketlist) and filter this list and display the filtered results (List<ForumData> filterlist) on the screen.
Firstly, you want to display filterlist on the screen so in onBindViewHolder() and getItemCount() you need to use filterlist instead of ticketlist.
Secondly, you want to ensure that ticketlist stays unchanged so that all future searches are on the same content. To do this you will have to replace all filterlist = ticketlist; with filterlist = new ArrayList<>(ticketlist); (in your contstructor and in performFiltering()) to avoid changing the contents of ticketlist.
This should make your code functional at least. I suggest you watch this video on Java and objects and references as well.
Another way to go is to filter the data and and refresh the recyclerview's adapter in the onQueryTextChange :
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
}
#Override
public boolean onQueryTextChange(String newText) {
ArrayList< ForumData > filteredData = new ArrayList<>();
for (ForumData forumData : data) {
if (forumData..getUsername().toLowerCase().contains(newText.toLowerCase())) {
filteredData.add(forumData);
}
}
adapter = new ForumAdapter(data, getContext() , this);
recyclerView.setAdapter(adapter);
return true ;
}
})

Wrong position after filter

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);
}
}
}
}));

Categories

Resources