i want to make a filter search function to my jsonobject array in recyclerview
i tried the getfilter in my adapter and pass it to my add_detail
but it gives me force close when i type a text in my app_detail activity
heres my app_detail.java :
public class app_detail extends AppCompatActivity implements PemrogramanAdapter.OnItemClickListener {
TextView nametxt;
ImageView imageView,listimageview;
private RecyclerView mRecyclerView;
private List<Object> mRecyclerViewItems = new ArrayList<>();
private SearchView searchView;
PemrogramanAdapter pemrogramanAdapters;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_app_detail);
nametxt = (TextView) findViewById(R.id.list_app_text_detail);
imageView = (ImageView) findViewById(R.id.list_app_image_detail);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setTitle("test");
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view1);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
PemrogramanAdapter pemrogramanAdapter = new PemrogramanAdapter(this,mRecyclerViewItems);
mRecyclerView.setAdapter(pemrogramanAdapter);
pemrogramanAdapter.setmListener(app_detail.this);
tambahMenuItemDariJson();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu,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 s) {
pemrogramanAdapters.getFilter().filter(s);
return false;
}
#Override
public boolean onQueryTextChange(String s) {
pemrogramanAdapters.getFilter().filter(s);
return false;
}
});
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == R.id.action_search)
return true;
if(id == android.R.id.home)
this.finish();
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
if(!searchView.isIconified())
{
searchView.setIconified(true);
return;
}
super.onBackPressed();
Animatoo.animateZoom(app_detail.this);
}
private void tambahMenuItemDariJson() {
try{
String jsonDataString = readJsonDataDariFile();
JSONArray menuItemsJsonArray = new JSONArray(jsonDataString);
for(int i = 0; i<menuItemsJsonArray.length(); ++i){
JSONObject menuItemObject =menuItemsJsonArray.getJSONObject(i);
String txt_id_app = menuItemObject.getString("id_app");
String txt_title = menuItemObject.getString("masalah");
String txt_id = menuItemObject.getString("id");
String txt_keterangan = menuItemObject.getString("ket");
String txt_langkah = menuItemObject.getString("langkah");
item item = new item(txt_id_app,txt_id,txt_title,txt_keterangan,txt_langkah);
mRecyclerViewItems.add(item);
}
} catch (IOException | JSONException exception){
Log.e(guidesoftware.class.getName(),"Tidak BISA BUKA FILE JSON!",exception);
}
}
private String readJsonDataDariFile() throws IOException {
InputStream inputStream = null;
StringBuilder builder = new StringBuilder();
//menentukan konten
Intent intent = this.getIntent();
int position = intent.getExtras().getInt("POS_KEY");
int jsonlocation = 0;
//kondisi per lokasi
if(position == 0){
jsonlocation = R.raw.pemrograman_octave;
}else if(position == 1){
jsonlocation = R.raw.pemrograman_netbeans;
}else if(position == 2){
jsonlocation = R.raw.pemrograman_devcpp;
}else if(position == 3){
jsonlocation = R.raw.pemrograman_notepad;
}
try {
String jsonDataString = null;
inputStream = getResources().openRawResource(jsonlocation);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
while ((jsonDataString = bufferedReader.readLine()) != null){
builder.append(jsonDataString);
}
}finally {
if(inputStream != null){
inputStream.close();
}
}
return new String(builder);
}
#Override
public void onItemSelected(int position) {
Intent detailIntent = new Intent(this,fortest.class);
item clickeditem = (item) mRecyclerViewItems.get(position);
detailIntent.putExtra(EXTRA_MASALAH,clickeditem.getMasalah());
detailIntent.putExtra(EXTRA_KETERANGAN,clickeditem.getKet());
detailIntent.putExtra(EXTRA_LANGKAH,clickeditem.getLangkah());
startActivity(detailIntent);
}}
and here is my pemrogramanAdapter.java :
public class PemrogramanAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements Filterable{
private static final int MENU_ITEM_VIEW_TYPE = 0;
private final Context context;
private final List<Object> recyclerViewItem;
private List<Object> filterrecyclerViewItem;
private OnItemClickListener mListener;
public PemrogramanAdapter(Context context, List<Object> recyclerViewItem) {
this.context = context;
this.recyclerViewItem = recyclerViewItem;
this.filterrecyclerViewItem = recyclerViewItem;
}
public void setmListener(OnItemClickListener mListener) {
this.mListener = mListener;
}
public class MenuItemViewHolder extends RecyclerView.ViewHolder{
public TextView txt_title,txt_keterangan;
public ImageView txt_image;
public MenuItemViewHolder(View view){
super(view);
txt_title = (TextView)view.findViewById(R.id.title);
txt_keterangan = (TextView)view.findViewById(R.id.isi);
txt_image = (ImageView)view.findViewById(R.id.avatar);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListener != null){
int position = getAdapterPosition();
if(position != RecyclerView.NO_POSITION){
mListener.onItemSelected(position);
}
}
}
});
}
}
#Override
public int getItemCount() {
return recyclerViewItem.size();
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
switch (i){
case MENU_ITEM_VIEW_TYPE:
default:
View menuItemLayoutView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_layout,viewGroup,false);
return new MenuItemViewHolder(menuItemLayoutView);
}
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
int viewType = getItemViewType(position);
switch (viewType){
case MENU_ITEM_VIEW_TYPE:
default:
MenuItemViewHolder menuItemViewHolder = (MenuItemViewHolder) holder;
item menuItem = (item) recyclerViewItem.get(position);
menuItemViewHolder.txt_title.setText(menuItem.getMasalah());
menuItemViewHolder.txt_keterangan.setText(menuItem.getKet());
menuItemViewHolder.txt_image.setImageResource(R.drawable.pemrog_netbeans);
}
}
public interface OnItemClickListener{
void onItemSelected (int position);
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String searchString = charSequence.toString();
if(searchString.isEmpty())
filterrecyclerViewItem = recyclerViewItem; //for se kembalikan item yg di search ke semula
else{
List<Object> resultList = new ArrayList<>();
for(Object data : recyclerViewItem)
{
item item = new item();
if(item.getMasalah().toLowerCase().contains(searchString.toLowerCase() ))
resultList.add(item);
}
filterrecyclerViewItem = resultList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = filterResults;
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults filterResults) {
filterrecyclerViewItem = (ArrayList<Object>)filterResults.values;
notifyDataSetChanged();
}
};
}
}
i want to make the filter search works on my jsonObject in app_detail.java
Related
In my app I have implemented a recyclerview with cardview to show the list of the employee inside a company. Now I want to implement a serch option by which user can search with the name of the employee. I have read related document in website about it. I wrote a code to implement a serch option. But unfortunately I can see the search option and I can write it but it cannot detect the name from the list. I do not know what is the problem inside my code. Here is my adapter class where I implment Filterable mehtod
public class MyColleaguesAdapter extends RecyclerView.Adapter<MyColleaguesAdapter.ColleagueHolder> implements Filterable {
private static final String TAG = "MyColleaguesAdapter";
protected List<MyColleageModel> colleagueObject;
protected List<MyColleageModel> filteredcolleague;
private Context context;
public MyColleaguesAdapter(List<MyColleageModel> colleagueObject, Context context) {
this.colleagueObject = colleagueObject;
this.filteredcolleague=colleagueObject;
this.context = context;
}
#Override
public ColleagueHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext())
.inflate(R.layout.colleage_row_layout,parent,false);
return new ColleagueHolder(view);
}
#Override
public void onBindViewHolder(ColleagueHolder holder, int position) {
final MyColleageModel myColleague=colleagueObject.get(position);
holder.name.setText(myColleague.getName());
holder.company.setText(myColleague.getCompany());
holder.title.setText(myColleague.getTitle());
holder.cardView.setTag(position);
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int pos = (int)view.getTag();
openDetailActivity(myColleague.getMobile(),myColleague.getMail(), myColleague.getName(),
myColleague.getCompany(), myColleague.getDepartment(), myColleague.getTitle());
}
});
}
#Override
public int getItemCount() {
return colleagueObject.size();
}
//open activity
private void openDetailActivity(String...details)
{
Intent i=new Intent(context,DetailMyColleague.class);
i.putExtra("mail",details[1]);
........
context.startActivity(i);
}
#Override
public Filter getFilter() {
return new Filter() {
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredcolleague = (List<MyColleageModel>) results.values;
MyColleaguesAdapter.this.notifyDataSetChanged();
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
List<MyColleageModel> filteredResults = null;
if (constraint.length() == 0) {
filteredResults = colleagueObject;
} else {
filteredResults = getFilteredResults(constraint.toString().toLowerCase());
}
FilterResults results = new FilterResults();
results.values = filteredResults;
return results;
}
};
}
protected List<MyColleageModel> getFilteredResults(String constraint) {
List<MyColleageModel> results = new ArrayList<>();
for (MyColleageModel item : colleagueObject) {
if (item.getName().toLowerCase().contains(constraint)) {
results.add(item);
Log.d( TAG,"value is here "+item.getName());
}
}
return results;
}
public class ColleagueHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public CardView cardView;
public TextView name;
public TextView company;
public TextView title;
public ColleagueHolder(View itemView) {
super(itemView);
name=(TextView) itemView.findViewById(R.id.colleague_name);
company=(TextView)itemView.findViewById(R.id.company_name);
title=(TextView) itemView.findViewById(R.id.job_role);
cardView=(CardView)itemView.findViewById(R.id.cvSingleUser);
}
}
Here is my MainActivity
public class MyColleaguesPage extends AppCompatActivity implements SearchView.OnQueryTextListener{
private RecyclerView recyclerView;
private CardView cardView;
private MyColleaguesAdapter adapter;
private List<MyColleageModel> colleagueObject;
InputStream is;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mycolleagues_layout);
// Showing and Enabling clicks on the Home/Up button
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
cardView=(CardView)findViewById(R.id.cvSingleUser);
recyclerView = (RecyclerView) findViewById(R.id.colleagues_recycler);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(MyColleaguesPage.this);
recyclerView.setLayoutManager(layoutManager);
new JSONTask().execute();
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
List<MyColleageModel> filteredModelList = filter(colleagueObject, newText);
if (filteredModelList.size() > 0) {
//myPhotosAdapter.setFilter(filteredModelList);
return true;
} else {
Toast.makeText(MyColleaguesPage.this, "Not Found", Toast.LENGTH_SHORT).show();
return false;
}
}
public class JSONTask extends AsyncTask<String, String, List<MyColleageModel>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected List<MyColleageModel> doInBackground(String... params) {
colleagueObject = new ArrayList<MyColleageModel>();
try {
//withou Gson
JSONObject obj = new JSONObject(loadJSONFromAsset());
JSONArray m_jArry = obj.getJSONArray("contacts");
MyColleageModel my_clg;
for (int i = 0; i < m_jArry.length(); i++) {
JSONObject jo_inside = m_jArry.getJSONObject(i);
String val1 = jo_inside.getString("mobile");
String val2 = jo_inside.getString("mail");
String val3 = jo_inside.getString("name");
String val4 = jo_inside.optString("company");
String val5 = jo_inside.optString("department");
String val6 = jo_inside.optString("title");
my_clg = new MyColleageModel(val1, val2, val3, val4, val5, val6);
colleagueObject.add(my_clg);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(final List<MyColleageModel> result) {
super.onPostExecute(result);
adapter = new MyColleaguesAdapter(colleagueObject, getApplicationContext());
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
private String loadJSONFromAsset() {
....
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.recyclerviewmenu, menu);
final MenuItem search = menu.findItem(R.id.search);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(search);
searchView.setOnQueryTextListener(this);
return true;
}
private List<MyColleageModel> filter(List<MyColleageModel> models, String query) {
query = query.toLowerCase();
final List<MyColleageModel> filteredModelList = new ArrayList<>();
for (MyColleageModel model : models) {
final String text = model.getName().toLowerCase().toString();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
// arraylist in your adapter
adapter = new MyColleaguesAdapter(colleagueObject, getApplicationContext());
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
return filteredModelList;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
}
And this is my recyclerviewmenu.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" tools:context="myColleagues.MyColleaguesPage">
<item
android:id="#+id/search"
android:icon="#drawable/ic_search"
android:title="Search"
app:showAsAction="ifRoom|collapseActionView"
app:actionViewClass="android.support.v7.widget.SearchView"/>
</menu>
I am not getting the error inside my code.
follow this stpes
step 1 implements SearchView.OnQueryTextListener in youractivity
step 2 in onCreateOptionsMenu write below code
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_album_search, menu);
final MenuItem item = menu.findItem(R.id.menu_search_album);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(this);
return true;
}
step 3 write this in onQueryTextChange() method
#Override
public boolean onQueryTextChange(String newText) {
List<MyColleageModel> filteredModelList = filter(data_fieldses, newText);
if (filteredModelList.size() > 0) {
//myPhotosAdapter.setFilter(filteredModelList);
return true;
} else {
Toast.makeText(MyPhotosActivity.this, "Not Found", Toast.LENGTH_SHORT).show();
return false;
}
}
step 4
private List<MyColleageModel> filter(List<MyColleageModel> models, String query) {
query = query.toLowerCase();
final List<MyColleageModel> filteredModelList = new ArrayList<>();
for (MyColleageModel model : models) {
final String text = model.getImagename().toLowerCase().toString();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
// arraylist in your adapter
myPhotosAdapter = new MyPhotosAdapter( MyPhotosActivity.this, (ArrayList<MyColleageModel>) filteredModelList);
recyclerViewMyPhotos.setLayoutManager(new GridLayoutManager(MyPhotosActivity.this, 2));
recyclerViewMyPhotos.setAdapter(myPhotosAdapter);
myPhotosAdapter.notifyDataSetChanged();
return filteredModelList;
}
ask me in case of any query
IMO you missed setNotifyDatachaged() in onPostExecute() try above code
public class MyColleaguesPage extends AppCompatActivity{
private RecyclerView recyclerView;
private MyColleaguesAdapter adapter;
private List<MyColleageModel> colleagueObject;
InputStream is;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mycolleagues_layout);
// Showing and Enabling clicks on the Home/Up button
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
recyclerView = (RecyclerView) findViewById(R.id.colleagues_recycler);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(MyColleaguesPage.this);
recyclerView.setLayoutManager(layoutManager);
adapter = new MyColleaguesAdapter(colleagueObject, getApplicationContext());
recyclerView.setAdapter(adapter);
new JSONTask().execute();
}
public class JSONTask extends AsyncTask<String, String, List<MyColleageModel>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected List<MyColleageModel> doInBackground(String... params) {
colleagueObject = new ArrayList<MyColleageModel>();
try {
//withou Gson
JSONObject obj = new JSONObject(loadJSONFromAsset());
JSONArray m_jArry = obj.getJSONArray("contacts");
// ArrayList<HashMap<String, String>> formList = new ArrayList<HashMap<String, String>>();
// HashMap<String, String> m_li;
MyColleageModel my_clg;
for (int i = 0; i < m_jArry.length(); i++) {
JSONObject jo_inside = m_jArry.getJSONObject(i);
//my_clg=new MyColleageModel();
String val1 = jo_inside.getString("mobile");
String val2 = jo_inside.getString("mail");
String val3 = jo_inside.getString("name");
String val4 = jo_inside.optString("company");
String val5 = jo_inside.optString("department");
String val6 = jo_inside.optString("title");
my_clg = new MyColleageModel(val1, val2, val3, val4, val5, val6);
colleagueObject.add(my_clg);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(final List<MyColleageModel> result) {
super.onPostExecute(result);
adapter.notifyDataSetChanged();
}
}
private String loadJSONFromAsset() {
...........
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.recyclerviewmenu, 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) {
adapter.getFilter().filter(newText);
return true;
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
I Have implemented the ListView with Custom Adopter class and Multiple check box selection . Its working fine . After that I have given search the name in ListView. If I checked row item then I search the name in search , Search positioned was changed . Kindly help me to fix this.
Model Class
public class FullUser {
String name=null;
String id=null;
boolean checked;
public FullUser(String name, String id,boolean checked){
this.name=name;
this.id = id;
this.checked = checked;
}
public String getName(){
return this.name;
}
public void setName(String name){
this.name = name;
}
public String getId(){
return this.id;
}
public void setId(String id){
this.id = id;
}
public Boolean getChecked(){
return this.checked;
}
public void setChecked(Boolean checked){
this.checked = checked;
}
#Override
public String toString() {
return this.name;
}
}
Adapter Class
public class FullUserAdapter extends ArrayAdapter<FullUser> {
private ArrayList<FullUser> originalList;
private ArrayList<FullUser> fullUsers;
private SubjectFilter filter;
public FullUserAdapter(Context context, int resource, ArrayList<FullUser> fullUsers) {
super(context, resource, fullUsers);
this.fullUsers = new ArrayList<FullUser>();
this.fullUsers.addAll(fullUsers);
this.originalList = new ArrayList<FullUser>();
this.originalList.addAll(fullUsers);
}
#Override
public int getCount() {
return fullUsers.size();
}
#Override
public FullUser getItem(int position) {
return fullUsers.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public Filter getFilter() {
if (filter == null){
filter = new SubjectFilter();
}
return filter;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Log.v("UserConvertView", String.valueOf(position));
View row;
if (convertView == null) {
row = LayoutInflater.from(getContext()).inflate(R.layout.list_row_with_checkbox, parent, false);
}else{
row = convertView;
}
holder = new ViewHolder();
holder.name_view = (TextView) row.findViewById(R.id.nameText);
holder.firstchar_view = (TextView) row.findViewById(R.id.first_char);
holder.groupid = (TextView) row.findViewById(R.id.rowid);
holder.checkBox =(CheckBox) row.findViewById(R.id.cbBox);
final FullUser group =getItem(position);
holder.groupid.setText(group.getId());
//holder.checkBox.setChecked(checkedHolder[position]);
String communityname_text = group.getName();
holder.name_view.setText(group.getName());
String firstchar = communityname_text.substring(0, 1);
holder.firstchar_view.setText(firstchar);
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked == true)
group.setChecked(true);
else
group.setChecked(false);
}
});
row.setTag(holder);
return row;
}
private class SubjectFilter extends Filter
{
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults result = new FilterResults();
if(constraint != null && constraint.toString().length() > 0)
{
constraint = constraint.toString().toLowerCase();
ArrayList<FullUser> filteredItems = new ArrayList<FullUser>();
for(int i = 0, l = fullUsers.size(); i < l; i++)
{
FullUser group = fullUsers.get(i);
if(group.toString().toLowerCase().contains(constraint)) {
FullUser grouplistss = new FullUser(group.getName(),group.id,group.getChecked());
filteredItems.add(grouplistss);
}
}
result.count = filteredItems.size();
result.values = filteredItems;
}
else
{
synchronized(this)
{
result.values = originalList;
result.count = originalList.size();
}
}
return result;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,Filter.FilterResults results) {
if(results.count > 0) {
fullUsers = (ArrayList<FullUser>)results.values;
notifyDataSetChanged();
clear();
for(int i = 0, l = fullUsers.size(); i < l; i++)
add(fullUsers.get(i));
} else {
notifyDataSetInvalidated();
}
}
}
private class ViewHolder {
TextView name_view;
TextView firstchar_view;
TextView groupid;
CheckBox checkBox;
}
}
Thanks in advance.
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
group.setChecked(true);
int pos = originalList.indexOf(group)
originalList.get(pos).setChecked(true);
fullUsers.get(position).setChecked(true);
}else{
group.setChecked(false);
int pos = originalList.indexOf(group)
originalList.get(pos).setChecked(true);
fullUsers.get(position).setChecked(false);
}
}
update your adapter use SparseBooleanArray
public class FullUserAdapter extends ArrayAdapter<FullUser> {
private ArrayList<FullUser> originalList;
private ArrayList<FullUser> fullUsers;
private SubjectFilter filter;
SparseBooleanArray booleanArray ;
public FullUserAdapter(Context context, int resource, ArrayList<FullUser> fullUsers) {
super(context, resource, fullUsers);
this.fullUsers = new ArrayList<FullUser>();
this.fullUsers.addAll(fullUsers);
this.originalList = new ArrayList<FullUser>();
this.originalList.addAll(fullUsers);
booleanArray = new SparseBooleanArray();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
.
.
.
final FullUser group =getItem(position);
holder.groupid.setText(group.getId());
holder.checkBox.setOnCheckedChangeListener(null);
holder.checkBox.setChecked(booleanArray.get(group.getId().hashCode(),false));
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
booleanArray.put(group.getId().hashCode(), isChecked);
}
});
.
.
.
return row;
}
public ArrayList<FullUser> getSelectedItems() {
ArrayList<FullUser> list = new ArrayList<>();
for(FullUser group:fullUsers){
if(booleanArray.get(group.getId().hashCode(), false)){
list.add(group);
}
}
return list;
};
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".dashboard.VoterListActivity">
<ProgressBar
android:id="#+id/reqprogressbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:visibility="gone" />
<ListView
android:id="#+id/voter_lv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/btn_show_me"
android:divider="#null"/>
<Button
android:id="#+id/btn_show_me"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="5dp"
android:background="#drawable/n_btn"
android:text="#string/add_family_numbers"
android:visibility="gone"
android:textColor="#ffffff"
android:textSize="20sp" />
</RelativeLayout>
Java Code
public Class Actvity extends AppCompatActivity {
ProgressBar progressBar;
ListView listView;
VoterDao voterDao;
String Token, Userid, Appid, Deviceid;
MenuItem searchview;
VoterListAdapter adapter;
String pid;
VoterDatum friend;
String value;
CheckBox mCheckBox;
Button btn_show_me;
ArrayList<VoterDatum> friends;
ListView1Adapter adapter1;
VoterDatum Model;
StringBuilder stringBuilder;
String name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_voter_list);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(R.string.voter_list);
stringBuilder = new StringBuilder();
Token = Util.getStringFromSP(this, "token");
Userid = Util.getStringFromSP(this, "user_id");
Appid = Util.getStringFromSP(this, "app_id");
Deviceid = Util.getStringFromSP(this, "device_id");
initViews();
getVoterData();
btn_show_me.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int i = 0;
if (friends.size() == i) { //do nothing
}
while (friends.size() > i) {
int count = friends.size();
Model = friends.get(i);
if (Model.isChecked()) {
Log.i("ListActivity", "here" + friends.get(i).getCitizenId());
stringBuilder.append("," + friends.get(i).getCitizenId());
name = stringBuilder.toString();
String joinedString = Model.getCitizenId().toString();
Log.d("ls", "" + name);
name = name.substring(1);
Log.d("fs", name);
sendToServer();
}
i++; // rise i
}
}
});
}
private void sendToServer() {
Intent intent = new Intent(VoterListActivity.this, AddFamilyNuberByVoterList.class);
intent.putParcelableArrayListExtra("CheckedList", friends);
startActivity(intent);
finish();
}
private void getVoterData() {
if (Util.isNetworkAvailable(this)) {
progressBar.setVisibility(View.VISIBLE);
SendRequestToServer();
} else {
progressBar.setVisibility(View.GONE);
Snackbar.make(listView, R.string.no_connection, Snackbar.LENGTH_SHORT).show();
return;
}
}
private void SendRequestToServer() {
try {
RegistrationApi api = ServiceGenerator.createService(RegistrationApi.class);
retrofit2.Call<VoterDao> call = api.togetVoters(Userid, Token, Appid, Deviceid);
call.enqueue(new Callback<VoterDao>() {
#Override
public void onResponse(Call<VoterDao> call, Response<VoterDao> response) {
if (response.isSuccessful()) {
voterDao = response.body();
if (voterDao.getAddData().getStatus().equals(1)) {
searchview.setVisible(true);
progressBar.setVisibility(View.GONE);
friends = (ArrayList<VoterDatum>) voterDao.getAddData().getData();
adapter1 = new ListView1Adapter(getApplicationContext(), R.layout.list_voter, friends);
listView.setAdapter(adapter1);
btn_show_me.setVisibility(View.VISIBLE);
} else {
searchview.setVisible(false);
progressBar.setVisibility(View.GONE);
Snackbar.make(listView, R.string.no_data_found, Snackbar.LENGTH_SHORT).show();
}
} else {
searchview.setVisible(false);
progressBar.setVisibility(View.GONE);
Snackbar.make(listView, R.string.no_data_found + response.message(), Snackbar.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<VoterDao> call, Throwable t) {
try {
searchview.setVisible(false);
progressBar.setVisibility(View.GONE);
Snackbar.make(listView, "" + t.getMessage(), Snackbar.LENGTH_SHORT).show();
Log.d("message", "" + t.getMessage());
System.out.println("onFAilureExecute" + t.getMessage());
if (t != null)
t.printStackTrace();
} catch (Throwable th) {
th.printStackTrace();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
private void initViews() {
progressBar = findViewById(R.id.reqprogressbar);
listView = findViewById(R.id.voter_lv);
btn_show_me = findViewById(R.id.btn_show_me);
}
#Override
public boolean onSupportNavigateUp() {
startActivity(new Intent(getApplicationContext(), DashboardActivity.class));
finish();
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
return true;
}
#Override
public void onBackPressed() {
startActivity(new Intent(getApplicationContext(), DashboardActivity.class));
finish();
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
searchview = menu.findItem(R.id.action_search);
final SearchView searchViewAndroidActionBar = (SearchView) MenuItemCompat.getActionView(searchview);
searchViewAndroidActionBar.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter1.getFilter().filter(newText);
return false;
}
});
View closeButton = searchViewAndroidActionBar.findViewById(android.support.v7.appcompat.R.id.search_close_btn);
closeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//handle click
searchViewAndroidActionBar.setIconified(true);
}
});
return super.onCreateOptionsMenu(menu);
}
#Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(LocalHelper.onAttach(base));
}
private class ListView1Adapter extends BaseAdapter {
ListView1Adapter.ViewHolder holder;
private Context activity;
private ArrayList<VoterDatum> Friends;
private ArrayList<VoterDatum> mList;
private final String TAG = ListViewAdapter.class.getSimpleName();
boolean[] checkedItems;
public ListView1Adapter(Context applicationContext, int list_voter, ArrayList<VoterDatum> list) {
this.activity = applicationContext;
this.Friends = list;
this.mList = list;
Log.i(TAG, "init adapter");
checkedItems = new boolean[mList.size()];
}
#Override
public int getCount() {
return mList.size();
}
#Override
public Object getItem(int position) {
return mList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
holder = null;
final int pos = position;
// inflate layout from xml
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
// If holder not exist then locate all view from UI file.
if (convertView == null) {
// inflate UI from XML file
convertView = inflater.inflate(R.layout.list_voter, parent, false);
// get all UI view
holder = new ListView1Adapter.ViewHolder(convertView);
// set tag for holder
convertView.setTag(holder);
} else {
// if holder created, get tag from view
holder = (ListView1Adapter.ViewHolder) convertView.getTag();
}
friend = mList.get(position);
String nameS = friend.getFirstname() + " " + friend.getLastname();
String namesS = friend.getVoterId();
String lname = friend.getLfname() + " " + friend.getLlastname();
//set Friend data to views
String Photo = friend.getPhoto();
if (Photo.isEmpty() || Photo == null) {
holder.image.setImageResource(R.mipmap.ic_launcher);
} else {
Picasso.with(activity).load(Photo).transform(new CircleTransform()).into(holder.image);
}
holder.name.setText(nameS);
holder.lanname.setText(lname);
holder.voterid_tv.setText(namesS);
holder.check.setChecked(friend.isChecked());
holder.check.setTag(friend);
holder.check.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
VoterDatum itemobj = (VoterDatum) cb.getTag();
if (mList.get(Integer.valueOf(pos)).isChecked()) {
cb.setSelected(false);
mList.get(Integer.valueOf(pos)).setIsChecked(false);
notifyDataSetChanged();
} else {
cb.setSelected(true);
mList.get(Integer.valueOf(pos)).setIsChecked(true);
notifyDataSetChanged();
}
}
});
return convertView;
}
private class ViewHolder {
private ImageView image;
private TextView name, lanname, voterid_tv;
private CheckBox check;
public ViewHolder(View v) {
image = v.findViewById(R.id.profile_iv);
name = (TextView) v.findViewById(R.id.name_tv);
lanname = (TextView) v.findViewById(R.id.desig_tv);
voterid_tv = (TextView) v.findViewById(R.id.voterid_tv);
check = (CheckBox) v.findViewById(R.id.chkEnable);
}
}
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
ArrayList<VoterDatum> filteredResults = null;
if (constraint.length() == 0) {
filteredResults = Friends;
} else {
filteredResults = (ArrayList<VoterDatum>) getFilteredResults(constraint.toString().toLowerCase());
}
results.values = filteredResults;
return results;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults results) {
mList = (ArrayList<VoterDatum>) results.values;
notifyDataSetChanged();
}
};
}
protected List<VoterDatum> getFilteredResults(String s) {
ArrayList<VoterDatum> results = new ArrayList<>();
for (VoterDatum item : Friends) {
String TotalSearch = item.getFirstname() + " " + item.getLastname();
if (TotalSearch.toLowerCase().contains(s) || item.getVoterId().toLowerCase().contains(s)) {
results.add(item);
}
}
return results;
}
public ArrayList<VoterDatum> getAllData() {
return mList;
}
}
}
Model Class
public class VoterDatum implements Parcelable {
#SerializedName("citizen_id")
#Expose
private String citizenId;
private boolean isChecked;
public static final Parcelable.Creator<VoterDatum> CREATOR = new Parcelable.Creator<VoterDatum>() {
public VoterDatum createFromParcel(Parcel in) {
return new VoterDatum(in);
}
public VoterDatum[] newArray(int size) {
return new VoterDatum[size];
}
};
public VoterDatum(Parcel in) {
this.citizenId = in.readString();
this.isChecked = in.readByte() != 0;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.citizenId);
dest.writeByte((byte) (this.isChecked ? 1 : 0));
}
public VoterDatum(String citizenId, boolean gender) {
this.citizenId = citizenId;
this.isChecked = false; // not selected when create
}
#SerializedName("status")
#Expose
private String status;
#SerializedName("firstname")
#Expose
private String firstname;
#SerializedName("lastname")
public boolean isChecked() {
return isChecked;
}
public void setIsChecked(boolean isChecked) {
this.isChecked = isChecked;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getCitizenId() {
return citizenId;
}
public void setCitizenId(String citizenId) {
this.citizenId = citizenId;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getLfname() {
return lfname;
}
public void setLfname(String lfname) {
this.lfname = lfname;
}
}
Get Data From Other Class
public class ACtivity extends AppCompatActivity implements View.OnClickListener {
String Mvoterid;
GPSTracker gps;
String Token, Userid, Deviceid, Appid, Language;
Button submit_btn;
ProgressBar progressBar;
AddFamilynumberbyvoterDao addFamilynumberbyvoterDao;
// ArrayList<VoterDatum> checkedList;
List<VoterDatum> checkedList;
LinearLayout container;
VoterDatum Model;
ListView list_item;
String join;
int position;
String userName;
String name;
StringBuilder stringBuilder;
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_family_nuber_by_voter_list);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(R.string.add_family_numbers);
VoterID = getIntent().getStringExtra("voterIDs");
stringBuilder= new StringBuilder();
checkedList = new ArrayList<VoterDatum>(); // initializing list
container = (LinearLayout) findViewById(R.id.layout);
getLocation();
initViews();
initListeners();
getDataFromIntent();
generateDataToContainerLayout();
}
#RequiresApi(api = Build.VERSION_CODES.O)
#SuppressLint("InflateParams")
private void generateDataToContainerLayout() {
int i = 0;
if (checkedList.size() == i) { //do nothing
}
while (checkedList.size() > i) {
int count = checkedList.size();
Model = checkedList.get(i);
if (Model.isChecked()) {
Log.i("ListActivity", "here" + checkedList.get(i).getCitizenId());
stringBuilder.append(","+checkedList.get(i).getCitizenId());
name=stringBuilder.toString();
String joinedString = Model.getCitizenId().toString();
Log.d("ls", "" + name);
name=name.substring(1);
Log.d("fs",name);
}
i++; // rise i
}
}
private void getDataFromIntent() {
checkedList = getIntent().getParcelableArrayListExtra("CheckedList");
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am getting this error-Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference
This is what i have done!
PeopleListFragment
**PeopleListFragment**
public class PeopleListFragment extends Fragment{
public static final String DISPLAY_URL = ServiceAPI.URL_CONTACTS;
private static final String TAG = "PeopleListActivity";
public static final boolean DEBUG = Constant.DEBUG;
private ProgressDialog progressDialog;
public PeopleAdapter adapter;
private GetAllPeopleTask mGetAllPeople = null;
private Intent intent;
public static ListView mContactlistView;
public PeopleListFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_people_list, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mContactlistView = (ListView) view.findViewById(R.id.people_list);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
List<People> contactList = new ArrayList<People>();
adapter = new PeopleAdapter(getActivity().getApplicationContext(),
R.layout.people_list_item, contactList);
mContactlistView.setAdapter(adapter);
mContactlistView.setTextFilterEnabled(true);
mContactlistView.setFastScrollEnabled(true);
mContactlistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String empId = String.valueOf(adapter.getItem(position).getEmployeeId());
String name = String.valueOf(adapter.getItem(position).getFirstName());
intent = new Intent(getActivity(),
PeopleDetailsActivity.class);
intent.putExtra("EmployeeId", empId);
intent.putExtra("name", name);
startActivity(intent);
}
});
startAsyncTask();
TextView textView = new TextView(getContext());
textView.setText("Empty");
mContactlistView.setEmptyView(textView);
}
public void startAsyncTask() {
mGetAllPeople = new GetAllPeopleTask();
mGetAllPeople.execute(DISPLAY_URL, "12345678");
}
public class GetAllPeopleTask extends AsyncTask<String, Void, List<People>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Loading");
progressDialog.show();
}
#Override
protected ArrayList<People> doInBackground(String... params) {
ArrayList<People> peopleList = new ArrayList<>();
try {
URL url = new URL(params[0]);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setReadTimeout(40000);
httpURLConnection.setConnectTimeout(50000);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Content-Type", "application/json");
httpURLConnection.setRequestProperty("Accept", "application/json");
httpURLConnection.setDoOutput(true);
JSONObject request = new JSONObject();
request.put("session", params[1]);
String bodyParams = request.toString();
if (DEBUG) {
Log.i(TAG, bodyParams);
}
httpURLConnection.setRequestProperty("Content-Length",
String.valueOf(bodyParams.getBytes().length));
DataOutputStream outputStream = new DataOutputStream(httpURLConnection.getOutputStream());
outputStream.writeBytes(bodyParams);
outputStream.flush();
outputStream.close();
httpURLConnection.connect();
if (httpURLConnection.getResponseCode() == 200) {
Log.i(TAG, "Success");
} else {
Log.i(TAG, "Error Code :" + httpURLConnection.getResponseCode());
}
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuilder builder = new StringBuilder();
while ((line = reader.readLine()) != null) {
builder.append(line);
}
Log.i(TAG, "Builder String : " + builder.toString());
JSONObject jsonObject = new JSONObject(builder.toString());
Log.i(TAG, "Response JSON : " + jsonObject.toString());
if (jsonObject.has("responseData")) {
JSONArray responseDataArr = jsonObject.optJSONArray("responseData");
for (int i = 0; i < responseDataArr.length(); i++) {
JSONObject peopleJSON = responseDataArr.optJSONObject(i);
People people = new People();
people.setEmployeeId(peopleJSON.optString("employeeId"));
people.setFirstName(peopleJSON.optString("firstName"));
people.setLastName(peopleJSON.optString("lastName"));
// Log.i("hebsiba ", "People first name" + people.getFirstName() + ", last name is " + people.getLastName()) ;
if((!people.getFirstName().isEmpty()) && (!people.getLastName().isEmpty())) {
peopleList.add(people);
}
if (DEBUG) {
Log.i(TAG, "People " + people.getEmployeeId());
}
}
}
} catch (IOException | JSONException e) {
Log.e(TAG, e.toString());
}
return peopleList;
}
#Override
protected void onPostExecute(List<People> people) {
super.onPostExecute(people);
Collections.sort(people, new Comparator<People>() {
#Override
public int compare(People lhs, People rhs) {
return lhs.getFirstName().compareToIgnoreCase(rhs.getFirstName());
}
});
adapter.addAll(people);
if (DEBUG) {
Log.i(TAG, adapter.getCount() + " ");
}
Log.v(TAG, String.valueOf(people.size()));
progressDialog.dismiss();
}
}
}
This is the PeopleAdapter
**PeopleAdapter**
public class PeopleAdapter extends ArrayAdapter<People> implements Filterable {
private PeopleListActivity activity;
private PeopleFilter peopleFilter;
private List<People> peopleList;
private List<People> filteredList;
public PeopleAdapter(Context applicationContext, int people_list_item, List<People> contactList) {
super(applicationContext, people_list_item, contactList);
filteredList = contactList;
getFilter();
}
#Override
public int getCount() {
return filteredList.size();
}
#Override
public People getItem(int i) {
return filteredList.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
People peopleList = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.people_list_item, null);
holder = new ViewHolder();
holder.firstName = (TextView) convertView.findViewById(R.id.firstName);
holder.lastName = (TextView) convertView.findViewById(R.id.lastName);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.firstName.setText(peopleList.getFirstName());
holder.lastName.setText(peopleList.getLastName());
return convertView;
}
/**
* Get custom filter
* #return filter
*/
#Override
public Filter getFilter() {
if (peopleFilter == null) {
peopleFilter = new PeopleFilter();
}
return peopleFilter;
}
static class ViewHolder {
TextView firstName;
TextView lastName;
}
private class PeopleFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if (constraint!=null && constraint.length()>0) {
ArrayList<People> tempList = new ArrayList<>();
// search content in friend list
for (People user : peopleList) {
if (user.getFirstName().toLowerCase().contains(constraint.toString().toLowerCase())) {
tempList.add(user);
}
}
filterResults.count = tempList.size();
filterResults.values = tempList;
} else {
filterResults.count = peopleList.size();
filterResults.values = peopleList;
}
return filterResults;
}
/**
* Notify about filtered list to ui
* #param constraint text
* #param results filtered result
*/
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, Filter.FilterResults results) {
filteredList = (ArrayList<People>) results.values;
notifyDataSetChanged();
}
}
}
And this is PeopleListActivity
**PeopleListActivity**
public class PeopleListActivity extends AppCompatActivity implements SearchView.OnQueryTextListener {
private PeopleListFragment fragment;
private FragmentManager displayFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.argb(255, 180, 110, 60));
}
setContentView(R.layout.activity_people);
Toolbar toolbar = (Toolbar) findViewById(R.id.people_toolbar);
setSupportActionBar(toolbar);
toolbar.setNavigationIcon(R.drawable.ic_back_arrow);
getSupportActionBar().setDisplayShowTitleEnabled(false);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(PeopleListActivity.this, NavigationActivity.class);
startActivity(intent);
}
});
displayFragment = getSupportFragmentManager();
fragment = new PeopleListFragment();
displayFragment.beginTransaction().add(R.id.people_fragment, fragment).commit();
if (savedInstanceState == null) {
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
SearchManager searchManager =(SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView =(SearchView) menu.findItem(R.id.search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
// searchView.setIconifiedByDefault(false);
searchView.setSubmitButtonEnabled(true);
searchView.setOnQueryTextListener(this);
return true;
// return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
PeopleAdapter peopleAdapter = (PeopleAdapter) PeopleListFragment.mContactlistView.getAdapter();
peopleAdapter.getFilter().filter(newText);
return true;
}
}
Could anyone help me with this..?
Assign some value to filteredList when you create the Adapter
Example:
public PeopleAdapter(Context applicationContext, int people_list_item, List<People> contactList) {
super(applicationContext, people_list_item, contactList);
filteredList = contactList;
getFilter();
}
filteredList is null when getCount() is called. Instantiate it first or make sure filteredList has some content.
I have used this solution to filter my RecyclerView. Using the solution I was able to get the result while typing. But when I clear the search widget I don't get the full list instead I get the empty RecyclerView.
This is how my result looks like.
https://imgur.com/nwyetEd
This is my Adapter
public class ContactsAdapter extends RecyclerView.Adapter<ContactViewHolder> {
private LayoutInflater inflater;
private ContactViewHolder viewHolder;
private ArrayList<Contact> contactsList = new ArrayList<>();
private VolleySingleton volleySingleton;
private ImageLoader imageLoader;
boolean fromMyContacts;
Context context;
public ContactsAdapter(Context context, boolean fromMyContacts){
inflater = LayoutInflater.from(context);
this.context = context;
volleySingleton = VolleySingleton.getsInstance();
imageLoader = volleySingleton.getImageLoader();
this.fromMyContacts = fromMyContacts;
}
public void setContactsList(ArrayList<Contact> contactsList){
this.contactsList = contactsList;
notifyItemRangeChanged(0, contactsList.size());
}
#Override
public ContactViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.contact_list, parent, false);
viewHolder = new ContactViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ContactViewHolder holder, int position) {
Contact current = contactsList.get(position);
viewHolder.name.setText(current.name);
viewHolder.phone.setText(current.phone);
viewHolder.city.setText(current.location + ", " + current.city);
if(fromMyContacts) {
if (current.verified) {
viewHolder.verified.setImageResource(R.drawable.ic_check_circle);
} else {
viewHolder.verified.setImageResource(R.drawable.ic_cancel);
}
}
String image_url = current.image_url;
if(!image_url.equals("null")){
Picasso.with(context).load(image_url).into(viewHolder.contactIcon);
}else{
viewHolder.contactIcon.setImageResource(R.drawable.contact_icon);
}
}
#Override
public int getItemCount() {
return contactsList.size();
}
public Contact removeItem(int position){
final Contact contacts = contactsList.remove(position);
notifyItemRemoved(position);
return contacts;
}
public void addItem(int position, Contact contactList){
contactsList.add(position, contactList);
notifyItemInserted(position);
}
public void moveItem(int fromPosition, int toPosition){
final Contact contacts = contactsList.remove(fromPosition);
contactsList.add(toPosition, contacts);
notifyItemMoved(fromPosition, toPosition);
}
public void animateTo(List<Contact> contacts){
applyAndAnimateRemovals(contacts);
applyAndAnimateAdditions(contacts);
applyAndAnimateMovedItems(contacts);
}
private void applyAndAnimateRemovals(List<Contact> newModels) {
for (int i = contactsList.size() - 1; i >= 0; i--) {
final Contact model = contactsList.get(i);
if (!newModels.contains(model)) {
removeItem(i);
}
}
}
private void applyAndAnimateAdditions(List<Contact> newModels) {
for (int i = 0, count = newModels.size(); i < count; i++) {
final Contact model = newModels.get(i);
if (!contactsList.contains(model)) {
addItem(i, model);
}
}
}
private void applyAndAnimateMovedItems(List<Contact> newModels) {
for (int toPosition = newModels.size() - 1; toPosition >= 0; toPosition--) {
final Contact model = newModels.get(toPosition);
final int fromPosition = contactsList.indexOf(model);
if (fromPosition >= 0 && fromPosition != toPosition) {
moveItem(fromPosition, toPosition);
}
}
}
}
And this is my Model
public class Contact {
String name;
String phone;
String city;
String location;
Boolean verified;
String image_url;
public Contact(String name, String phone, String city, String location, Boolean verified, String image_url){
this.name = name;
this.phone = phone;
this.city = city;
this.location = location;
this.verified = verified;
this.image_url = image_url;
}
}
This is the Activity where I use my filter
public class MyContactsActivity extends AppCompatActivity implements View.OnClickListener, SearchView.OnQueryTextListener {
private RecyclerView recyclerView;
private ContactsAdapter adapter;
private NetworkChecker networkChecker;
private SessionManager sessionManager;
private AppConfig appConfig;
private RelativeLayout loading, retry;
private Button tryAgain;
AlertHelper alertHelper;
final ArrayList<Contact> contactArrayList = new ArrayList<>();
String url;
DebugHelper debugHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_contacts);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
debugHelper = new DebugHelper();
loading = (RelativeLayout) findViewById(R.id.loadingPanel);
retry = (RelativeLayout) findViewById(R.id.retry);
tryAgain = (Button) findViewById(R.id.tryAgainButton);
tryAgain.setOnClickListener(this);
alertHelper = new AlertHelper(this);
networkChecker = new NetworkChecker(this);
sessionManager = new SessionManager(this);
appConfig = new AppConfig();
String phone = sessionManager.getLoggedInUserPhone();
url = appConfig.getApiUrlForSpecificContacts(phone);
recyclerView = (RecyclerView) findViewById(R.id.contactsView);
adapter = new ContactsAdapter(getApplicationContext(), true);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
sendJsonRequest(url);
recyclerView.setAdapter(adapter);
recyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
TextView phone = (TextView) view.findViewById(R.id.contact_phone);
TextView name = (TextView) view.findViewById(R.id.contact_name);
Intent i = new Intent(getApplicationContext(), ContactProfileActivity.class);
i.putExtra("selected_user_phone", phone.getText());
i.putExtra("selected_user_name", name.getText());
startActivity(i);
}
})
);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getApplicationContext(), AddContactActivity.class));
}
});
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
private void sendJsonRequest(String url) {
if (networkChecker.networkAvailable()) {
loading.setVisibility(View.VISIBLE);
RequestQueue requestQueue = VolleySingleton.getsInstance().getmRequestQueue();
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.setVisibility(View.GONE);
retry.setVisibility(View.GONE);
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("contact_info");
if(jsonArray != null){
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject currentContact = jsonArray.getJSONObject(i);
String name = currentContact.getString("name");
String phone = currentContact.getString("phone");
String city = currentContact.getString("city");
String address = currentContact.getString("address");
Boolean verified = currentContact.getBoolean("verified");
String image_url = currentContact.getString("image_url");
Contact contact = new Contact(name, phone, city, address, verified, image_url);
contactArrayList.add(contact);
}
adapter.setContactsList(contactArrayList);
}
else{
alertHelper.displayDialog("No Contacts Found.");
}
}catch (Exception e){
retry.setVisibility(View.VISIBLE);
tryAgain.setClickable(true);
alertHelper.displayDialog(getString(R.string.action_failed_try_again));
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
loading.setVisibility(View.GONE);
retry.setVisibility(View.VISIBLE);
tryAgain.setClickable(true);
if (error instanceof TimeoutError || error instanceof NoConnectionError) {
alertHelper.displayDialog(getString(R.string.connection_failed));
} else {
alertHelper.displayDialog(getString(R.string.action_failed_try_again));
}
}
});
requestQueue.add(stringRequest);
} else {
retry.setVisibility(View.VISIBLE);
tryAgain.setClickable(true);
}
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.contact_list_menu, menu);
debugHelper.L("Search Click Vayo");
final MenuItem item = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(this);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
switch (id) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.tryAgainButton:
sendJsonRequest(url);
break;
}
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String query) {
final List<Contact> filteredModelList = filter(contactArrayList, query);
adapter.animateTo(filteredModelList);
recyclerView.scrollToPosition(0);
return true;
}
private List<Contact> filter(List<Contact> models, String query) {
query = query.toLowerCase();
if(query.equals("")) { return contactArrayList; }
final List<Contact> filteredModelList = new ArrayList<>();
for (Contact model : models) {
final String text = model.name.toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
}
Can anyone help me please?
assuming contactsList is var with the full contacts
private List<Contact> filter(List<Contact> models, String query) {
query = query.toLowerCase();
if(query.equals("")) { return contactsList; }
final List<Contact> filteredModelList = new ArrayList<>();
for (Contact model : models) {
final String text = model.name.toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
}
He has defined in this way:
public void setModels(List<ExampleModel> models) {
mModels = new ArrayList<>(models);
}
Initialize like the way he has done.
Your soultion would be:
this.contactsList = new ArrayList<>(contactsList);
You need to move your filter() method from your Activity to your Adapter. At your Adapter add one additional variable to hold a copy of unfiltered dataset. In your case, you need contactsList and copyOfContactsList variables.
Change your Adapter's constructor as follows:
public class ContactsAdapter extends RecyclerView.Adapter<ContactViewHolder> {
....
private ArrayList<Contact> contactsList = new ArrayList<>();
private ArrayList<Contact> copyOfContactsList = new ArrayList<>();
....
public ContactsAdapter(Context context, ArrayList<Contact> dataSet, boolean fromMyContacts){
...
this.contactsList = dataSet;
copyOfContactsList.addAll(dataSet);
...
}
and this is the filter method to be added to your Adapter:
public void filter(String text) {
if(text.isEmpty()){
contactsList.clear();
contactsList.addAll(copyOfContactsList);
} else{
ArrayList<Contact> result = new ArrayList<>();
text = text.toLowerCase();
for(Contact item: copyOfContactsList){
if(item.getName().toLowerCase().contains(text)){
result.add(item);
}
}
contactsList.clear();
contactsList.addAll(result);
}
notifyDataSetChanged();
}
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);
}
}
}
}));