Android Issue with RecyclerView: view get override - android

I am using RecyclerView for first tab and ListView for other tabs.
when I scroll in RecyclerView it of same for ListView. but when I swipe from first tab to other tab and return to first tab I get the result as below
For the first time:
After travelling from other tab:
public class QuestionListAdapter extends RecyclerView.Adapter<QuestionListAdapter.CustomViewHolder> {
private List<QuestionListModel> feedItemList;
private Context mContext;
private String UserIDFromDatabase = "";
private ConnectionDetector connectionDetector;
public QuestionListAdapter(Context context, List<QuestionListModel> feedItemList, String UserIDFromDatabase) {
this.feedItemList = feedItemList;
this.mContext = context;
this.UserIDFromDatabase = UserIDFromDatabase;
connectionDetector = new ConnectionDetector(mContext);
}
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.buds_profile_list_child, null);
CustomViewHolder viewHolder = new CustomViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(CustomViewHolder customViewHolder, int i) {
QuestionListModel feedItem = feedItemList.get(i);
// Setting text view title
customViewHolder.textView.setText(Html.fromHtml(feedItem.getQuestion()));
}
#Override
public int getItemCount() {
return (null != feedItemList ? feedItemList.size() : 0);
}
public class CustomViewHolder extends RecyclerView.ViewHolder {
protected TextView textView;
public CustomViewHolder(View view) {
super(view);
this.textView = (TextView) view.findViewById(R.id.textView_ask_question_bplc);
}
}
}
Fragment:
public class QuestionFragment extends Fragment {
ConnectionDetector connectionDetector;
View rootView;
String UserIDFromDatabase = "";
int sendToServerOffsetPub = 0;
Boolean callSuccessful = false;
private RecyclerView mRecyclerView;
private QuestionListAdapter adapter;
private com.oi.example.swipyrefreshlayout.SwipyRefreshLayout swipeRefreshLayout;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.public__question_fragment, container, false);
initializeScreen();
return rootView;
}
private void initializeScreen() {
Utility.sp = getActivity().getSharedPreferences("User_Details", Context.MODE_PRIVATE);
UserIDFromDatabase = Utility.sp.getString("UserID", "");
// Initialize recycler view
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_public__question_paqf);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
adapter = new QuestionListAdapter(getActivity(), Utility.arrayListQuestionListModels, UserIDFromDatabase);
mRecyclerView.setAdapter(adapter);
connectionDetector = new ConnectionDetector(getActivity());
swipeRefreshLayout = (com.oi.example.swipyrefreshlayout.SwipyRefreshLayout) rootView.findViewById(R.id.swipe_refresh_public_listview_paqf);
swipeRefreshLayout.setColorSchemeResources(R.color.color_dark_grey);
swipeRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
#Override
public void onRefresh(SwipyRefreshLayoutDirection direction) {
if (direction == SwipyRefreshLayoutDirection.BOTTOM) {
if (connectionDetector.isConnectingToInternet()) { // if 1
if ((Utility.publicCount > 0) && (Utility.arrayListQuestionListModels.size() > 0)) {
sendToServerOffsetPub++;
try {
callSuccessful = new getQuestionListOnProfile(getActivity(), Utility.referenceForProfileID, sendToServerOffsetPub, "PUBLIC").execute().get();
} catch (InterruptedException | ExecutionException e) {
callSuccessful = false;
}
if (!callSuccessful) {
adapter.notifyDataSetChanged();
}
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
} else {
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
} else {
Toast.makeText(getActivity(), Constants.INTERNET_CONNECTION, Toast.LENGTH_SHORT).show();
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
}
}
});
mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(getActivity(), new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Utility.ID = (Utility.arrayListQuestionListModels.get(position).getId());
RateFeedController rateFeedController = new RateFeedController(getActivity());
ArrayList<HashMap<String, String>> DetailsArraylist = new ArrayList<HashMap<String, String>>();
DetailsArraylist = rateFeedController.getDetailsForSays(Utility.ID);
if (DetailsArraylist.size() > 0) {
String creatorID = DetailsArraylist.get(0).get("userID");
if (creatorID.equalsIgnoreCase(BudsProfileActivity.UserIDFromDatabase)) {
Utility.attachedListPPFM = 2;
}
Intent intentSays = new Intent(getActivity(), SaysScreenActivity.class);
intentSays.putExtra("ProfileBACKFLAG", "BudsProfileActivity");
startActivity(intentSays);
} else {
if (connectionDetector.isConnectingToInternet()) {// If 2
new GetFromServer(getActivity(), Integer.toString(Utility.ID), BudsProfileActivity.UserIDFromDatabase).execute();
} else {
Toast.makeText(getActivity(), Constants.INTERNET_CONNECTION, Toast.LENGTH_SHORT).show();
}// End of If 2
}
}
}));
}
}

Don't know what was wrong, but I just remove the parent Layout SwipyRefreshLayout and the My issue get solved..

Related

Animation with firestore recycler view not working

I have found this library and I want to implement it in my app:
cardslider-android--Github
In my case I have events and I want to query their name, time, description and picture and, each time I select a card, they will change dynamically in the same fragment.
This is the event adapter:
public class EventsAdapter extends FirestoreRecyclerAdapter < EventsModel, EventsAdapter.EventsViewHolder > {
public EventsAdapter(FirestoreRecyclerOptions < EventsModel > options) {
super(options);
}
DocumentSnapshot documentSnapshot;
#Override
protected void onBindViewHolder(#NonNull EventsViewHolder holder, int position, #NonNull EventsModel eventsModel) {
holder.nameSwitcher.setText(eventsModel.getEvent_name());
holder.timeSwitcher.setText(eventsModel.getEvent_date());
holder.descriptionsSwitcher.setText(eventsModel.getEvent_desc());
GlideApp.with(holder.eventpic.getContext())
.load(eventsModel.getEvent_pic())
.into(holder.eventpic);
String documentID = getSnapshots().getSnapshot(position).getId();
eventsModel.setDocid(documentID);
}
#NonNull
#Override
public EventsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_past_event, parent, false);
return new EventsViewHolder(view);
}
public class EventsViewHolder extends RecyclerView.ViewHolder {
private TextView eventname;
private Button morebtn;
private ImageView eventpic;
private TextSwitcher nameSwitcher;
private TextSwitcher timeSwitcher;
private TextSwitcher descriptionsSwitcher;
public EventsViewHolder(#NonNull View itemView) {
super(itemView);
nameSwitcher = itemView.findViewById(R.id.ts_name);
timeSwitcher = itemView.findViewById(R.id.ts_time);
descriptionsSwitcher = itemView.findViewById(R.id.ts_description);
}
}
}
This is the Fragment:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View root_past_event_view = inflater.inflate(R.layout.fragment_past_event, container, false);
mFirestoreList = (RecyclerView) root_past_event_view.findViewById(R.id.xrecyclerview_events);
firebaseFirestore = FirebaseFirestore.getInstance();
Query query = firebaseFirestore.collection("events");
FirestoreRecyclerOptions < EventsModel > options = new FirestoreRecyclerOptions
.Builder < EventsModel > ()
.setQuery(query, EventsModel.class)
.build();
adapter = new EventsAdapter(options);
mFirestoreList.setHasFixedSize(true);
mFirestoreList.setLayoutManager(new CardSliderLayoutManager(getContext()));
mFirestoreList.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
onActiveCardChange();
}
}
});
mFirestoreList.setLayoutManager(new CardSliderLayoutManager(getContext()));
new CardSnapHelper().attachToRecyclerView(mFirestoreList);
mFirestoreList.setAdapter(adapter);
nameSwitcher = (TextSwitcher) root_past_event_view.findViewById(R.id.ts_name);
nameSwitcher.setFactory(new TextViewFactory(R.style.nameTextView, false));
timeSwitcher = (TextSwitcher) root_past_event_view.findViewById(R.id.ts_time);
timeSwitcher.setFactory(new TextViewFactory(R.style.timeTextView, false));
descriptionsSwitcher = (TextSwitcher) root_past_event_view.findViewById(R.id.ts_description);
descriptionsSwitcher.setInAnimation(getContext(), android.R.anim.fade_in);
descriptionsSwitcher.setOutAnimation(getContext(), android.R.anim.fade_out);
descriptionsSwitcher.setFactory(new TextViewFactory(R.style.DescriptionTextView, false));
return root_past_event_view;
}
private void initRecyclerView() {
}
private void onActiveCardChange() {
final int pos = layoutManger.getActiveCardPosition();
if (pos == RecyclerView.NO_POSITION || pos == currentPosition) {
return;
}
onActiveCardChange(pos);
}
private void onActiveCardChange(int pos) {
int animH[] = new int[] {
R.anim.slide_in_right, R.anim.slide_out_left
};
int animV[] = new int[] {
R.anim.slide_in_top, R.anim.slide_out_bottom
};
final boolean left2right = pos < currentPosition;
if (left2right) {
animH[0] = R.anim.slide_in_left;
animH[1] = R.anim.slide_out_right;
animV[0] = R.anim.slide_in_bottom;
animV[1] = R.anim.slide_out_top;
}
//setCountryText(countries[pos % countries.length], left2right);
nameSwitcher.setInAnimation(getContext(), animV[0]);
nameSwitcher.setOutAnimation(getContext(), animV[1]);
timeSwitcher.setInAnimation(getContext(), animV[0]);
timeSwitcher.setOutAnimation(getContext(), animV[1]);
currentPosition = pos;
}
private class TextViewFactory implements ViewSwitcher.ViewFactory {
#StyleRes
final int styleId;
final boolean center;
TextViewFactory(#StyleRes int styleId, boolean center) {
this.styleId = styleId;
this.center = center;
}
#SuppressWarnings("deprecation")
#Override
public View makeView() {
final TextView textView = new TextView(getContext());
if (center) {
textView.setGravity(Gravity.CENTER);
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
textView.setTextAppearance(getContext(), styleId);
} else {
textView.setTextAppearance(styleId);
}
return textView;
}
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
}
I changed the LayoutInflater to include the whole fragment and I do not get a single card but the following error:
Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference

how programmatically select item by position in adapter (android)

I want to select an item by position in adapter programmatically
in my project i have an activity that get categories , now i want to select an item form this adapter automatic.
final result is :
after Home activity have been lunched when user clicks on the button and lunch the second activity that getting my categories from web service in the adapter and then select an item by position at adapter and run third activity that shown the content of the item.
Here is my codes
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class FragmentCategory extends Fragment {
private View root_view, parent_view;
private RecyclerView recyclerView;
private SwipeRefreshLayout swipe_refresh;
private AdapterCategory mAdapter;
private Call<CallbackCategories> callbackCall = null;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
root_view = inflater.inflate(R.layout.fragment_category, null);
parent_view = getActivity().findViewById(R.id.main_content);
swipe_refresh = (SwipeRefreshLayout) root_view.findViewById(R.id.swipe_refresh_layout_category);
recyclerView = (RecyclerView) root_view.findViewById(R.id.recyclerViewCategory);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setHasFixedSize(true);
//set data and list adapter
mAdapter = new AdapterCategory(getActivity(), new ArrayList<Category>());
recyclerView.setAdapter(mAdapter);
// on item list clicked
mAdapter.setOnItemClickListener(new AdapterCategory.OnItemClickListener() {
#Override
public void onItemClick(View v, Category obj, int position) {
ActivityCategoryDetails.navigate((ActivityMain) getActivity(), v.findViewById(R.id.lyt_parent), obj);
}
});
// on swipe list
swipe_refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mAdapter.resetListData();
requestAction();
}
});
requestAction();
return root_view;
}
private void displayApiResult(final List<Category> categories) {
mAdapter.setListData(categories);
swipeProgress(false);
if (categories.size() == 0) {
showNoItemView(true);
}
}
private void requestCategoriesApi() {
API api = RestAdapter.createAPI();
callbackCall = api.getAllCategories();
callbackCall.enqueue(new Callback<CallbackCategories>() {
#Override
public void onResponse(Call<CallbackCategories> call, Response<CallbackCategories> response) {
CallbackCategories resp = response.body();
if (resp != null && resp.status.equals("ok")) {
displayApiResult(resp.categories);
} else {
onFailRequest();
}
}
#Override
public void onFailure(Call<CallbackCategories> call, Throwable t) {
if (!call.isCanceled()) onFailRequest();
}
});
}
private void onFailRequest() {
swipeProgress(false);
if (NetworkCheck.isConnect(getActivity())) {
showFailedView(true, getString(R.string.failed_text));
} else {
showFailedView(true, getString(R.string.no_internet_text));
}
}
private void requestAction() {
showFailedView(false, "");
swipeProgress(true);
showNoItemView(false);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
requestCategoriesApi();
}
}, Constant.DELAY_TIME);
}
#Override
public void onDestroy() {
super.onDestroy();
swipeProgress(false);
if(callbackCall != null && callbackCall.isExecuted()){
callbackCall.cancel();
}
}
private void showFailedView(boolean flag, String message) {
View lyt_failed = (View) root_view.findViewById(R.id.lyt_failed_category);
((TextView) root_view.findViewById(R.id.failed_message)).setText(message);
if (flag) {
recyclerView.setVisibility(View.GONE);
lyt_failed.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
lyt_failed.setVisibility(View.GONE);
}
((Button) root_view.findViewById(R.id.failed_retry)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
requestAction();
}
});
}
private void showNoItemView(boolean show) {
View lyt_no_item = (View) root_view.findViewById(R.id.lyt_no_item_category);
((TextView) root_view.findViewById(R.id.no_item_message)).setText(R.string.no_category);
if (show) {
recyclerView.setVisibility(View.GONE);
lyt_no_item.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
lyt_no_item.setVisibility(View.GONE);
}
}
private void swipeProgress(final boolean show) {
if (!show) {
swipe_refresh.setRefreshing(show);
return;
}
swipe_refresh.post(new Runnable() {
#Override
public void run() {
swipe_refresh.setRefreshing(show);
}
});
}
}
`
Update : AdapterCategory Codes
public class AdapterCategory extends RecyclerView.Adapter<AdapterCategory.ViewHolder> {
private List<Category> items = new ArrayList<>();
private Context ctx;
private OnItemClickListener mOnItemClickListener;
public interface OnItemClickListener {
void onItemClick(View view, Category obj, int position);
}
public void setOnItemClickListener(final OnItemClickListener mItemClickListener) {
this.mOnItemClickListener = mItemClickListener;
}
// Provide a suitable constructor (depends on the kind of dataset)
public AdapterCategory(Context context, List<Category> items) {
this.items = items;
ctx = context;
}
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView name;
public TextView post_count;
public LinearLayout lyt_parent;
public ViewHolder(View v) {
super(v);
name = (TextView) v.findViewById(R.id.name);
post_count = (TextView) v.findViewById(R.id.post_count);
lyt_parent = (LinearLayout) v.findViewById(R.id.lyt_parent);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_category, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
final Category c = items.get(position);
holder.name.setText(Html.fromHtml(c.title));
holder.post_count.setText(c.post_count+"");
holder.lyt_parent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(view, c, position);
}
}
});
}
public void setListData(List<Category> items){
this.items = items;
notifyDataSetChanged();
}
public void resetListData() {
this.items = new ArrayList<>();
notifyDataSetChanged();
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return items.size();
}
}

RecyclerView not refreshing onClick

The RecyclerView is getting refreshed fine when I call for it in the main activity, but when I use a FloatingActionButton it no longer works, and it is not giving any errors as to why.
The onCreate method from the MainActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Initially get the events
dh.getEvents();
//Initially setting the list fragment
EventListFragment eventListFragment = new EventListFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame, eventListFragment, "list_fragment");
fragmentTransaction.commit();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dh.getEvents();
}
});
}
This is the getEvents() method from the DataHandaling class
public void getEvents() {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(enviroClass.url() + "/api/events/" + 7)
.build();
client.newCall(request)
.enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
try {
JSONObject eventObject = new JSONObject(response.body().string());
JSONArray eventJsonArray = eventObject.getJSONArray("events");
for (int i = 0; i<eventJsonArray.length(); i++) {
eventObject = eventJsonArray.getJSONObject(i);
eventObject = eventObject.getJSONObject("event");
eventArray.add(new Event(eventObject.getString("name"), eventObject.getString("address"), eventObject.getString("image"), "100", eventObject.getString("description"), eventObject.getString("start_date"), eventObject.getString("end_date"), eventObject.getInt("id")));
}
EventListAdapter adapter = new EventListAdapter(eventArray, null);
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
UPDATE
This is the RecyclerAdapter that is being used
public class EventListAdapter extends RecyclerView.Adapter<EventListAdapter.ViewHolder> {
DataHandaling dh = new DataHandaling();
private static ArrayList<Event> mValues;
private OnListFragmentInteractionListener mListener = null;
public EventListAdapter(ArrayList<Event> items, OnListFragmentInteractionListener listener) {
if (items != null) {
mValues = items;
}
if (listener != null ) {
mListener = listener;
}
}
public void swap(ArrayList<Event> eventArray) {
mValues.clear();
mValues.addAll(eventArray);
notifyDataSetChanged();
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.fragment_item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.mItem = mValues.get(position);
holder.mIdView.setText(mValues.get(position).getStarTime());
holder.mContentView.setText(mValues.get(position).getName());
Picasso.with(getApplicationContext()).load(mValues.get(position).getImage()).into(holder.mImageView);
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (null != mListener) {
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
mListener.onListFragmentInteraction(position);
}
}
});
}
#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 final ImageView mImageView;
public Event mItem;
public ViewHolder(View view) {
super(view);
mView = view;
mIdView = (TextView) view.findViewById(R.id.id);
mContentView = (TextView) view.findViewById(R.id.content);
mImageView = (ImageView) view.findViewById(R.id.eventImage);
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}
This is the Fragment onCreateView, where the adapter is set
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_item_list, container, false);
// Set the adapter
if (view instanceof RecyclerView) {
Context context = view.getContext();
RecyclerView recyclerView = (RecyclerView) view;
if (mColumnCount <= 1) {
recyclerView.setLayoutManager(new LinearLayoutManager(context));
} else {
recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
}
recyclerView.setAdapter(new EventListAdapter(dh.getEventArray(), mListener));
}
return view;
}
If you create a new adapter, you need to set it in the RecyclerView
EventListAdapter adapter = new EventListAdapter(eventArray, null);
myRecyclerView.setAdapter(adapter)
The class DataHandling should have access to RecyclerView
Or you could use the previous created adapter :
In fragment, change :
recyclerView.setAdapter(new EventListAdapter(dh.getEventArray(), mListener));
by
mAdapter = new EventListAdapter(dh.getEventArray(), mListener)
recyclerView.setAdapter(mAdapter);
In getEvents() :
mAdapter.swap(eventArray);
It means that DataHandling class should have access to mAdapter, you could pass it in contructor, or you should move getEvents() to Fragment and delete DataHandling class

Duplicate items in the recyclerView

I am new here, I have an activity that contains ViewPager with two Fragments. Each Fragment has a RecyclerView. on selecting a tab through OnTabSelection items in the RecyclerView gets repeated. I can't understand what is causing this problem.
I am using DataHandler to save the data because I have to use this data in other activities as well.
class DataHandler {
private ArrayList<MenuHolder> listOfItemsFromJson;
private static DataHandler mInstance = null;
static public DataHandler getInstance() {
if (null == mInstance) {
mInstance = new DataHandler();
}
return mInstance;
}
public DataHandler() {
listOfItemsFromJson = new ArrayList<>();
}
public ArrayList<MenuHolder> getListOfItemsFromJson() {
return listOfItemsFromJson;
}
public void clearList() {
listOfItemsFromJson.clear();
}
public void addData(MenuHolder holder) {
listOfItemsFromJson.add(holder);
}
public MenuHolder getData(int position) {
return listOfItemsFromJson.get(position);
}
public void removeData(int position) {
listOfItemsFromJson.remove(getData(position));
}
public int size() {
return listOfItemsFromJson.size();
}
}
Here is my Fragment
class ComboRecycler extends Fragment {
private ArrayList<Integer> index = new ArrayList<>();
private LinearLayout mViewCartLayout;
private RelativeLayout relativeLayout;
private RecyclerView recyclerView;
RecyclerView.Adapter recyclerAdapter;
RecyclerView.LayoutManager recylerViewLayoutManager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.recycler_combo, container, false);
relativeLayout = (RelativeLayout) view.findViewById(R.id.relativelayout1);
recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
recylerViewLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(recylerViewLayoutManager);
new FetchTask().execute();
return view;
}
public class FetchTask extends AsyncTask<Void, Void, JSONArray> {
#Override
protected JSONArray doInBackground(Void... params) {
JSONArray jsonArray;
........
}
#Override
protected void onPostExecute(JSONArray result) {
if (result != null) {
try {
for (int i = 0; i < DataHandler.getInstance().size(); i++) {
if (DataHandler.getInstance().getData(i).isCombo()) {
DataHandler.getInstance().removeData(i);
}
}
for (int i = 0; i < result.length(); i++) {
JSONObject mJsonObject = result
.getJSONObject(i);
MenuHolder mDataHolder = new MenuHolder();
......
mDataHolder.setCombo(true);
mDataHolder.setItemCount("0");
DataHandler.getInstance().addData(mDataHolder);
}
setAdapter();
} catch (Exception e) {
}
}
}
}
private void setAdapter() {
index.clear();
for (int i = 0; i < DataHandler.getInstance().size(); i++) {
if (DataHandler.getInstance().getListOfItemsFromJson().get(i).isCombo()) {
index.add(i);
}
}
recyclerComboAdapter = new RecyclerComboAdapter(getActivity(), index);
recyclerView.setAdapter(recyclerComboAdapter);
}
}
Here is my RecyclerAdapter
class RecyclerComboAdapter extends RecyclerView.Adapter<RecyclerComboAdapter.ViewHolder> {
Context context;
View view1;
ViewHolder viewHolder1;
ArrayList<Integer> index;
LinearLayout mViewCart;
Recycler recycler;
private AQuery mQuery;
public RecyclerComboAdapter(Context context1, ArrayList<Integer> index) {
this.index = index;
context = context1;
mQuery = new AQuery(context1);
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
view1 = LayoutInflater.from(context).inflate(R.layout.combo_meals_adapter, parent, false);
viewHolder1 = new ViewHolder(view1);
return viewHolder1;
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
final int pos = position;
MenuHolder menuHolder =DataHandler.getInstance().getData(index.get(position));
holder.itemName.setText(menuHolder.getItemname());
holder.itemPrice.setText(menuHolder.getItemprice());
mQuery.id(holder.imageView).image(menuHolder.getItemPicture());
holder.counter.setText(menuHolder.getItemCount());
}
#Override
public int getItemCount() {
return index.size();
}
static class ViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
TextView add, minus, plus, counter, itemName, itemPrice;
ViewHolder(View v) {
super(v);
itemName = (TextView) v.findViewById(R.id.itemnametxt);
imageView = (ImageView) v.findViewById(R.id.image);
itemPrice = (TextView) v.findViewById(R.id.price);
minus = (TextView) v.findViewById(R.id.minus);
plus = (TextView) v.findViewById(R.id.plus);
counter = (TextView) v.findViewById(R.id.count);
add = (TextView) v.findViewById(R.id.addtxt);
}
}
}
After swiping the list multiple times I am seeing repeated list items. Please help me with this problem. Thanks in advance.

Expandable Recycler View only showing one item in parent

My recycler view has a parent and a child. My parent is only displaying one item with then all the topics in that one item. I can post my code below I'm not sure what it is I need to do to correct this as this is my first time using expandable views. I've posted the whole class below. Not sure what was needed for you to see.
public class TopicFragment extends Fragment {
private View mRootView;
private CategoryResponse mData;
private CategoryFeedDataFactory mDataFactory;
private List<String> mCategories;
//Expandable Recycler View
private List<TopicItem> mTopics;
private TopicResponse mTopic;
private TopicFeedDataFactory mTopicDataFactory;
private CategoryItem mCategoryItem;
//RecyclerView
private RecyclerView mRecyclerView;
private LinearLayoutManager mLayoutManager;
private TopicExpandableAdapter mExpandableAdapter;
public TopicFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mRootView = inflater.inflate(R.layout.fragment_topic, container, false);
initUI();
return mRootView;
}
private void initUI() {
mRecyclerView = (RecyclerView) mRootView.findViewById(R.id.categoryView);
mLayoutManager = new LinearLayoutManager(getActivity().getApplication().getApplicationContext());
loadData();
}
private void loadData() {
mDataFactory = new CategoryFeedDataFactory(getActivity().getApplicationContext());
mTopicDataFactory = new TopicFeedDataFactory(getActivity().getApplicationContext());
mDataFactory.getCategoryFeed(new CategoryFeedDataFactory.CategoryFeedDataFactoryCallback() {
#Override
public void onCategoryDataReceived(CategoryResponse response) {
mData = response;
}
#Override
public void onCategoryDataFailed(Exception exception) {
}
});
mTopicDataFactory.getAllTopics(new TopicFeedDataFactory.TopicFeedDataFactoryCallback() {
#Override
public void onTopicDataReceived(TopicResponse response) {
mTopic = response;
populateUIWithData();
}
#Override
public void onTopicDataFailed(Exception exception) {
}
});
}
private void populateUIWithData() {
mCategories = new ArrayList<>();
mTopics = new ArrayList<>();
for (int i = 0; i <= mData.getItems().size(); i++) {
if (mData != null) {
if (mData.getItem(i) != null) {
if (mData.getItem(i).getCategoryItem() != null &&
mData.getItem(i).getCategoryItem().getName() != null) {
mCategories.add(mData.getItem(i).getCategoryItem().getName());
}
}
}
for (int j = 0; j <= mTopic.getItems().size(); j++) {
if (mTopic != null)
if (mTopic.getItem(j) != null)
if (mTopic.getItem(j).getTopicItem() != null)
if (mTopic.getItem(j).getTopicItem().getCategoryID() != null) {
if (mData.getItem(i) != null && mData.getItem(i).getCategoryItem() != null)
if (mData.getItem(i).getCategoryItem().getId() != null)
if (mTopic.getItem(j).getTopicItem().getCategoryID().equals
(mData.getItem(i).getCategoryItem().getId())) {
mTopics.add(mTopic.getItem(j).getTopicItem());
mCategoryItem =
new CategoryItem(mData.getItem(i).getCategoryItem().getName(),
mTopics);
}
}
}
}
final List<CategoryItem> categoryItems = Collections.singletonList(mCategoryItem);
mExpandableAdapter = new TopicExpandableAdapter(getActivity(), categoryItems);
mExpandableAdapter.setExpandCollapseListener(new ExpandableRecyclerAdapter.ExpandCollapseListener() {
#Override
public void onListItemExpanded(int position) {
CategoryItem expandedCategoryItem = categoryItems.get(position);
String toastMsg = getResources().getString(R.string.expanded, expandedCategoryItem);
Toast.makeText(getActivity().getApplicationContext(),
toastMsg,
Toast.LENGTH_SHORT)
.show();
}
#Override
public void onListItemCollapsed(int position) {
CategoryItem collapsedCategoryItem = categoryItems.get(position);
String toastMsg = getResources().getString(R.string.collapsed, collapsedCategoryItem.getName());
Toast.makeText(getActivity().getApplicationContext(),
toastMsg,
Toast.LENGTH_SHORT)
.show();
}
});
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mRecyclerView.setAdapter(mExpandableAdapter);
}
}
Am I just missing something really simple? Because this feels really complicated lol
Thanks in advance!
I'm not sure that your code is good enough.
See https://github.com/anandbose/ExpandableListViewDemo is pretty clear
You can easily implement it with the library SectionedRecyclerViewAdapter. There is a full working example here.
Basically you create a section class:
class MySection extends StatelessSection {
String title;
List<TopicItem> list;
boolean expanded = true; // true if you want it to be displayed expanded initially
public MySection(String title, List<TopicItem> list) {
// call constructor with layout resources for this Section header, footer and items
super(R.layout.section_header, R.layout.section_item);
this.title = title;
this.list = list;
}
#Override
public int getContentItemsTotal() {
return expanded? list.size() : 0;
}
#Override
public RecyclerView.ViewHolder getItemViewHolder(View view) {
// return a custom instance of ViewHolder for the items of this section
return new MyItemViewHolder(view);
}
#Override
public void onBindItemViewHolder(RecyclerView.ViewHolder holder, int position) {
MyItemViewHolder itemHolder = (MyItemViewHolder) holder;
// bind your view here
itemHolder.tvItem.setText(list.get(position).getTopicName());
}
#Override
public RecyclerView.ViewHolder getHeaderViewHolder(View view) {
return new SimpleHeaderViewHolder(view);
}
#Override
public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder) {
MyHeaderViewHolder headerHolder = (MyHeaderViewHolder) holder;
// bind your header view here
headerHolder.tvItem.setText(title);
// handles the click on the header to toggle the expanded variable
headerHolder.rootView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
expanded = !expanded;
headerHolder.imgArrow.setImageResource(
expanded ? R.drawable.ic_keyboard_arrow_up_black_18dp : R.drawable.ic_keyboard_arrow_down_black_18dp
);
sectionAdapter.notifyDataSetChanged();
}
});
}
}
Then you set up the RecyclerView with your sections:
// Create an instance of SectionedRecyclerViewAdapter
SectionedRecyclerViewAdapter sectionAdapter = new SectionedRecyclerViewAdapter();
// Create your sections with the list of data for each category
MySection cat1Section = new MySection(mCategories.get(0), cat1TopicItemList);
MySection cat2Section = new MySection(mCategories.get(1), cat2TopicItemList);
// Add your Sections to the adapter
sectionAdapter.addSection(cat1Section);
sectionAdapter.addSection(cat2Section);
// Set up your RecyclerView with the SectionedRecyclerViewAdapter
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(sectionAdapter);

Categories

Resources