I'm learning android and I'm testing right now with ExpandableListViews. I'm doing something like a dictionary with a SearchView. When I click on a child I want to start a new activity with the child name on the ActionBar and the meaning of the word(from strings.xml) in a TextView. The problem is that instead of the child name, the showed text is something like: com.example.jairo_2.myapplication.country#58f8f2e with each child. Could you help me?. I have simplified the code with a Toast that shows the child name. Thanks.
Error image
I have followed Android ExpandableListView Search Filter Example.
MainActivity.java:
package com.example.jairo_2.myapplication;
import android.app.SearchManager;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.SearchView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements
SearchView.OnQueryTextListener, SearchView.OnCloseListener{
private SearchView search;
private MyListAdapter listAdapter;
private ExpandableListView myList;
public ArrayList<Continent> continentList = new ArrayList<Continent>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
search = (SearchView) findViewById(R.id.search);
search.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
search.setIconifiedByDefault(false);
search.setOnQueryTextListener(this);
search.setOnCloseListener(this);
//display the list
displayList();
//expand all Groups
//expandAll();
setListener();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
//method to expand all groups
private void expandAll() {
int count = listAdapter.getGroupCount();
for (int i = 0; i < count; i++){
myList.expandGroup(i);
}
}
//method to expand all groups
private void displayList() {
//display the list
loadSomeData();
//get reference to the ExpandableListView
myList = (ExpandableListView) findViewById(R.id.expandableList);
//create the adapter by passing your ArrayList data
listAdapter = new MyListAdapter(MainActivity.this, continentList);
//attach the adapter to the list
myList.setAdapter(listAdapter);
}
private void loadSomeData() {
ArrayList<Country> countryList = new ArrayList<Country>();
Country country = new Country("word1");
countryList.add(country);
country = new Country("word2");
countryList.add(country);
country = new Country("word3");
countryList.add(country);
Continent continent = new Continent("A",countryList);
continentList.add(continent);
countryList = new ArrayList<Country>();
country = new Country("China");
countryList.add(country);
country = new Country("Japan");
countryList.add(country);
country = new Country("Thailand");
countryList.add(country);
continent = new Continent("Asia",countryList);
continentList.add(continent);
}
#Override
public boolean onClose() {
listAdapter.filterData("");
expandAll();
return false;
}
#Override
public boolean onQueryTextChange(String query) {
listAdapter.filterData(query);
expandAll();
if (query.compareTo("") == 0){
int count = listAdapter.getGroupCount();
for (int i = 0; i <count ; i++)
myList.collapseGroup(i);}
return false;
}
#Override
public boolean onQueryTextSubmit(String query) {
listAdapter.filterData(query);
expandAll();
if (query.compareTo("") == 0){
int count = listAdapter.getGroupCount();
for (int i = 0; i <count ; i++)
myList.collapseGroup(i);}
return false;
}
void setListener() {
// This listener will show toast on group click
myList.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView listview, View view,
int group_pos, long id) {
Toast.makeText(MainActivity.this, "You clicked : " + listAdapter.getGroup(group_pos), Toast.LENGTH_SHORT).show();
return false;
}
});
// This listener will expand one group at one time
// You can remove this listener for expanding all groups
//myList.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
// Default position
//int previousGroup = -1;
//#Override
//public void onGroupExpand(int groupPosition) {
// if (groupPosition != previousGroup)
// Collapse the expanded group
// myList.collapseGroup(previousGroup);
//previousGroup = groupPosition;
// }
// });
// This listener will show toast on child click
myList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView listview, View view,
int groupPos, int childPos, long id) {
Toast.makeText(MainActivity.this, "You clicked : " + listAdapter.getChild(groupPos,childPos), Toast.LENGTH_SHORT).show();
return false;
}
});
}
}
MyListAdapter.java:
package com.example.jairo_2.myapplication;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class MyListAdapter extends BaseExpandableListAdapter {
private Context context;
public ArrayList<Continent> continentList;
private ArrayList<Continent> originalList;
public MyListAdapter(Context context, ArrayList<Continent> continentList) {
this.context = context;
this.continentList = new ArrayList<Continent>();
this.continentList.addAll(continentList);
this.originalList = new ArrayList<Continent>();
this.originalList.addAll(continentList);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
ArrayList<Country> countryList = continentList.get(groupPosition).getCountryList();
return countryList.get(childPosition);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
View view, ViewGroup parent) {
Country country = (Country) getChild(groupPosition, childPosition);
if (view == null) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.child_row, null);
}
TextView name = (TextView) view.findViewById(R.id.name);
name.setText(country.getName().trim());
return view;
}
#Override
public int getChildrenCount(int groupPosition) {
ArrayList<Country> countryList = continentList.get(groupPosition).getCountryList();
return countryList.size();
}
#Override
public Object getGroup(int groupPosition) {
return continentList.get(groupPosition);
}
#Override
public int getGroupCount() {
return continentList.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isLastChild, View view,
ViewGroup parent) {
Continent continent = (Continent) getGroup(groupPosition);
if (view == null) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.group_row, null);
}
TextView heading = (TextView) view.findViewById(R.id.heading);
heading.setText(continent.getName().trim());
return view;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
public void filterData(String query){
query = query.toLowerCase();
Log.v("MyListAdapter", String.valueOf(continentList.size()));
continentList.clear();
if(query.isEmpty()){
continentList.addAll(originalList);
}
else {
for(Continent continent: originalList){
ArrayList<Country> countryList = continent.getCountryList();
ArrayList<Country> newList = new ArrayList<Country>();
for(Country country: countryList){
if(country.getName().toLowerCase().contains(query)){
newList.add(country);
}
}
if(newList.size() > 0){
Continent nContinent = new Continent(continent.getName(),newList);
continentList.add(nContinent);
}
}
}
Log.v("MyListAdapter", String.valueOf(continentList.size()));
notifyDataSetChanged();
}
}
Country.java:
package com.example.jairo_2.myapplication;
public class Country {
private String name = "";
public Country(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Continent.java
package com.example.jairo_2.myapplication;
import java.util.ArrayList;
public class Continent {
private String name;
private ArrayList<Country> countryList = new ArrayList<Country>();
public Continent(String name, ArrayList<Country> countryList) {
super();
this.name = name;
this.countryList = countryList;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ArrayList<Country> getCountryList() {
return countryList;
}
public void setCountryList(ArrayList<Country> countryList) {
this.countryList = countryList;
};
}
Use like this continentList.get(groupPosition).getCountryList().get(childposition)
in your Toast message section
Related
I have an ExpandableListView created and working with static data, my problem is I am not sure how to get data from my sqlite database into the ExpandableListView. I have tried multiple websites and posts and have gotten very little.
If someone could please take a look at my code below and suggest a working solution.
Thanks
package com.example.pooveshin.vennsroadaccident2;
import android.app.Activity;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ExpandableListView.OnGroupCollapseListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends Activity {
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get the listview
expListView = (ExpandableListView) findViewById(R.id.lvExp);
// preparing list data
prepareListData();
listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);
// setting list adapter
expListView.setAdapter(listAdapter);
// Listview Group click listener
expListView.setOnGroupClickListener(new OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
// Toast.makeText(getApplicationContext(),
// "Group Clicked " + listDataHeader.get(groupPosition),
// Toast.LENGTH_SHORT).show();
return false;
}
});
// Listview Group expanded listener
expListView.setOnGroupExpandListener(new OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
Toast.makeText(getApplicationContext(),
listDataHeader.get(groupPosition) + " Expanded",
Toast.LENGTH_SHORT).show();
}
});
// Listview Group collasped listener
expListView.setOnGroupCollapseListener(new OnGroupCollapseListener() {
#Override
public void onGroupCollapse(int groupPosition) {
Toast.makeText(getApplicationContext(),
listDataHeader.get(groupPosition) + " Collapsed",
Toast.LENGTH_SHORT).show();
}
});
// Listview on child click listener
expListView.setOnChildClickListener(new OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
// TODO Auto-generated method stub
Toast.makeText(
getApplicationContext(),
listDataHeader.get(groupPosition)
+ " : "
+ listDataChild.get(
listDataHeader.get(groupPosition)).get(
childPosition), Toast.LENGTH_SHORT)
.show();
return false;
}
});
}
/*
* Preparing the list data
*/
private void prepareListData() {
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
// Adding child data
listDataHeader.add("Accident Number : 1");
listDataHeader.add("Accident Number : 2");
listDataHeader.add("Accident Number : 3");
// Adding child data
List<String> AccYV = new ArrayList<String>();
AccYV.add("Accident Number : ");
AccYV.add("Registration Number : ");
AccYV.add("Make & Model");
AccYV.add("Address of Owner");
AccYV.add("Name of Driver");
AccYV.add("Address of Driver");
AccYV.add("Tel no.Driver");
List<String> AccOV = new ArrayList<String>();
AccOV.add("Name of Driver");
AccOV.add("Identity Number");
AccOV.add("Residential Address");
AccOV.add("Tel no.Work");
AccOV.add("Make & Model");
AccOV.add("Licence Number");
List<String> AccCD = new ArrayList<String>();
AccCD.add("Date");
AccCD.add("Time");
AccCD.add("Place");
AccCD.add("Weather");
AccCD.add("Road Surface");
listDataChild.put(listDataHeader.get(0), AccYV); // Header, Child data
listDataChild.put(listDataHeader.get(1), AccOV);
listDataChild.put(listDataHeader.get(2), AccCD);
}
}
In DBHelper.java
public Cursor getYVAllData()
{
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
Cursor res = sqLiteDatabase.rawQuery("SELECT * FROM " + TABLE_NAME,null);
return res;
}
you shoud make an adapter for expandablelistview like this
public class ExpandListAdapter extends BaseExpandableListAdapter {
private Context context;
private ArrayList<ExpandListGroup> groups;
public ExpandListAdapter(Context context, ArrayList<ExpandListGroup> groups) {
this.context = context;
this.groups = groups;
}
public void addItem(ExpandListChild item, ExpandListGroup group) {
if (!groups.contains(group)) {
groups.add(group);
}
int index = groups.indexOf(group);
ArrayList<ExpandListChild> ch = groups.get(index).getItems();
ch.add(item);
groups.get(index).setItems(ch);
}
public Object getChild(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
ArrayList<ExpandListChild> chList = groups.get(groupPosition).getItems();
return chList.get(childPosition);
}
public long getChildId(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return childPosition;
}
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View view,
ViewGroup parent) {
ExpandListChild child = (ExpandListChild) getChild(groupPosition, childPosition);
if (view == null) {
LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
view = infalInflater.inflate(R.layout.expandlist_child_item, null);
}
TextView tv = (TextView) view.findViewById(R.id.tvChild);
tv.setText(child.getName().toString());
tv.setTag(child.getTag());
// TODO Auto-generated method stub
return view;
}
public int getChildrenCount(int groupPosition) {
// TODO Auto-generated method stub
ArrayList<ExpandListChild> chList = groups.get(groupPosition).getItems();
return chList.size();
}
public Object getGroup(int groupPosition) {
// TODO Auto-generated method stub
return groups.get(groupPosition);
}
public int getGroupCount() {
// TODO Auto-generated method stub
return groups.size();
}
public long getGroupId(int groupPosition) {
// TODO Auto-generated method stub
return groupPosition;
}
public View getGroupView(int groupPosition, boolean isLastChild, View view,
ViewGroup parent) {
ExpandListGroup group = (ExpandListGroup) getGroup(groupPosition);
if (view == null) {
LayoutInflater inf = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
view = inf.inflate(R.layout.expandlist_group_item, null);
}
TextView tv = (TextView) view.findViewById(R.id.tvGroup);
tv.setText(group.getName());
// TODO Auto-generated method stub
return view;
}
public boolean hasStableIds() {
// TODO Auto-generated method stub
return true;
}
public boolean isChildSelectable(int arg0, int arg1) {
// TODO Auto-generated method stub
return true;
}
}
then you should make child and group classes for list like this
child:
public class ExpandListChild {
private String Name;
private String Tag;
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public String getTag() {
return Tag;
}
public void setTag(String Tag) {
this.Tag = Tag;
}
}
group:
public class ExpandListGroup {
private String Name;
private ArrayList<ExpandListChild> Items;
public String getName() {
return Name;
}
public void setName(String name) {
this.Name = name;
}
public ArrayList<ExpandListChild> getItems() {
return Items;
}
public void setItems(ArrayList<ExpandListChild> Items) {
this.Items = Items;
}
}
and this is usage in your MainActivity :
ExpandList = (ExpandableListView) findViewById(R.id.expandableListView);
ExpListItems = SetStandardGroups(da.queryName());
ExpAdapter = new ExpandListAdapter(MainActivity.this, ExpListItems);
and this is my method for fiil that list:
public ArrayList<ExpandListGroup> SetStandardGroups(Cursor crsr) {
ArrayList<ExpandListGroup> list = new ArrayList<ExpandListGroup>();
ArrayList<ExpandListChild> list2;
Cursor c = crsr;
if (c.moveToFirst()) {
do {
String English = c.getString(c.getColumnIndex("English"));
String Farsi = c.getString(c.getColumnIndex("Farsi"));
ExpandListGroup gru1 = new ExpandListGroup();
gru1.setName(English);
ExpandListChild ch1_1 = new ExpandListChild();
ch1_1.setName(Farsi);
ch1_1.setTag(null);
list2 = new ArrayList<ExpandListChild>();
list2.add(ch1_1);
gru1.setItems(list2);
list.add(gru1);
} while (c.moveToNext());
}
c.close();
return list;
}
I have a Listview with two adapters. They receive an Array with some data and when scrolled to bottom of the listview more data is loaded into the Array and here the listview should add the new data.
Question:
How can I make the listview reflect the new data and why isn't it updated when I call adAdapter.notifyDataSetChanged(); ?
Fragments inner class where I download data & update UI in onPostExecute:
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
numberofpagesshown = numberofpagesshown + 1;
if(numberofpagesshown == 1 ) {
list = (ListView) getActivity().findViewById(R.id.search_listview_movie);
adapter = new SearchListViewAdapter(getActivity(), mylist);
adAdapter = new BannerAdListView2(getActivity(), adapter);
// list.setAdapter(adapter); this works when adapter.notifyDataSetChanged(); also is in the else statement but here I don't use the BannerAdListView2 adapter which i want to?
list.setAdapter(adAdapter);
bar.setVisibility(View.GONE);
}
else {
// adapter.notifyDataSetChanged(); // Here the listview should get refresh with the new data
adAdapter.notifyDataSetChanged();
bar.setVisibility(View.GONE);
}
// Attach the listener to the AdapterView onCreate
list.setOnScrollListener(new EndlessScrollListener() {
#Override
public void onLoadMore(int page, int totalItemsCount) {
// Triggered only when new data needs to be appended to the list
// Append new items to AdapterView
if(pageNumberInt < totalPagesInt){
++incre;
new DownloadJSON().execute();
}
}
});
}
Here is my SearchListViewAdapter:
public class SearchListViewAdapter extends BaseAdapter{
Context context;
ArrayList<HashMap<String, String>> data;
HashMap<String, String> mylist = new HashMap<>();
static String url;
static String title;
public SearchListViewAdapter(Context a, ArrayList<HashMap<String, String>> d) {
context = a;
data = d;
}
public int getCount() {
return data.size();
}
public HashMap<String, String> getItem(int position) {
return data.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Avoid unneccessary calls to findViewById() on each row
final ViewHolder holder;
/*
* If convertView is not null, reuse it directly, no inflation
* Only inflate a new View when the convertView is null.
*/
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.search_list_item, parent, false);
holder = new ViewHolder();
holder.poster = (ImageView) convertView.findViewById(R.id.list_image);
holder.textForTitle = (TextView) convertView.findViewById(R.id.search_title);
holder.textForTitle.setTag(position);
convertView.setTag(holder);
}
else{
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
holder = (ViewHolder) convertView.getTag();
holder.textForTitle.setTag(data.get(position));
}
mylist = data.get(position);
final String mediaType = mylist.get("media_type");
if (mediaType.equals("movie")) {
String posterPath = mylist.get("poster_path");
url = "http://image.tmdb.org/t/p/w185" + posterPath;
title = mylist.get("title");
} else if (mediaType.equals("tv")) {
String posterPath = mylist.get("poster_path");
url = "http://image.tmdb.org/t/p/w185" + posterPath;
title = mylist.get("original_name");
} else {
String posterPath = mylist.get("profile_path");
url = "http://image.tmdb.org/t/p/w185" + posterPath;
title = mylist.get("name");
}
// set image url correctly
// sizes for image 45, 92, 154, 185, 300, 500
// load image url into poster
Picasso.with(context).load(url).into(holder.poster);
// set title to textview
holder.textForTitle.setText(title);
return convertView;
}
class ViewHolder {
ImageView poster;
TextView textForTitle;
}
}
And my BannerAdListView2 adapter:
public class BannerAdListView2 extends BaseAdapter
{
Activity activity;
Context context;
BaseAdapter delegate;
int k = 7;
int baseItems;
int noAds;
// Constructor takes in a BaseAdapter
public BannerAdListView2(Activity activity, BaseAdapter delegate ) {
this.activity = activity;
this.delegate = delegate;
baseItems = delegate.getCount();
noAds = baseItems / k;
LayoutInflater mLayoutInflater = (LayoutInflater) this.activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// Total count includes list items and ads.
return baseItems + noAds;
}
#Override
public Object getItem(int position) {
// Return null if an item is an ad. Otherwise return the delegate item.
if (isItemAnAd(position)) {
return null;
}
return delegate.getItem(getOffsetPosition(position));
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getViewTypeCount() {
return delegate.getViewTypeCount() + noAds;
}
#Override
public int getItemViewType(int position) {
if (isItemAnAd(position)) {
return delegate.getViewTypeCount();
} else {
return delegate.getItemViewType(getOffsetPosition(position));
}
}
#Override
public boolean areAllItemsEnabled() {
return false;
}
#Override
public boolean isEnabled(int position) {
return (!isItemAnAd(position)) && delegate.isEnabled(getOffsetPosition(position));
}
private boolean isItemAnAd(int position) {
if (position < k) return false;
// Calculate current offset caused by ads already embedded
if (position==k){
return true;
}
else {
return isItemAnAd(position-k);
}
}
// Get the position that is offset by the insertion of the ads
private int getOffsetPosition(int position) {
int currentNoAds = position / k;
return position - currentNoAds;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Display every n list items
if (isItemAnAd(position)) {
if (convertView instanceof AdView) {
// Don’t instantiate new AdView, reuse old one
return convertView;
} else {
// Create a new AdView
AdView adView = new AdView(activity);
adView.setAdSize(AdSize.BANNER);
String bannerId = "My unit id";
adView.setAdUnitId(bannerId);
// Disable focus for sub-views of the AdView to avoid problems with
// trackpad navigation of the list.
for (int i = 0; i < adView.getChildCount(); i++)
{
adView.getChildAt(i).setFocusable(false);
}
adView.setFocusable(false);
// Convert the default layout parameters so that they play nice with
// ListView.
float density = activity.getResources().getDisplayMetrics().density;
int height = Math.round(AdSize.BANNER.getHeight() * density);
AbsListView.LayoutParams params = new AbsListView.LayoutParams(
AbsListView.LayoutParams.MATCH_PARENT,
height);
adView.setLayoutParams(params);
AdRequest bannerIntermediateReq = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.addTestDevice("d9e108ab") //means that a test ad is shown on my phone
.build();
adView.loadAd(bannerIntermediateReq);
return adView;
}
} else {
// Offload displaying other items to the delegate
return delegate.getView(getOffsetPosition(position) ,
convertView, parent);
}
}
}
Edit:
Changed the constructor of BannerAdListView2
// Constructor takes in a BaseAdapter
public BannerAdListView2(Activity activity, final BaseAdapter delegate ) {
this.activity = activity;
this.delegate = delegate;
delegate.registerDataSetObserver(new DataSetObserver() {
public void onChanged() {
baseItems = delegate.getCount();
noAds = baseItems / k;
}
public void onInvalidated() {
notifyDataSetInvalidated();
}
});
baseItems = delegate.getCount();
noAds = baseItems / k;
LayoutInflater mLayoutInflater = (LayoutInflater) this.activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
And in fragment
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
numberofpagesshown = numberofpagesshown + 1;
if(numberofpagesshown == 1 ) {
list = (ListView) getActivity().findViewById(R.id.search_listview_movie);
adapter = new SearchListViewAdapter(getActivity(), mylist);
adAdapter = new BannerAdListView2(getActivity(), adapter);
list.setAdapter(adAdapter);
bar.setVisibility(View.GONE);
}
else {
adapter.notifyDataSetChanged();
bar.setVisibility(View.GONE);
}
}
Try this solution ... DecorerAdapter:
public static abstract class DecorerAdapter extends BaseAdapter {
public int DECORER_ITEM_TYPE;
private final BaseAdapter mInnerAdapter;
private final int mRepeatAfterEvery;
private int mCount;
public DecorerAdapter(BaseAdapter innerAdapter, int repeatAfterEvery) {
mInnerAdapter = innerAdapter;
mRepeatAfterEvery = repeatAfterEvery;
mInnerAdapter.registerDataSetObserver(new DataSetObserver() {
#Override
public void onChanged() {
notifyDataSetChanged();
}
#Override
public void onInvalidated() {
notifyDataSetInvalidated();
}
});
setupAdapter();
}
#Override
public void notifyDataSetChanged() {
setupAdapter();
super.notifyDataSetChanged();
}
private void setupAdapter(){
mCount = mInnerAdapter.getCount();
mCount += (mCount + mRepeatAfterEvery - 2) / (mRepeatAfterEvery - 1);
DECORER_ITEM_TYPE = mInnerAdapter.getViewTypeCount();
}
#Override
public int getCount() {
return mCount;
}
#Override
public Object getItem(int position) {
if(position % mRepeatAfterEvery == 0)
return null;
return mInnerAdapter.getItem(calculateInnerPosition(position));
}
private int calculateInnerPosition(int position) {
return position - (position + mRepeatAfterEvery - 1) / mRepeatAfterEvery;
}
#Override
public long getItemId(int position) {
if(position % mRepeatAfterEvery == 0)
return -1;
return mInnerAdapter.getItemId(calculateInnerPosition(position));
}
#Override
public int getItemViewType(int position) {
if(position % mRepeatAfterEvery == 0)
return DECORER_ITEM_TYPE;
return mInnerAdapter.getItemViewType(calculateInnerPosition(position));
}
#Override
public boolean hasStableIds() {
return mInnerAdapter.hasStableIds();
}
#Override
public int getViewTypeCount() {
return mInnerAdapter.getViewTypeCount() + 1;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(position % mRepeatAfterEvery == 0)
return getDecorerView((position + mRepeatAfterEvery - 1) / mRepeatAfterEvery, convertView, parent);
return mInnerAdapter.getView(calculateInnerPosition( position), convertView, parent);
}
public abstract View getDecorerView(int position, View convertView, ViewGroup parent);
}
code with usage:
package pl.selvin.decoreradapter;
import android.database.DataSetObserver;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
/*** paste the DecorerAdapter class here ***/
public static class MyListFragment extends ListFragment{
final ArrayList<String> strings = new ArrayList<>();
private BaseAdapter innerAdapter;
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.add("Add rnd(10) more");
super.onCreateOptionsMenu(menu, inflater);
}
final Random rnd = new Random();
#Override
public boolean onOptionsItemSelected(MenuItem item) {
final String[] toAdd = new String[rnd.nextInt(10)];
int start = strings.size();
for(int i = 0; i < toAdd.length; i++)
toAdd[i] = (start + i) + "";
Collections.addAll(strings, toAdd);
Toast.makeText(getActivity(), "Added " + toAdd.length + " count: " + strings.size(), Toast.LENGTH_SHORT).show();
innerAdapter.notifyDataSetChanged();
return true;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
for(int i = 0; i < 4; i++) {
strings.add(i + "");
}
innerAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, strings);
setListAdapter(new DecorerAdapter(innerAdapter, 5) {
#Override
public View getDecorerView(int position, View convertView, ViewGroup parent) {
if(convertView == null) {
convertView = new TextView(getActivity());
convertView.setBackgroundColor(Color.RED);
}
((TextView)convertView).setText("AdView: " + position);
return convertView;
}
});
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
String item = (String)l.getItemAtPosition(position);
Toast.makeText(getActivity(), "Item click: " + (item == null ? "ADVIEW" : item), Toast.LENGTH_LONG).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(android.R.id.content, new MyListFragment(), "LIST").commit();
}
}
}
It repeats decorer view at every element passed to the constructor ...
all you need to do is implement getDecorerView in the similar way as getView in normal adapter
This might be very easy question, but I'm looking for your help.
I'm using downloaded open source file. I have a list of Groups with populated Child's under it. I'm able to expand the list and see the Child's. How could I open new activity window with text information relater for specific Children when clicking on it?
Thank you for support.
MainActivity.java:
package com.example.expandablelistviewsearch;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.os.Bundle;
import android.view.Menu;
import android.widget.ExpandableListView;
import android.widget.SearchView;
import android.widget.ExpandableListView.OnChildClickListener;
import java.util.ArrayList;
public class MainActivity extends Activity implements
SearchView.OnQueryTextListener, SearchView.OnCloseListener {
private SearchView search;
private MyListAdapter listAdapter;
private ExpandableListView myList;
private ArrayList<Continent> continentList = new ArrayList<Continent>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myList.setOnChildClickListener(myListItemClicked); //added line
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
search = (SearchView) findViewById(R.id.search);
search.setSearchableInfo(searchManager
.getSearchableInfo(getComponentName()));
search.setIconifiedByDefault(true);
search.setOnQueryTextListener(this);
//search.setOnCloseListener(this);
// display the list
displayList();
// expand all Groups
//expandAll();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
// method to expand all groups
private void expandAll() {
int count = listAdapter.getGroupCount();
for (int i = 0; i < count; i++) {
myList.expandGroup(i);
}
}
private OnChildClickListener myListItemClicked = new OnChildClickListener() {
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
//get the group header
HeaderInfo headerInfo = deptList.get(groupPosition);
//get the child info
DetailInfo detailInfo = headerInfo.getProductList().get(childPosition);
//start new activity with specific child information
return false;
}
};
// method to expand all groups
private void displayList() {
// display the list
loadSomeData();
// get reference to the ExpandableListView
myList = (ExpandableListView) findViewById(R.id.expandableList);
// create the adapter by passing your ArrayList data
listAdapter = new MyListAdapter(MainActivity.this, continentList);
// attach the adapter to the list
myList.setAdapter(listAdapter);
}
private void loadSomeData() {
ArrayList<Country> countryList = new ArrayList<Country>();
Country country = new Country("Test1", "Test2", "Test3");
countryList.add(country);
Continent continent = new Continent("Main Test", countryList);
continentList.add(continent);
private void loadSomeData() {
ArrayList<Country> countryList = new ArrayList<Country>();
Country country = new Country("Test1", "Test2", "Test3");
countryList.add(country);
Continent continent = new Continent("Main Tes1t", countryList);
continentList.add(continent);
private void loadSomeData() {
ArrayList<Country> countryList = new ArrayList<Country>();
Country country = new Country("Test1", "Test2", "Test3");
countryList.add(country);
Continent continent = new Continent("Main Test2", countryList);
continentList.add(continent);
}
#Override
public boolean onClose() {
// TODO Auto-generated method stub
listAdapter.filterData("");
//expandAll();
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
// TODO Auto-generated method stub
listAdapter.filterData(newText);
expandAll();
return false;
}
#Override
public boolean onQueryTextSubmit(String query) {
// TODO Auto-generated method stub
listAdapter.filterData(query);
expandAll();
return false;
}
}
MyListAdapter.java
package com.example.expandablelistviewsearch;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class MyListAdapter extends BaseExpandableListAdapter {
private Context context;
private ArrayList<Continent> continentList;
private ArrayList<Continent> originalList;
public MyListAdapter(Context context, ArrayList<Continent> continentList) {
this.context = context;
this.continentList = new ArrayList<Continent>();
this.continentList.addAll(continentList);
this.originalList = new ArrayList<Continent>();
this.originalList.addAll(continentList);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
ArrayList<Country> countryList = continentList.get(groupPosition).getCountryList();
return countryList.get(childPosition);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return childPosition;
}
#Override
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Country country = (Country) getChild(groupPosition, childPosition);
if(convertView == null)
{
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.child_row, null);
}
TextView code = (TextView) convertView.findViewById(R.id.code);
TextView name = (TextView) convertView.findViewById(R.id.name);
TextView fdd = (TextView) convertView.findViewById(R.id.fdd);
code.setText(country.getCode().trim());
name.setText(country.getName().trim());
fdd.setText(country.getFdd().trim());
//population.setText(NumberFormat.getNumberInstance(Locale.US).format(country.getPopulation()));
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
// TODO Auto-generated method stub
ArrayList<Country> countryList = continentList.get(groupPosition).getCountryList();
return countryList.size();
}
#Override
public Object getGroup(int groupPosition) {
// TODO Auto-generated method stub
return continentList.get(groupPosition);
}
#Override
public int getGroupCount() {
// TODO Auto-generated method stub
return continentList.size();
}
#Override
public long getGroupId(int groupPosition) {
// TODO Auto-generated method stub
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Continent continent = (Continent) getGroup(groupPosition);
if(convertView == null)
{
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.group_row, null);
}
TextView heading = (TextView) convertView.findViewById(R.id.heading);
heading.setText(continent.getName().trim());
return convertView;
}
#Override
public boolean hasStableIds() {
// TODO Auto-generated method stub
return true;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return true;
}
public void filterData(String query)
{
query = query.toLowerCase();
Log.v("MyListAdapter", String.valueOf(continentList.size()));
continentList.clear();
if(query.isEmpty())
{
continentList.addAll(originalList);
} else {
for(Continent continent: originalList)
{
ArrayList<Country> countryList = continent.getCountryList();
ArrayList<Country> newList = new ArrayList<Country>();
for(Country country: countryList)
{
if(country.getCode().toLowerCase().contains(query) || country.getName().toLowerCase().contains(query))
{
newList.add(country);
}
}
if(newList.size() > 0)
{
Continent nContinent = new Continent(continent.getName(), newList);
continentList.add(nContinent);
}
}
}
Log.v("MyListAdapter", String.valueOf(continentList.size()));
notifyDataSetChanged();
}
}
You are almost there, under your code, you can send anything related to the child you click to the new activity using intent, then get the information out in the new activity
private OnChildClickListener myListItemClicked = new OnChildClickListener() {
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
//get the group header
HeaderInfo headerInfo = deptList.get(groupPosition);
//get the child info
DetailInfo detailInfo = headerInfo.getProductList().get(childPosition);
//start new activity with specific child information
//--Add below codes to your code
Intent myIntent = new Intent(MainActivity.this, TargetActivity.class);
myIntent.putExtra("information",detailInfo.getInfor());
return false;
}
};
In the TargetActivity,
Intent tIntent= getIntent();
Bundle b = tIntent.getExtras();
String information = (String)b.get("information");
The string information is probably what you want to display
I need yout help. How to add Ad Unit (NativeAd) within a List of Articles, using Facebook Audience Network https://developers.facebook.com/docs/audience-network/android/native-api. Im not programmer and need all code how it should be. The ads have to be between posts (listview)Thanks
import com.facebook.ads.*;
public class Posts extends Fragment{
ArrayList<Post> mPosts;
private static final String KEY_CONTENT = "PostsFragment:array";
boolean isLoadMore = false;
int mPageCount = 0;
int mCurrectPage = 1;
PullToRefreshListView mListView;
MyAdapter mListViewAdapter;
View mLoadingFooter;
private Tracker tracker;
#SuppressWarnings("unchecked")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.tracker = EasyTracker.getInstance(this.getActivity());
if ((savedInstanceState != null) && savedInstanceState.containsKey(KEY_CONTENT)) {
mPosts = (ArrayList<Post>) savedInstanceState.getSerializable(KEY_CONTENT);
mCurrectPage = 1;
mPosts.clear();
mLoadingFooter.setVisibility(View.VISIBLE);
isLoadMore = true;
loadPostsList();
}
}
#Override
public void onResume() {
super.onResume();
this.tracker.set(Fields.SCREEN_NAME, "Article");
this.tracker.send( MapBuilder.createAppView().build() );
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable(KEY_CONTENT, mPosts);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View _result = inflater.inflate(R.layout.list, null);
mLoadingFooter = inflater.inflate(R.layout.loading_footer, null);
mLoadingFooter.setVisibility(View.GONE);
if (mPosts == null)
{
mPosts = new ArrayList<Post>();
loadPostsList();
}
mListView = (PullToRefreshListView) _result.findViewById(R.id.listView);
mListViewAdapter = new MyAdapter(getActivity(), mPosts);
mListView.addFooterView(mLoadingFooter);
mListView.setAdapter(mListViewAdapter);
mListView.setOnRefreshListener(new OnRefreshListener<ListView>() {
#Override
public void onRefresh(PullToRefreshBase<ListView> refreshView) {
mCurrectPage = 1;
mPosts.clear();
mLoadingFooter.setVisibility(View.VISIBLE);
isLoadMore = true;
loadPostsList();
}
});
mListView.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
int lastInScreen = firstVisibleItem + visibleItemCount;
if (totalItemCount > Constant.MIN_ITEM_COUNT && lastInScreen >= (totalItemCount - Constant.MIN_ITEM_COUNT_HALF) && !isLoadMore && mCurrectPage <= mPageCount)
{
mLoadingFooter.setVisibility(View.VISIBLE);
isLoadMore = true;
loadPostsList();
}
}
});
return _result;
}
public void loadPostsList() {
isLoadMore = true;
mLoadingFooter.setVisibility(View.VISIBLE);
new AsynckRequestGet().execute(getActivity(), TYPE_GET_OPERATION.POSTS, CodeRequestManager.codePosts(TempData.getInstance().getToken(), mCurrectPage));
}
private class AsynckRequestGet extends AbstractAsyncRequestGet {
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
isLoadMore = false;
if(!isDetached()) {
mLoadingFooter.setVisibility(View.GONE);
mListView.onRefreshComplete();
}
if(result == null) return;
int[] t = JsonParser.parsePageCountResponse(result);
mPageCount = t[0];
mCurrectPage = t[1] +1;
ArrayList<Post> temp = JsonParser.parsePostsResponse(result);
if(temp == null || isDetached())
return;
mPosts.addAll(temp);
mListViewAdapter.notifyDataSetChanged();
}
}
private class MyAdapter extends ArrayAdapter<Post> {
private LayoutInflater inflater;
public MyAdapter(Context context, ArrayList<Post> objects) {
super(context, R.layout.post_item, objects);
inflater = LayoutInflater.from(context);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
convertView = inflater.inflate(R.layout.post_item, null);
final Post post = getItem(position);
final TextView postLikes = ((TextView) convertView.findViewById(R.id.post_likes));
final TextView postComments = ((TextView) convertView.findViewById(R.id.post_comments));
postComments.setText(post.getCountComment() + "");
postLikes.setText(post.getCountLike() + "");
if(post.isMyLike()) {
postLikes.setCompoundDrawablesWithIntrinsicBounds(R.drawable.like_my_icon, 0, 0, 0);
} else {
postLikes.setCompoundDrawablesWithIntrinsicBounds(R.drawable.like_icon, 0, 0, 0);
}
postLikes.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new AbstractAsyncRequestGet().execute(getActivity(), TYPE_GET_OPERATION.LIKE, CodeRequestManager.codeLike(TempData.getInstance().getToken(), post.getId(), post.isMyLike()? 0 : 1));
post.setCountLike((post.getCountLike()) + (post.isMyLike()? -1 : 1));
post.setMyLike(post.isMyLike()? 0 : 1);
postLikes.setText(post.getCountLike() + "");
mListViewAdapter.notifyDataSetChanged();
}
});
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
((TrainingFragment) getParentFragment().getParentFragment()).showPostDetails(mPosts.get(arg2-1), new DetailListener() {
#Override
public void onRefresh() {
if(!isDetached())
mListViewAdapter.notifyDataSetChanged();
}
})
;}
});
((TextView) convertView.findViewById(R.id.post_title)).setText(post.getTitle());
((TextView) convertView.findViewById(R.id.post_content)).setText(post.getContent());
return convertView;
}
}
}
If you get the latest Facebook Android SDK, you can find the NativeAdSample project updated with how to display native ads in a list view. Code copied from the sample:
package com.facebook.samples.NativeAdSample;
import java.util.ArrayList;
import java.util.List;
import com.facebook.ads.Ad;
import com.facebook.ads.AdError;
import com.facebook.ads.AdListener;
import com.facebook.ads.NativeAd;
import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class NativeAdListActivity extends ListActivity implements AdListener {
private ListView listView;
private ListViewAdapter adapter;
private NativeAd listNativeAd;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listNativeAd = new NativeAd(this, "YOUR_PLACEMENT_ID");
listNativeAd.setAdListener(this);
listNativeAd.loadAd();
listView = getListView();
adapter = new ListViewAdapter(getApplicationContext());
listView.setAdapter(adapter);
}
#Override
public void onAdClicked(Ad ad) {
Toast.makeText(this, "Ad Clicked", Toast.LENGTH_SHORT).show();
}
#Override
public void onAdLoaded(Ad ad) {
adapter.addNativeAd((NativeAd) ad);
}
#Override
public void onError(Ad ad, AdError error) {
Toast.makeText(this, "Ad failed to load: " + error.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
class ListViewAdapter extends BaseAdapter {
private LayoutInflater inflater;
private List<Object> list;
private NativeAd ad;
private static final int AD_INDEX = 2;
public ListViewAdapter(Context context) {
list = new ArrayList<Object>();
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for (int i = 1; i <= 35; i++) {
list.add("ListView Item #" + i);
}
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (position == AD_INDEX && ad != null) {
// Return the native ad view
return (View) list.get(position);
} else {
TextView view; // Default item type (non-ad)
if (convertView != null && convertView instanceof TextView) {
view = (TextView) convertView;
} else {
view = (TextView) inflater.inflate(R.layout.list_item, parent, false);
}
view.setText((String) list.get(position));
return view;
}
}
public synchronized void addNativeAd(NativeAd ad) {
if (ad == null) {
return;
}
if (this.ad != null) {
// Clean up the old ad before inserting the new one
this.ad.unregisterView();
this.list.remove(AD_INDEX);
this.ad = null;
this.notifyDataSetChanged();
}
this.ad = ad;
View adView = inflater.inflate(R.layout.ad_unit, null);
NativeAdSampleActivity.inflateAd(ad, adView, NativeAdListActivity.this);
list.add(AD_INDEX, adView);
this.notifyDataSetChanged();
}
}
}
I am trying to implement the getFilter() function in my ListView but everytime I enter something in the EditText my ListView disappears.
My SetHelpRows file:
public class SetHelpRows {
String name;
String id;
public String getName () {
return name;
}
public void setName (String name) {
this.name = name;
}
public String getID () {
return id;
}
public void setID (String id) {
this.id = id;
}
public SetHelpRows(String name, String id) {
super();
this.name = name;
this.id = id;
}
}
My SetHelpRowsCustomAdapter file:
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.ImageView;
import android.widget.TextView;
public class SetRowsCustomAdapter extends ArrayAdapter<SetRows> {
Context context;
int layoutResourceId;
ArrayList<SetRows> data=new ArrayList<SetRows>();
private ArrayList<SetRows> original;
private ArrayList<SetRows> fitems;
private Filter filter;
public SetRowsCustomAdapter(Context context, int layoutResourceId, ArrayList<SetRows> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
this.original = data;//new ArrayList<Pkmn>();
this.fitems = data;//new ArrayList<Pkmn>();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ImageHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ImageHolder();
holder.txtTitle = (TextView)row.findViewById(R.id.txtTitle);
holder.imgIcon = (ImageView)row.findViewById(R.id.imgIcon);
holder.txtID = (TextView)row.findViewById(R.id.txtModDate);
row.setTag(holder);
}
else
{
holder = (ImageHolder)row.getTag();
}
SetRows myImage = data.get(position);
holder.txtTitle.setText(myImage.name);
holder.txtID.setText(myImage.id);
int outImage=myImage.image;
holder.imgIcon.setImageResource(outImage);
return row;
}
static class ImageHolder
{
ImageView imgIcon;
TextView txtTitle;
TextView txtID;
}
#Override
public Filter getFilter()
{
if (filter == null) {
Log.i("Before Filter", "Before Filter");
filter = new PkmnNameFilter();
}
return filter;
}
private class PkmnNameFilter extends Filter
{
#Override
protected FilterResults performFiltering(CharSequence constraint)
{
FilterResults results = new FilterResults();
String prefix = constraint.toString().toLowerCase();
if (prefix == null || prefix.length() == 0)
{
Log.i("prefix is null or 0", "prefix is null or 0");
ArrayList<SetRows> list = new ArrayList<SetRows>(original);
results.values = list;
results.count = list.size();
}
else
{
Log.i("prefix is !null or !0", "prefix is !null or !0");
final ArrayList<SetRows> list = new ArrayList<SetRows>(original);
final ArrayList<SetRows> nlist = new ArrayList<SetRows>();
int count = list.size();
for (int i=0; i<count; i++)
{
final SetRows pkmn = list.get(i);
final String value = pkmn.getName().toLowerCase();
if (value.startsWith(prefix))
{
nlist.add(pkmn);
}
}
results.values = nlist;
results.count = nlist.size();
}
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
Log.i("publish result", "publish result");
fitems = (ArrayList<SetRows>)results.values;
clear();
int count = fitems.size();
for (int i=0; i<count; i++)
{
SetRows pkmn = (SetRows)fitems.get(i);
add(pkmn);
}
}
}
}
My partial MainActivity file:
inputSearch = (EditText) findViewById(R.id.etSearch);
dataList = (ListView) findViewById(R.id.lvFiles);
for (int y=0; y<strNames.length;y++) {
name = strNamesOfAllah[y];
meaning = strMeaning[y];
rowsArray.add(new SetRows(R.drawable.icon, name, meaning));
}
adapter = new SetRowsCustomAdapter(MainActivity.this, R.layout.customlist, rowsArray);
dataList.setAdapter(adapter);
dataList.setClickable(true);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
//MainActivity.this.adapter.getFilter().filter(cs);
//String text = inputSearch.getText().toString().toLowerCase();
adapter.getFilter().filter(cs.toString().toLowerCase(Locale.US));
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
//TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
//TODO Auto-generated method stub
}
});
In the LogCat I do see the following:
12-12 12:15:57.077: I/Before Filter(720): Before Filter
12-12 12:15:57.106: I/prefix is !null or !0(720): prefix is !null or !0
12-12 12:15:57.216: I/publish result(720): publish result
I modified my code and was able to get it to work. If anyone wants to use it, be my guest :)
SetRows Java file:
public class SetRows {
int image;
String name;
String id;
public int getImage () {
return image;
}
public void setImage (int image) {
this.image = image;
}
public String getName () {
return name;
}
public void setName (String name) {
this.name = name;
}
public String getID () {
return id;
}
public void setID (String id) {
this.id = id;
}
public SetRows(int image, String name, String id) {
super();
this.image = image;
this.name = name;
this.id = id;
}
#Override
public String toString() {
return image + " " + name + " " + id;
}
}
SetRowsCustomAdapter Java file:
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.ImageView;
import android.widget.TextView;
public class SetRowsCustomAdapter extends ArrayAdapter<SetRows> {
Context context;
int layoutResourceId;
ArrayList<SetRows> data=new ArrayList<SetRows>(); //data = countryList
private ArrayList<SetRows> originalList;
private NameFilter filter;
public SetRowsCustomAdapter(Context context, int layoutResourceId, ArrayList<SetRows> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
//this.data.addAll(data);
this.originalList = new ArrayList<SetRows>();
this.originalList.addAll(data);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ImageHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ImageHolder();
holder.txtTitle = (TextView)row.findViewById(R.id.txtTitle);
holder.imgIcon = (ImageView)row.findViewById(R.id.imgIcon);
holder.txtID = (TextView)row.findViewById(R.id.txtModDate);
row.setTag(holder);
}
else
{
holder = (ImageHolder)row.getTag();
}
SetRows myImage = data.get(position);
holder.txtTitle.setText(myImage.name);
holder.txtID.setText(myImage.id);
int outImage=myImage.image;
holder.imgIcon.setImageResource(outImage);
return row;
}
static class ImageHolder
{
ImageView imgIcon;
TextView txtTitle;
TextView txtID;
}
#Override
public Filter getFilter() {
if (filter == null){
filter = new NameFilter();
}
return filter;
}
private class NameFilter extends Filter
{
#Override
protected FilterResults performFiltering(CharSequence constraint) {
constraint = constraint.toString().toLowerCase();
FilterResults result = new FilterResults();
if(constraint != null && constraint.toString().length() > 0)
{
ArrayList<SetRows> filteredItems = new ArrayList<SetRows>();
for(int i = 0, l = originalList.size(); i < l; i++)
{
SetRows nameList = originalList.get(i);
if(nameList.toString().toLowerCase().contains(constraint))
filteredItems.add(nameList);
}
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,
FilterResults results) {
data = (ArrayList<SetRows>)results.values;
notifyDataSetChanged();
clear();
for(int i = 0, l = data.size(); i < l; i++)
add(data.get(i));
notifyDataSetInvalidated();
}
}
}
Everything else stayed the same :)
I hope people find it useful for their own app.
You don't need to implement your own Filter, if you are using an ArrayAdapter you can just override the toString method in SetHelpRows to return the name. Then you can call the ArrayAdapters built-in Filter.
This is not a direct answer to your question but rather a suggestion to change your implementation.
please try this in your publishResults function
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
Log.i("publish result", "publish result");
data = (ArrayList<SetRows>)results.values;
notifyDataSetChanged();
}
In SiB's answer, the Filter can be improved by overriding getCount()
#Override
public int getCount()
{
return data.size();
}