i'm trying to implement search on my list view
this is my custom adapter:
public class AllContactsAdapter extends BaseAdapter implements Filterable {
Context context;
ArrayList<Contact> contactList;
ArrayList<Contact> mStringFilterList;
ValueFilter valueFilter;
public AllContactsAdapter(Context context, ArrayList<Contact> list) {
this.context = context;
contactList = list;
mStringFilterList = list;
}
#Override
public int getCount() {
return contactList.size();
}
#Override
public Object getItem(int position) {
return contactList.get(position);
}
#Override
public long getItemId(int position) {
return contactList.get(position).getID();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Contact item = contactList.get(position);
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.row_name_phone_view, null);
}
TextView name = (TextView) convertView.findViewById(R.id.txtAllFullName);
name.setText(item.getName());
TextView phone = (TextView) convertView.findViewById(R.id.txtAllPhoneNumber);
phone.setText(item.getPhoneNumber());
return convertView;
}
#Override
public Filter getFilter() {
if (valueFilter == null) {
valueFilter = new ValueFilter();
}
return valueFilter;
}
private class ValueFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint != null && constraint.length() > 0) {
ArrayList<Contact> filterList = new ArrayList<Contact>();
for (int i = 0; i < mStringFilterList.size(); i++) {
if ((mStringFilterList.get(i).getName().toUpperCase())
.contains(constraint.toString().toUpperCase())) {
Contact contact = new Contact(mStringFilterList.get(i)
.getName(), mStringFilterList.get(i)
.getPhoneNumber());
filterList.add(contact);
}
}
results.count = filterList.size();
results.values = filterList;
} else {
results.count = mStringFilterList.size();
results.values = mStringFilterList;
}
return results;
}
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
contactList = (ArrayList<Contact>) results.values;
notifyDataSetChanged();
}
}
}
this is my call in main activity:
#Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return false;
}
i'm getting this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.widget.Filter com.example.shaka.contactsmanager.AllContactsAdapter.getFilter()' on a null object reference
can you please help me?
The variable adapter is null and you're trying to call the method getFilter() on it.
You need to initialize the adapter variable before using it. I can't be sure of how to do it because I can't see the MainActivity code, but it's definetely this problem.
Related
I tried everything to remove the elements from my array without losing the json data of my SharedPreferences, if I don't add in my HashSet the data that I merged, I get an array without duplicate elements. This is what I want, add my model element without duplications in my array by loading the elements from the Json.
**Here my MyModel :**
public class MyModel {
Integer imageRes;
String textRes;
public MyModel(Integer imageRes, String textRes) {
this.imageRes = imageRes;
this.textRes = textRes;
}
public Integer getImageRes() {
return imageRes;
}
public void setImageRes(Integer imageRes) {
this.imageRes = imageRes;
}
public String getTextRes() {
return textRes;
}
public void setTextRes(String textRes) {
this.textRes = textRes;
}
}
And here my Holder
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.myViewHolder> {
public MyAdapter(ArrayList<MyModel> models) {
this.models = models;
}
private final ArrayList<MyModel> models;
#NonNull
#Override
public myViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.items, parent,false);
return new myViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull myViewHolder holder, int position) {
holder.setIsRecyclable(false);
holder.imageItem.setImageResource(models.get(position).getImageRes());
holder.textItem.setText(models.get(position).getTextRes());
}
public ArrayList<MyModel> getModels() {
return models;
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
#Override
public int getItemViewType(int position) {
return super.getItemViewType(position);
}
#Override
public int getItemCount() {
return (models == null) ? 0 : models.size();
}
#Override
public void setHasStableIds(boolean hasStableIds) {
super.setHasStableIds(hasStableIds);
}
static class myViewHolder extends RecyclerView.ViewHolder{
ImageView imageItem;
TextView textItem;
public myViewHolder(#NonNull View itemView){
super(itemView);
imageItem = itemView.findViewById(R.id.ItemMarker);
textItem = itemView.findViewById(R.id.itemTxt);
}
}
}
**And here my problem :**
if(models != null){
try {
try{
SharedPreferences ListDatas = getSharedPreferences("SavedList", MODE_PRIVATE);
Gson gson = new Gson();
String json = ListDatas.getString("ListKey", null);
Type type = new TypeToken<ArrayList<MyModel>>(){}.getType();
models = gson.fromJson(json, type);
list.setHasFixedSize(true);
if(adapter != null){
adapter.setHasStableIds(true);
}
list.setAdapter(adapter);
list.setBackgroundColor(R.color.items);
list.setDuplicateParentStateEnabled(false);
models.ensureCapacity(100);
adapter = new MyAdapter(models);
NewModel = models;
Set<MyModel> DelItems = new HashSet<>();
DelItems.add(new MyModel(R.drawable.marker, "Commande en cours..." + "\n" + "Date : " + dateFormat + "\n" + "Nettoyage enregistré à : " + heure + "H" + minutes));
Set<MyModel> DelItems2 = new HashSet<>(NewModel);
NewModel.clear();
Set<MyModel> DelItemsFinal = new HashSet<>(DelItems2);
DelItemsFinal.addAll(DelItems2);
DelItemsFinal.addAll(DelItems);
Set<MyModel> DelItemsFinal2 = new LinkedHashSet<>(DelItemsFinal);
NewModel.clear();
NewModel.addAll(DelItemsFinal2);
DelItems.clear();
DelItems2.clear();
adapter.notifyDataSetChanged();
lastPosition = NewModel.size() -1;
layoutManager.scrollToPosition(lastPosition);
InfosHisto.setText("Votre historique de commande");
} catch (JsonSyntaxException e) {
e.printStackTrace();
}
I am very new to Android programming. I can't find a solution for my current problem which I've been trying to solve for days.
I want to click on item of populated Array List and get the position i.e. the searched word result in Cardview (neither ItemClickListener nor OnSuggestionListener did work here. Here is my code of MainActivity and I would be very thankful if somebody could help me out:
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
SearchAdapter adapter;
MaterialSearchBar materialSearchBar;
List<String> suggestList = new ArrayList<>();
Database database;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//init View
recyclerView = (RecyclerView) findViewById(R.id.recycler_search);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
materialSearchBar = (MaterialSearchBar) findViewById(R.id.search_bar);
database = new Database(this);
materialSearchBar.setHint("Search");
materialSearchBar.setCardViewElevation(10);
loadSuggestList();
materialSearchBar.addTextChangeListener (new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
List<String> suggest = new ArrayList<>();
for (String search : suggestList) {
if (search.toLowerCase().contains(materialSearchBar.getText().toLowerCase()))
suggest.add(search);
}
materialSearchBar.setLastSuggestions(suggest);
}
#Override
public void afterTextChanged(Editable s) {
}
});
materialSearchBar.setOnSearchActionListener (new MaterialSearchBar.OnSearchActionListener() {
#Override
public void onSearchStateChanged(boolean enabled) {
if (!enabled)
adapter = new SearchAdapter(getBaseContext(), database.getLughats());
recyclerView.setAdapter(adapter);
}
#Override
public void onSearchConfirmed(CharSequence text) {
startSearch(text.toString());
}
#Override
public void onButtonClicked(int buttonCode) {
}
});
adapter = new SearchAdapter(this, database.getLughats());
recyclerView.setAdapter(adapter);
}
private void startSearch(String text) {
adapter = new SearchAdapter(this, database.getLughatByWort(text));
recyclerView.setAdapter(adapter);
}
private void loadSuggestList() {
suggestList = database.getWorts();
materialSearchBar.setLastSuggestions(suggestList);
}
}```
Let me know if I should post here also my AdapterCode for the ViewHolder.
Thank you for your help in advance!
Here ist my AdapterCode:
class SearchViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
RecyclerItemClick itemClickListener;
public TextView wort, praeteritum, partizip2, artikelGrammatik, uebersetzung1, uebersetzung2;
public ImageButton button1, button2;
public SearchViewHolder(#NonNull View itemView) {
super(itemView);
wort = (TextView)itemView.findViewById(R.id.wort);
praeteritum = (TextView)itemView.findViewById(R.id.praeteritum);
partizip2 = (TextView)itemView.findViewById(R.id.partizip2);
artikelGrammatik = (TextView)itemView.findViewById(R.id.artikelGrammatik);
uebersetzung1 = (TextView)itemView.findViewById(R.id.uebersetzung1);
uebersetzung2 = (TextView)itemView.findViewById(R.id.uebersetzung2);
button1 = (ImageButton)itemView.findViewById(R.id.button_id_1);
button2 = (ImageButton) itemView.findViewById(R.id.button_id_2);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
this.itemClickListener.onItemClickListener(v, getLayoutPosition());
}
public void setItemClickListener(RecyclerItemClick ic) {
this.itemClickListener = ic;
}
}
public class SearchAdapter extends RecyclerView.Adapter<SearchViewHolder> {
private Context context;
private List<Lughat> lughats;
public SearchAdapter(Context context, List<Lughat> lughats) {
this.context = context;
this.lughats = lughats;
}
#NonNull
#Override
public SearchViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
final View itemView = inflater.inflate(R.layout.layout_item, parent, false);
return new SearchViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull final SearchViewHolder holder, final int position) {
holder.wort.setText(lughats.get(position).getWort());
holder.praeteritum.setText(lughats.get(position).getPraeteritum());
holder.partizip2.setText(lughats.get(position).getPartizip2());
holder.artikelGrammatik.setText(lughats.get(position).getArtikelGrammatik());
holder.uebersetzung1.setText(lughats.get(position).getUebersetzung1());
holder.uebersetzung2.setText(lughats.get(position).getUebersetzung2());
CharSequence praet;
praet = holder.praeteritum.getText();
if (praet.length() == 0) {
holder.praeteritum.setVisibility(View.GONE);
holder.button1.setVisibility(View.GONE);
} else {
holder.praeteritum.setVisibility(View.VISIBLE);
holder.button1.setVisibility(View.VISIBLE);
}
CharSequence part2;
part2 = holder.partizip2.getText();
if (part2.length() == 0) {
holder.partizip2.setVisibility(View.GONE);
} else {
holder.partizip2.setVisibility(View.VISIBLE);
}
CharSequence artGr;
artGr = holder.artikelGrammatik.getText();
if (artGr.length() == 0) {
holder.artikelGrammatik.setVisibility(View.GONE);
holder.button2.setVisibility(View.GONE);
} else {
holder.artikelGrammatik.setVisibility(View.VISIBLE);
holder.button2.setVisibility(View.VISIBLE);
}
CharSequence ueb2;
ueb2 = holder.uebersetzung2.getText();
if (ueb2.length() == 0) {
holder.uebersetzung2.setVisibility(View.GONE);
} else {
holder.uebersetzung2.setVisibility(View.VISIBLE);
}
holder.button1.setOnClickListener(new ToastMaker(context.getApplicationContext()));
holder.button2.setOnClickListener(new ToastMaker(context.getApplicationContext()));
holder.setItemClickListener(new RecyclerItemClick() {
#Override
public void onItemClickListener(View v, int position) {
Toast.makeText(context, "Begriff", Toast.LENGTH_LONG).show();
}
});
}
#Override
public int getItemCount() {
return lughats.size();
}
}
If I do it also with OnClickListener it does not work too, it does not call the method startSearch.
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CharSequence text = materialSearchBar.getText();
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
startSearch(text.toString());
}
I got trouble filtering data in recylerview through searchview action bar. I got an project example and trying to implement the method. But the data won't filtering.
I put this on my fragment (search view)
public override void OnCreateOptionsMenu(IMenu menu,MenuInflater menuInflater)
{
//SearchMenu
menuInflater.Inflate(Resource.Menu.nav_search, menu);
var searchItem = menu.FindItem(Resource.Id.action_search);
var provider = MenuItemCompat.GetActionView(searchItem);
mSearchView = provider.JavaCast<Android.Support.V7.Widget.SearchView>();
mSearchView.QueryTextChange += (s, e) => mLocationsAdapter.Filter.InvokeFilter(e.NewText);
mSearchView.QueryTextSubmit += (s, e) =>
{
Toast.MakeText(this.Activity, "You searched: " + e.Query, ToastLength.Short).Show();
e.Handled = true;
};
MenuItemCompat.SetOnActionExpandListener(searchItem, new SearchViewExpandListener(mLocationsAdapter));
}
And this is my adapter:
namespace ShopDiaryApp.Adapter
{
public class LocationsRecycleAdapter : RecyclerView.Adapter,IFilterable
{
private readonly Activity mActivity;
private List<LocationViewModel> mLocations;
private List<LocationViewModel> mFilteredLocations;
private int mSelectedPosition = -1;
public LocationsRecycleAdapter(List<LocationViewModel> locations, Activity activity)
{
this.mLocations = locations;
this.mActivity = activity;
Filter = new LocationFilter(this);
}
public override int ItemCount => this.mLocations.Count;
public Filter Filter { get; private set; }
public event EventHandler<int> ItemClick;
private void OnClick(int position)
{
this.ItemClick?.Invoke(this, position);
NotifyItemChanged(position);
mSelectedPosition = position;
NotifyItemChanged(position);
}
public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
if (this.mLocations.Count > 0)
{
var vh = holder as ViewHolder;
if (vh != null)
{
var location = this.mLocations[position];
vh.LocationName.Text = location.Name;
vh.LocationAddress.Text = location.Address;
vh.LocationDescription.Text = location.Description;
vh.ItemView.Selected = (mSelectedPosition == position);
}
}
}
public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
{
var v = LayoutInflater.From(parent.Context).Inflate(Resource.Layout.AdapterLocations, parent, false);
var vh = new ViewHolder(v, this.OnClick);
return vh;
}
public class ViewHolder : RecyclerView.ViewHolder
{
public ViewHolder(IntPtr javaReference, JniHandleOwnership transfer)
: base(javaReference, transfer)
{
}
public ViewHolder(View itemView, Action<int> listener)
: base(itemView)
{
this.LocationName = itemView.FindViewById<TextView>(Resource.Id.textviewLocationsAdapterName);
this.LocationAddress = itemView.FindViewById<TextView>(Resource.Id.textviewLocationAdapterAddress);
this.LocationDescription = itemView.FindViewById<TextView>(Resource.Id.textviewLocationAdapterDescription);
itemView.Click += (sender, e) => listener(this.LayoutPosition);
}
public TextView LocationName { get; }
public TextView LocationAddress { get; }
public TextView LocationDescription { get; }
}
private class LocationFilter : Filter
{
private readonly LocationsRecycleAdapter mLocationAdapter;
public LocationFilter(LocationsRecycleAdapter adapter)
{
mLocationAdapter = adapter;
}
protected override FilterResults PerformFiltering(ICharSequence constraint)
{
var returnObj = new FilterResults();
var results = new List<LocationViewModel>();
if (mLocationAdapter.mLocations == null)
mLocationAdapter.mLocations = mLocationAdapter.mFilteredLocations;
if (constraint == null) return returnObj;
if (mLocationAdapter.mLocations != null && mLocationAdapter.mLocations.Any())
{
// Compare constraint to all names lowercased.
// It they are contained they are added to results.
results.AddRange(
mLocationAdapter.mLocations.Where(
location => location.Name.ToLower().Contains(constraint.ToString())));
}
// Nasty piece of .NET to Java wrapping, be careful with this!
returnObj.Values = FromArray(results.Select(r => r.ToJavaObject()).ToArray());
returnObj.Count = results.Count;
constraint.Dispose();
return returnObj;
}
protected override void PublishResults(ICharSequence constraint, FilterResults results)
{
using (var values = results.Values)
mLocationAdapter.mFilteredLocations = values.ToArray<Java.Lang.Object>()
.Select(r => r.ToNetObject<LocationViewModel>()).ToList();
mLocationAdapter.NotifyDataSetChanged();
// Don't do this and see GREF counts rising
//constraint.Dispose();
//results.Dispose();
}
}
}
}
In protected override void PublishResults(ICharSequence constraint, FilterResults results) I got the filtered data. But the recyler view wont update (not filtered). Am I missing something?? Thanks for help :)
I think that you should be using mFilteredLocations in OnBindViewHolder:
if (this.mFilteredLocations.Count > 0)
...
var location = this.mFilteredLocations[position];
So that your mLocations stays as your original list of locations and what you show on your RecyclerView is always your filtered list.
Obviously at the beginning both mFilteredLocations and mLocations have to have the same items.
public LocationsRecycleAdapter(List<LocationViewModel> locations, Activity activity)
{
this.mLocations = locations;
this.mFilteredLocations = locations;
this.mActivity = activity;
Filter = new LocationFilter(this);
}
And on your filter you are changing mFilteredLocations and notify the data set changed so that all data is refreshed. But this will only take effect if you do the aforementioned changes.
Here you have another related question/answer but on Android if it can serve you as a further guidance.
HIH
I'm using recycler view as a single child inside the swipe refresh layout. Initially, its not scrolling smoothly while loading data from webservice both upwards and downwards. But after first scroll, it scrolls smoothly. How to make it scroll smoothly at very first scroll itself.
private RecyclerView newsFeedList;
newsFeedList = (RecyclerView) view.findViewById(R.id.rv_feed_list);
newsFeedList.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
llm.setOrientation(LinearLayoutManager.VERTICAL);
newsFeedList.setLayoutManager(llm);
newsFeedAdapter = new NewsFeedAdapter(getActivity(), new ArrayList<NewsFeedParser.NewsFeed>(), newsFeedList);
newsFeedList.setAdapter(newsFeedAdapter);
and updated recyclerview after getting response from web service by calling below method:
private void parseDataToNewsFeed(String response, boolean isLoadMore) {
Gson gson = new Gson();
NewsFeedParser newsFeedParser = gson.fromJson(response, NewsFeedParser.class);
if (newsFeedParser.data != null && newsFeedParser.data.size() > 0) {
if (isLoadMore) {
newsFeedAdapter.removeProgress(newsFeedAdapter.getItemCount());
newsFeedAdapter.addList(newsFeedParser.data);
} else {
currentPageCount = 1;
newsFeedAdapter.updateList(newsFeedParser.data);
}
} else {
newsFeedAdapter.updateList(newsFeedParser.data);
txtNoResult.setText(getString(R.string.no_clubs_socities_subscribed));
txtNoResult.setVisibility(View.VISIBLE);
}
}
Adaper class:
public class NewsFeedAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final DisplayImageOptions options;
private Context context;
private ArrayList<NewsFeedParser.NewsFeed> itemList;
private int lastVisibleItem, totalItemCount, visibleThreshold = 2;
private boolean loading;
public OnLoadMoreListener onLoadMoreListener;
private OnItemClickListener itemClickListener;
// private ImageLoader mImageLoader;
private final int VIEW_ITEM = 1;
private final int VIEW_PROG = 0;
private long mLastClickTimeListViewItem = 0;
public NewsFeedAdapter(Context context, ArrayList<NewsFeedParser.NewsFeed> itemList, RecyclerView recyclerView) {
this.context = context;
this.itemList = itemList;
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_default_news)
.showImageForEmptyUri(R.drawable.ic_default_news)
.showImageOnFail(R.drawable.ic_default_news)
.cacheInMemory(true)
.cacheOnDisk(true)
.considerExifParams(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
if (recyclerView.getLayoutManager() instanceof LinearLayoutManager) {
final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
totalItemCount = linearLayoutManager.getItemCount();
lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
if (!loading && totalItemCount <= (lastVisibleItem + visibleThreshold)) {
if (onLoadMoreListener != null) {
onLoadMoreListener.onLoadMore();
}
loading = true;
}
}
});
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder vh;
if (viewType == VIEW_ITEM) {
View itemView = LayoutInflater.from(context).inflate(R.layout.fragment_news_feed_trending_list_item, parent, false);
vh = new NewsFeedViewHolder(itemView);
} else {
View progView = LayoutInflater.from(context).inflate(R.layout.view_refresh_footer, parent, false);
vh = new ProgressViewHolder(progView);
}
return vh;
}
#Override
public int getItemViewType(int position) {
return itemList.get(position) != null ? VIEW_ITEM : VIEW_PROG;
}
#Override
public int getItemCount() {
return itemList.size();
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
if (holder instanceof NewsFeedViewHolder) {
final NewsFeedParser.NewsFeed singleItem = itemList.get(position);
((NewsFeedViewHolder) holder).txtNews.setText(Html.fromHtml(singleItem.title));
((NewsFeedViewHolder) holder).txtDays.setText(DateConversion.getStatusTiming(context, singleItem.modified));
((NewsFeedViewHolder) holder).imgNewsPhoto.setImageResource(R.drawable.ic_default_news);
if (singleItem.featured_image != null) {
if (singleItem.featured_image.attachment_meta != null) {
if (singleItem.featured_image.attachment_meta.sizes != null) {
if (singleItem.featured_image.attachment_meta.sizes.thumbnail != null) {
if (!TextUtils.isNullOrEmpty(singleItem.featured_image.attachment_meta.sizes.thumbnail.url)) {
ImageLoader.getInstance().displayImage(singleItem.featured_image.attachment_meta.sizes.thumbnail.url, ((NewsFeedViewHolder) holder).imgNewsPhoto, options);
} else {
if (!TextUtils.isNullOrEmpty(singleItem.featured_image.source)) {
ImageLoader.getInstance().displayImage(singleItem.featured_image.source, ((NewsFeedViewHolder) holder).imgNewsPhoto, options);
}
}
}
}
}
}
if (singleItem.read_status == 0) {
((NewsFeedViewHolder) holder).rlFeedItem.setBackgroundColor(ContextCompat.getColor(context, R.color.clr_news_feed_item_bg));
} else {
((NewsFeedViewHolder) holder).rlFeedItem.setBackgroundColor(ContextCompat.getColor(context, R.color.transparent));
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (SystemClock.elapsedRealtime() - mLastClickTimeListViewItem < 1000) {
return;
}
mLastClickTimeListViewItem = SystemClock.elapsedRealtime();
if (itemClickListener != null) {
itemClickListener.onItemClick(singleItem);
singleItem.read_status = 1;
notifyItemChanged(position);
}
}
});
} else {
((ProgressViewHolder) holder).progressBar.setLinearProgress(true);
}
}
public void addList(ArrayList<NewsFeedParser.NewsFeed> items) {
if (items == null) {
this.itemList.add(null);
} else {
for (NewsFeedParser.NewsFeed item : items) {
this.itemList.add(item);
}
}
notifyDataSetChanged();
}
public void updateList(ArrayList<NewsFeedParser.NewsFeed> items) {
if (items != null) {
this.itemList = items;
}
notifyDataSetChanged();
}
public void removeProgress(int itemCount) {
this.itemList.remove(itemCount - 1);
notifyItemRemoved(itemCount);
}
public static class NewsFeedViewHolder extends RecyclerView.ViewHolder {
USUTextView txtNews, txtDays;
ImageView imgNewsPhoto;
RelativeLayout rlFeedItem;
public NewsFeedViewHolder(View itemView) {
super(itemView);
txtNews = (USUTextView) itemView.findViewById(R.id.txt_news);
txtDays = (USUTextView) itemView.findViewById(R.id.txt_days);
imgNewsPhoto = (ImageView) itemView.findViewById(R.id.img_news_photo);
rlFeedItem = (RelativeLayout) itemView.findViewById(R.id.rl_feed_list_item);
}
}
public static class ProgressViewHolder extends RecyclerView.ViewHolder {
public ProgressWheel progressBar;
public ProgressViewHolder(View progView) {
super(progView);
progressBar = (ProgressWheel) progView.findViewById(R.id.progress_bar);
}
}
public void setLoaded() {
loading = false;
}
public void setOnLoadMoreListener(OnLoadMoreListener onLoadMoreListener) {
this.onLoadMoreListener = onLoadMoreListener;
}
public interface OnLoadMoreListener {
void onLoadMore();
}
public void setOnItemClickListener(OnItemClickListener recyclerClickListener) {
this.itemClickListener = recyclerClickListener;
}
public interface OnItemClickListener {
void onItemClick(NewsFeedParser.NewsFeed item);
}
}
Please suggest me any idea.....
I want to display a list in fragment. i am using a custom arraylist. it is giving me classcast exception. i searched for the soluo solvetion but it dosnt solve my problem. i am new to android so i have no idea how this.. can anyone help..
this is my Item class
public class Item {
public String item_name;
public String item_desc;
public String item_qty;
public Item(String item_name, String item_desc,String item_qty) {
super();
this.item_name = item_name;
this.item_desc = item_desc;
this.item_qty = item_qty;
}
public String getItem_name(){
return item_name;
}
public void setItem_name(String item_name)
{
this.item_name=item_name;
}
public String getItem_desc()
{
return item_desc;
}
public void setItem_desc(String item_desc)
{
this.item_desc=item_desc;
}
public String getItem_qty()
{
return item_qty;
}
public void setItem_qty(String item_qty) {
this.item_qty = item_qty;
}
}
this is my addstock fragment
public class AddStock extends Fragment {
EditText edit_item_name,edit_item_desc,edit_item_qty;
Button btn_save;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_add_stock, container, false);
edit_item_name = (EditText)rootView.findViewById(R.id.edittext_item_name);
edit_item_desc = (EditText) rootView.findViewById(R.id.editText_item_desc);
edit_item_qty = (EditText) rootView.findViewById(R.id.editText_item_qty);
btn_save = (Button) rootView.findViewById(R.id.button_Save);
MainActivity act=(MainActivity)this.getActivity();
final ArrayList stock = act.arrayList;
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String item_name=edit_item_name.getText().toString();
String item_desc=edit_item_desc.getText().toString();
String item_qty=edit_item_qty.getText().toString();
stock.add(item_name);
stock.add(item_desc);
stock.add(item_qty);
Toast.makeText(AddStock.this.getActivity(), "Saved", Toast.LENGTH_LONG).show();
}
});
return rootView;
}
}
this is my viewstock fragment
public class ViewStock extends Fragment {
public ViewStock() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootview= inflater.inflate(R.layout.fragment_view_stock, container, false);
ListView listview = (ListView)rootview.findViewById(R.id.list);
// Context mCtx = getActivity().getApplicationContext();
MainActivity act=(MainActivity)this.getActivity();
ItemAdapter adapter = new ItemAdapter(getActivity(),R.layout.list_item,act.arrayList);
listview.setAdapter(adapter);
return rootview;
}
}
this is my main activity
Public class MainActivity extends AppCompatActivity {
private Toolbar mToolbar;
private DrawerLayout mDrawerLayout;
NavigationView mNavigationView;
FrameLayout mContentFrame;
FragmentManager fragmentManager;
private static final String PREFERENCES_FILE = "mymaterialapp_settings";
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
private boolean mUserLearnedDrawer;
private boolean mFromSavedInstanceState;
private int mCurrentSelectedPosition;
public ArrayList<Item> arrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nav_drawer);
setUpToolbar();
arrayList=new ArrayList<Item>();
mDrawerLayout = (DrawerLayout) findViewById(R.id.nav_drawer);
mUserLearnedDrawer = Boolean.valueOf(readSharedSetting(this, PREF_USER_LEARNED_DRAWER, "false"));
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
setUpNavDrawer();
mNavigationView = (NavigationView) findViewById(R.id.nav_view);
mContentFrame = (FrameLayout) findViewById(R.id.nav_contentframe);
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
Fragment newFragment;
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
menuItem.setChecked(true);
switch (menuItem.getItemId()) {
case R.id.navigation_item_1:
newFragment = new AddStock();
transaction.replace(R.id.nav_contentframe, newFragment);
transaction.addToBackStack(null);
transaction.commit();
mCurrentSelectedPosition = 0;
mDrawerLayout.closeDrawers();
return true;
case R.id.navigation_item_2:
newFragment = new ViewStock();
transaction.replace(R.id.nav_contentframe, newFragment);
transaction.addToBackStack(null);
transaction.commit();
mCurrentSelectedPosition = 1;
return true;
default:
return true;
}
}
});
//fragmentManager.beginTransaction().replace(R.id.nav_contentframe, fragment).commit();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION, 0);
Menu menu = mNavigationView.getMenu();
menu.getItem(mCurrentSelectedPosition).setChecked(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
return true;
}
return super.onOptionsItemSelected(item);
}
private void setUpToolbar() {
mToolbar = (Toolbar) findViewById(R.id.toolbar);
if (mToolbar != null) {
setSupportActionBar(mToolbar);
}
}
private void setUpNavDrawer() {
if (mToolbar != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mToolbar.setNavigationIcon(R.drawable.ic_drawer);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDrawerLayout.openDrawer(GravityCompat.START);
}
});
}
if (!mUserLearnedDrawer) {
mDrawerLayout.openDrawer(GravityCompat.START);
mUserLearnedDrawer = true;
saveSharedSetting(this, PREF_USER_LEARNED_DRAWER, "true");
}
}
public static void saveSharedSetting(Context ctx, String settingName, String settingValue) {
SharedPreferences sharedPref = ctx.getSharedPreferences(PREFERENCES_FILE, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(settingName, settingValue);
editor.apply();
}
public static String readSharedSetting(Context ctx, String settingName, String defaultValue) {
SharedPreferences sharedPref = ctx.getSharedPreferences(PREFERENCES_FILE, Context.MODE_PRIVATE);
return sharedPref.getString(settingName, defaultValue);
}
}
this is my ItemAdapter
public class ItemAdapter extends ArrayAdapter<Item> {
Context context;
public ItemAdapter(Context context, int resourceId,
ArrayList<Item> items) {
super(context, resourceId, items);
this.context = context;
}
/* public int getCount() {
return items.size();
}
public Item getItem(int position) {
return items.get(position);
}
public long getItemId(int position) {
return position;
}
*/
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
Item rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.list_item, null);
holder.txtItemName = (TextView) convertView.findViewById(R.id.txt_item_name);
holder.txtItemDesc = (TextView) convertView.findViewById(R.id.txt_item_desc);
holder.txtItemQty = (TextView) convertView.findViewById(R.id.txt_item_qty);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtItemName.setText(rowItem.getItem_name());
holder.txtItemDesc.setText(rowItem.getItem_desc());
holder.txtItemQty.setText(rowItem.getItem_qty());
return convertView;
}
private class ViewHolder {
TextView txtItemName;
TextView txtItemDesc;
TextView txtItemQty;
}
}
this is the exception m getting
java.lang.ClassCastException: java.lang.String cannot be cast to com.example.owner.stock.Item
at com.example.owner.stock.ItemAdapter.getView(ItemAdapter.java:60)
at android.widget.AbsListView.obtainView(AbsListView.java:2344)
at android.widget.ListView.makeAndAddView(ListView.java:1864)
at android.widget.ListView.fillDown(ListView.java:698)
at android.widget.ListView.fillFromTop(ListView.java:759)
at android.widget.ListView.layoutChildren(ListView.java:1673)
at android.widget.AbsListView.onLayout(AbsListView.java:2148)
at android.view.View.layout(View.java:15614)
at android.view.ViewGroup.layout(ViewGroup.java:4968)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
at android.view.View.layout(View.java:15614)
at android.view.ViewGroup.layout(ViewGroup.java:4968)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
at android.view.View.layout(View.java:15614)
at android.view.ViewGroup.layout(ViewGroup.java:4968)
at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1076)
at android.view.View.layout(View.java:15614)
at android.view.ViewGroup.layout(ViewGroup.java:4968)
at android.support.v4.widget.DrawerLayout.onLayout(DrawerLayout.java:907)
at android.view.View.layout(View.java:15614)
at android.view.ViewGroup.layout(ViewGroup.java:4968)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
at android.view.View.layout(View.java:15614)
at android.view.ViewGroup.layout(ViewGroup.java:4968)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1703)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1557)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1466)
at android.view.View.layout(View.java:15614)
at android.view.ViewGroup.layout(ViewGroup.java:4968)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
at android.view.View.layout(View.java:15614)
at android.view.ViewGroup.layout(ViewGroup.java:4968)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1703)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1557)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1466)
at android.view.View.layout(View.java:15614)
at android.view.ViewGroup.layout(ViewGroup.java:4968)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
at android.view.View.layout(View.java:15614)
at android.view.ViewGroup.layout(ViewGroup.java:4968)
at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2102)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1859)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1077)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5884)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
at android.view.Choreographer.doCallbacks(Choreographer.java:580)
at android.view.Choreographer.doFrame(Choreographer.java:550)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5312)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
07-22 23:34:00.334 20992-20992/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
You are adding String objects to a list that is typed to take Item objects.
Instead of:
stock.add(someString);
stock.add(someString);
stock.add(someString);
Do
stock.add(new Item(someString, someString, someString));