I am building a shopping cart where the customer can add to cart the item, but my problem is how can I achieve this king of list when the customer views their cart they show the info of the seller and the item, i have used nested recyclerview.
public class adapter extends RecyclerView.Adapter<adapter.ViewHolder> {
List<testCartUsers> cartModelList;
List<testSellerModel> sellerModelList;
Context context;
public adapter(List<testCartUsers> cartModelList, List<testSellerModel> sellerModelList, Context context) {
this.cartModelList = cartModelList;
this.sellerModelList = sellerModelList;
this.context = context;
}
#NonNull
#Override
public adapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = null;
if(viewType == 0) {
v = LayoutInflater.from(parent.getContext()).inflate(R.layout.itemrow , parent , false);
}else {
v = LayoutInflater.from(parent.getContext()).inflate(R.layout.child_item , parent , false);
}
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull adapter.ViewHolder holder, int position) {
testSellerModel data = sellerModelList.get(position);
for (int i = 0; i< sellerModelList.size(); i++) {
holder.sellerName.setText(sellerModelList.get(position).getSeller_name() + " Seller_ID: "+ sellerModelList.get(position).getSeller_id());
for (int y = 0; y<cartModelList.size(); y++) {
if (cartModelList.get(y).getSeller_id() == sellerModelList.get(i).getSeller_id()) {
holder.child.setLayoutManager(new LinearLayoutManager(context));
childAdapter childAdapter = new childAdapter(Collections.singletonList(cartModelList.get(position)));
holder.child.setAdapter(childAdapter);
}
}
}
}
#Override
public int getItemCount() {
return sellerModelList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView sellerName;
RecyclerView child;
public ViewHolder(View v) {
super(v);
sellerName = v.findViewById(R.id.SellerName);
child = v.findViewById(R.id.childRecycler);
}
This what I expected Output of the cart list when the customer views their cart.
Related
I am having an EditText in a TTextInputLayout as a Row_item for my recycler view, On the click of a button I am incrementing the count value in that recycler view and adding the edit text views in the app. After having as many views as I want, I am putting some data in those EditTexts and After all this I press save button and all the data from EditTexts should save in a list. I tried the textwatcher Property in xamarin.android but not able to perform that.
In my activity I also tried
var view = addChildRecyclerView.FindViewHolderForAdapterPosition(i);
var holder = view as fragmentRecyclerViewAdapterViewHolder;
if (holder != null)
{
holder.childname.FindViewById<TextInputLayout>(Resource.Id.enterChildNameTextView);
childlisttosend.Add(holder.childname.EditText.Text);
But sometimes I get holder as a null and some valus are missed to be put in the list.
I tried textchange property but it puts every single alphabet in the list, like
for index 1 it is "m"
for index 2 it is "ma"
for index 3 it is "man"
for index 4 it is "mani"
for index 5 it is "manis"
for index 6 it is "manish"
It is of no use. Please sugggest a solution.
adapter is
namespace assessment1_part2_v2.Fragment
{
public class addFamilyFragment : DialogFragment
{
public TextInputLayout fathername, mothername, address;
public MaterialButton addchild, savebutton;
public ArrayAdapter adapter;
public ListView listview;
public familyData familydata = new familyData();
public List<childData> childrenList = new List<childData>();
public editTextAdapter EditTextAdapter;
public event EventHandler<DataSenderClass> famaDataSender;
public RecyclerView enterChildRecyclerView;
public List<string> addChildDummyData = new List<string>();
public TextInputLayout enterChildEditTExt;
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.Inflate(Resource.Layout.addfam_layout, container, false);
connectingViews(view);
buttonClicks();
return view;
}
public class DataSenderClass : EventArgs
{
public familyData data { get; set; }
}
private void buttonClicks()
{
addchild.Click += Addchild_Click;
savebutton.Click += Savebutton_Click;
}
private void Savebutton_Click(object sender, EventArgs e)
{
//father, mother and address
familydata.fathername = fathername.EditText.Text;
familydata.mothername = mothername.EditText.Text;
familydata.location = address.EditText.Text;
familydata.children = new List<childData>();
List<childData> list = new List<childData>();
List<string> dummyCheck = new List<string>();
for (int i = 0; i <= addChildDummyData.Count; i++)
{
var viewholder = enterChildRecyclerView.FindViewHolderForAdapterPosition(i);
var holder = viewholder as editTextAdapterViewHolder;
// holder.addChildEditTExt;
if(holder != null)
{
holder.addChildEditTExt.FindViewById<TextInputLayout>(Resource.Id.enterChildEditTExt);
dummyCheck.Add(holder.addChildEditTExt.EditText.Text);
}
}
var x = dummyCheck;
addChildDummyData.Clear();
famaDataSender?.Invoke(this, new DataSenderClass { data = familydata });
this.Dismiss();
}
private void Addchild_Click(object sender, EventArgs e)
{
if (addChildDummyData.Count == 0)
{
addChildDummyData.Add("");
EditTextAdapter = new editTextAdapter(addChildDummyData);
enterChildRecyclerView.SetLayoutManager(new LinearLayoutManager(Activity));
enterChildRecyclerView.SetAdapter(EditTextAdapter);
int x = enterChildRecyclerView.ChildCount;
}
else
{
addChildDummyData.Add("");
EditTextAdapter.NotifyItemInserted(addChildDummyData.Count - 1);
int x = enterChildRecyclerView.ChildCount;
}
}
private void connectingViews(View view)
{
fathername = view.FindViewById<TextInputLayout>(Resource.Id.enterFatherNameEditText);
mothername = view.FindViewById<TextInputLayout>(Resource.Id.enterMotherNameEditText);
address = view.FindViewById<TextInputLayout>(Resource.Id.enterAddressEditText);
addchild = view.FindViewById<MaterialButton>(Resource.Id.addChildButton);
savebutton = view.FindViewById<MaterialButton>(Resource.Id.saveButton);
enterChildRecyclerView = view.FindViewById<RecyclerView>(Resource.Id.enterChildRecyclerView);
//listview = (ListView)view.FindViewById(Resource.Id.enterChildRecyclerView);
}
}
} `
We couldn't see the code of editTextAdapter.
But you can refer to my code ,my RecyclerView has an Edittext in each item and we can get data from the input list.
I put TextWatcher in my RecyclerView.ViewHolder(PhotoViewHolder.cs).
PhotoViewHolder.cs
public class PhotoViewHolder: RecyclerView.ViewHolder
{
public ImageView Image { get; private set; }
public TextView Caption { get; private set; }
public CheckBox MyCheckBox { get; set; }
public bool IsChecked { get; set; }
public EditText MyEditText { get; set; }
public MyTextWatcher myTextWatcher;
public Button imAddBefore { get; private set; }
public Button imAddAfter { get; private set; }
public PhotoViewHolder(View itemView, Action<int> listener, MyTextWatcher myWatcher ) : base(itemView)
{
//Image = itemView.FindViewById<ImageView> (Resource.Id.imageView);
Caption = itemView.FindViewById<TextView>(Resource.Id.textView);
MyCheckBox = itemView.FindViewById<CheckBox>(Resource.Id.myCheckBox);
DeleteButton = itemView.FindViewById<Button>(Resource.Id.deleteBtn);
MyEditText = itemView.FindViewById<EditText>(Resource.Id.mEditText);
this.myTextWatcher = myWatcher;
// add TextWatcher here
MyEditText.AddTextChangedListener(myTextWatcher);
// other code
}
public class MyTextWatcher : Java.Lang.Object, ITextWatcher
{
int position;
public void AfterTextChanged(IEditable s)
{
}
public void BeforeTextChanged(ICharSequence s, int start, int count, int after)
{
}
public void OnTextChanged(ICharSequence s, int start, int before, int count)
{ //mInput is a field in my item model
PhotoAlbumAdapter.mPhotoAlbum[position].mInput = s.ToString();
}
public void updatePosition(int position)
{
this.position = position;
}
}
}
My RecyclerView.Adapter is PhotoAlbumAdapter.cs
PhotoAlbumAdapter.cs
public class PhotoAlbumAdapter: RecyclerView.Adapter
{
public event EventHandler<int> ItemClick;
public static List<Photo> mPhotoAlbum = new List<Photo>();
public static RecyclerView.Adapter adapter;
public PhotoAlbumAdapter(List<Photo> branchesList)
{
adapter = this;
mPhotoAlbum = branchesList;
}
public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
{
View itemView = LayoutInflater.From(parent.Context).Inflate(Resource.Layout.PhotoCardView, parent, false);
PhotoViewHolder vh = new PhotoViewHolder(itemView, OnClick, new PhotoViewHolder.MyTextWatcher());
return vh;
}
public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
PhotoViewHolder vh = holder as PhotoViewHolder;
Photo item= mPhotoAlbum[position];
vh.Caption.Text = item.Caption;
// here we call function `updatePosition` in our TextWatcher class
vh.myTextWatcher.updatePosition(vh.AdapterPosition);
vh.MyEditText.Text = item.mInput;
// other code
}
public override int ItemCount
{
get { return mPhotoAlbum.Count; }
}
// Raise an event when the item-click takes place:
void OnClick(int position)
{
if (ItemClick != null)
ItemClick(this, position);
}
}
In my activity, we can get the data from the recycleview like this:
List<Photo> items= new List<Photo>();
mAdapter = new PhotoAlbumAdapter(items);
mRecyclerView.SetAdapter(mAdapter);
The result is:
for (int i=0;i< items.Count;i++) {
Photo temp = items[i];
System.Diagnostics.Debug.WriteLine( "The "+i +" result is: "+" Caption= " + temp.Caption + "<---> input = " + temp.mInput);
}
I am getting Json data in list which has like 100 of items. I am passing this list to the recyclerview adapter. But i want to pass only 10 items at first. after 10 items when user scrolls the list it should load more data from the list.I have Implemented the scroll listeners and other adapter.I am not sure how to pass 10 items from the json list to adapter.
ScrollListener
public abstract class PaginationScrollListener extends RecyclerView.OnScrollListener {
LinearLayoutManager layoutManager;
/**
* Supporting only LinearLayoutManager for now.
*
* #param layoutManager
*/
public PaginationScrollListener(LinearLayoutManager layoutManager) {
this.layoutManager = layoutManager;
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int visibleItemCount = layoutManager.getChildCount();
int totalItemCount = layoutManager.getItemCount();
int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();
if (!isLoading() && !isLastPage()) {
if ((visibleItemCount + firstVisibleItemPosition) >= totalItemCount
&& firstVisibleItemPosition >= 0
&& totalItemCount >= getTotalPageCount()) {
loadMoreItems();
}
}
}
protected abstract void loadMoreItems();
public abstract int getTotalPageCount();
public abstract boolean isLastPage();
public abstract boolean isLoading();
}
Adapter
public class PaginationAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int ITEM = 0;
private static final int LOADING = 1;
private List<Movie> movies;
private Context context;
private boolean isLoadingAdded = false;
public PaginationAdapter(Context context) {
this.context = context;
movies = new ArrayList<>();
}
public List<Movie> getMovies() {
return movies;
}
public void setMovies(List<Movie> movies) {
this.movies = movies;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder viewHolder = null;
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
switch (viewType) {
case ITEM:
viewHolder = getViewHolder(parent, inflater);
break;
case LOADING:
View v2 = inflater.inflate(R.layout.item_progress, parent, false);
viewHolder = new LoadingVH(v2);
break;
}
return viewHolder;
}
#NonNull
private RecyclerView.ViewHolder getViewHolder(ViewGroup parent, LayoutInflater inflater) {
RecyclerView.ViewHolder viewHolder;
View v1 = inflater.inflate(R.layout.item_list, parent, false);
viewHolder = new MovieVH(v1);
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
Movie movie = movies.get(position);
switch (getItemViewType(position)) {
case ITEM:
MovieVH movieVH = (MovieVH) holder;
movieVH.textView.setText(movie.getTitle());
break;
case LOADING:
break;
}
}
#Override
public int getItemCount() {
return movies == null ? 0 : movies.size();
}
#Override
public int getItemViewType(int position) {
return (position == movies.size() - 1 && isLoadingAdded) ? LOADING : ITEM;
}
public void add(Movie mc) {
movies.add(mc);
notifyItemInserted(movies.size() - 1);
}
public void addAll(List<Movie> mcList) {
for (Movie mc : mcList) {
add(mc);
}
}
public void remove(Movie city) {
int position = movies.indexOf(city);
if (position > -1) {
movies.remove(position);
notifyItemRemoved(position);
}
}
public void clear() {
isLoadingAdded = false;
while (getItemCount() > 0) {
remove(getItem(0));
}
}
public boolean isEmpty() {
return getItemCount() == 0;
}
public void addLoadingFooter() {
isLoadingAdded = true;
add(new Movie());
}
public void removeLoadingFooter() {
isLoadingAdded = false;
int position = movies.size() - 1;
Movie item = getItem(position);
if (item != null) {
movies.remove(position);
notifyItemRemoved(position);
}
}
public Movie getItem(int position) {
return movies.get(position);
}
public MovieVH(View itemView) {
super(itemView);
textView = (TextView) itemView.findViewById(R.id.item_text);
}
}
protected class LoadingVH extends RecyclerView.ViewHolder {
public LoadingVH(View itemView) {
super(itemView);
}
}
}
**Getting Api response **
private void callApi() {
apiInterfacePages = ApiClient.getRetrofit().create(APIInterface.class);
Call<CamerasItem> camerasCall = apiInterfacePages.getCameras();
camerasCall.enqueue(new Callback<CamerasItem>() {
#Override
public void onResponse(Call<CamerasItem> call, Response<CamerasItem> response) {
CamerasItem camerasItem = response.body();
itemList = new ArrayList<>();
itemList = camerasItem.getItems();
Log.i("Item", "" + getChannel().getName());
for (int i = 0; i < itemList.size(); i++) {
if (itemList.get(i).getCategory().equals(getChannel().getName())){
if (!itemList.get(i).getUrlMjpeg().endsWith("=mediaRedirect")) {
String videoUrl = itemList.get(i).getUrlMjpeg();
String imageUrl = itemList.get(i).getThumbnail();
String name = itemList.get(i).getName();
String city = itemList.get(i).getCity();
String flag = itemList.get(i).getFlag();
String country= itemList.get(i).getCountry();
modelList.add(new MyModel(videoUrl, imageUrl, name, city, flag,country));
}
}
}
#Override
public void onFailure(Call<CamerasItem> call, Throwable t) {
Log.i("Item", "" + t.getMessage());
}
});
}
So now how to pass to 10 items to recyclerview for the first time and 10 items at each scroll.
You have to set Progressbar inside the activity's xml where Recyclerview is defined.
and loadThumbnail is a function to download thumbnail. it just gives a little delay to scroll down. Now the complete code for the adapter class is as following
public class CamerasAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<MyModel> list;
private Activity mActivity;
private static final int TYPE_VIDEO = 0, TYPE_ADD = 1;
private static final int PAGE_LIMIT = 5;
private int mCurrentLimit = PAGE_LIMIT;
private boolean mIsLoading;
RelativeLayout mLoaderProgress;
public CamerasAdapter(FragmentActivity activity, RelativeLayout loaderLayout) {
mActivity = activity;
mLoaderProgress = loaderLayout;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.li_web_cam_view, viewGroup, false);
return new CamsViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder viewHolder, int i) {
if (mCurrentLimit == (i + 1) && mCurrentLimit <= list.size() && !mIsLoading) {
mLoaderProgress.setVisibility(View.VISIBLE);
mIsLoading = true;
loadThumbnail(0, i + 1);
} else {
//do nothing
}
((CamsViewHolder) viewHolder).onBindData(mActivity, list.get(i), i);
((CamsViewHolder) viewHolder).emptyView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
itemClickListner.onClick(i, ((CamsViewHolder) viewHolder).tvCamName, list.get(i));
}
});
}
private void loadThumbnail(final int count, int position) {
try {
if (count > 2 || position >= list.size()) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
mIsLoading = false;
mCurrentLimit = mCurrentLimit + PAGE_LIMIT;
notifyItemChanged(position - count);
mLoaderProgress.setVisibility(View.GONE);
return;
}
}, 2000);
} else {
if (list.get(position) == null) {
loadThumbnail(count, position + 1);
} else {
Glide.with(mActivity).load(list.get(position).getImage_url()).downloadOnly(new SimpleTarget<File>() {
#Override
public void onResourceReady(File resource, GlideAnimation<? super File> glideAnimation) {
loadThumbnail((count + 1), (position + 1));
}
#Override
public void onLoadFailed(Exception e, Drawable errorDrawable) {
loadThumbnail((count + 1), (position + 1));
}
});
}
}
} catch (Exception e) {
e.printStackTrace();
mLoaderProgress.setVisibility(View.GONE);
mIsLoading = false;
}
}
#Override
public int getItemCount() {
return mCurrentLimit <= list.size() ? mCurrentLimit : list.size();
}
public void setData(List<MyModel> dataList) {
this.list = dataList;
notifyDataSetChanged();
}
ItemClickListner itemClickListner;
public void setListener(ItemClickListner listener) {
itemClickListner = listener;
}
ProgressLoadListener progressLoadListener;
public void setProgressLoadListener(ProgressLoadListener listener) {
progressLoadListener = listener;
}
}
code for xml file
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:visibility="gone"
android:layout_height="match_parent"
android:layout_above="#+id/loader_progress_bar_layout"
android:background="#f5f5f5"
android:layout_gravity="center" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:id="#+id/loader_progress_bar_layout"
android:visibility="gone"
android:background="#fff"
>
<ProgressBar
android:id="#+id/progress_bar_loader"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_gravity="center" />
</RelativeLayout>
initialize Recyclerview with adapter
public class Main2Activity extends AppCompatActivity {
RecyclerView recyclerView;
RelativeLayout layoutProgressBar;
CamerasAdapter adapter;
List<Item> itemList;
LinearLayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
layoutProgressBar = findViewById(R.id.loader_progress_bar_layout);
recyclerView = findViewById(R.id.recycler_view);
adapter = new CamerasAdapter(getActivity(), loaderLayout);
mLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setAdapter(adapter);
adapter.setProgressLoadListener(new ProgressLoadListener() {
#Override
public void loadProgressBar() {
layoutProgressBar.setVisibility(View.VISIBLE);
}
});
adapter.setData(setAdaperData());
}
public List<MyModel> setAdaperData(){
List<MyModel> modelList = new ArrayList<>();
/*addItemsto list*/
return modelList;
}
}
Please i need help on this one. Have been working on it for days but cant figure it out.
I have a recycleView to display a list of names but its displaying empty list, but i can print the list in console.
here,s the code fetching the list
public List<BackendlessUser> userList = new ArrayList<BackendlessUser>();
BackendlessDataQuery query = new BackendlessDataQuery();
Backendless.Data.of( BackendlessUser.class ).find( query, new AsyncCallback<BackendlessCollection<BackendlessUser>>()
{
#Override
public void handleResponse( BackendlessCollection<BackendlessUser> response )
{
userList = response.getCurrentPage();
for( BackendlessUser user : userList ){
Log.d( "USERS : ", user.getEmail() );
}
Log.d("USER LIST", String.valueOf( userList.size() ));
}
#Override
public void handleFault(BackendlessFault backendlessFault) {
}
});
and the recyclerView adapter that is supposed to adapt the list to the view ..
private void setupRecyclerView(#NonNull RecyclerView recyclerView) {
recyclerView.setAdapter(new SimpleItemRecyclerViewAdapter(userList));
}
public class SimpleItemRecyclerViewAdapter
extends RecyclerView.Adapter<SimpleItemRecyclerViewAdapter.ViewHolder> {
private final List<BackendlessUser> mValues;
public SimpleItemRecyclerViewAdapter(List<BackendlessUser> items) {
mValues = items;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_list_content, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.mItem = mValues.get(position);
holder.mIdView.setText(mValues.get(position).getProperty("idno").toString());
holder.mContentView.setText(mValues.get(position).getProperty("fname").toString());
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putString(ItemDetailFragment.ARG_ITEM_ID, holder.mItem.getProperty("idno").toString());
ItemDetailFragment fragment = new ItemDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.item_detail_container, fragment)
.commit();
} else {
Context context = v.getContext();
Intent intent = new Intent(context, ItemDetailActivity.class);
intent.putExtra(ItemDetailFragment.ARG_ITEM_ID, holder.mItem.getProperty("idno").toString());
context.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return mValues.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mIdView;
public final TextView mContentView;
public BackendlessUser mItem;
public ViewHolder(View view) {
super(view);
mView = view;
mIdView = (TextView) view.findViewById(R.id.id);
mContentView = (TextView) view.findViewById(R.id.content);
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}
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'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.