CustomView inside recycler view not showing keyboard when focus - android-recyclerview

I have created one custom view that extends constraintsalyout. Inside that view, I added EditText and Textview. When I try to add this custom view inside recycler view, Its not showing keyboard when I touch on that edittext.
Its perfectly working when added outside of recycler view
public class SVEditText extends ConstraintLayout {
private Context context;
private EditText editText;
private TextView textView;
public SVEditText(final Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.sv_edittext, this);
editText = view.findViewById(R.id.editText);
textView = view.findViewById(R.id.textView);
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.SVEditText);
editText.setText(typedArray.getString(R.styleable.SVEditText_text));
editText.setHint(typedArray.getString(R.styleable.SVEditText_hint));
editText.setLines(typedArray.getInteger(R.styleable.SVEditText_android_lines, 1));
editText.setInputType(typedArray.getInteger(R.styleable.SVEditText_android_inputType, 0));
textView.setText(typedArray.getString(R.styleable.SVEditText_title));
setDrawablesToEditText(typedArray);
typedArray.recycle();
}
private void setDrawablesToEditText(TypedArray typedArray){
if (typedArray.getInteger(R.styleable.SVEditText_android_lines, 1) != 1){
Drawable innerDrawableLeft = typedArray.getDrawable(R.styleable.SVEditText_iconLeft);
Drawable innerDrawableRight = typedArray.getDrawable(R.styleable.SVEditText_iconRight);
GravityCompoundDrawable iconLeft = null, iconRight = null;
if (innerDrawableLeft != null) {
iconLeft = new GravityCompoundDrawable(innerDrawableLeft);
innerDrawableLeft.setBounds(0, 30, innerDrawableLeft.getIntrinsicWidth(), innerDrawableLeft.getIntrinsicHeight()+30);
iconLeft.setBounds(0, 0, innerDrawableLeft.getIntrinsicWidth(), innerDrawableLeft.getIntrinsicHeight());
iconLeft.setColorFilter(new PorterDuffColorFilter(ContextCompat.getColor(getContext(), R.color.colorPrimary), PorterDuff.Mode.SRC_IN));
}
if (innerDrawableRight != null) {
iconRight = new GravityCompoundDrawable(innerDrawableRight);
innerDrawableRight.setBounds(0, 30, innerDrawableRight.getIntrinsicWidth(), innerDrawableRight.getIntrinsicHeight()+30);
iconRight.setBounds(0, 0, innerDrawableRight.getIntrinsicWidth(), innerDrawableRight.getIntrinsicHeight());
iconRight.setColorFilter(new PorterDuffColorFilter(ContextCompat.getColor(getContext(), R.color.colorPrimary), PorterDuff.Mode.SRC_IN));
}
editText.setCompoundDrawablesWithIntrinsicBounds(iconLeft,
null, iconRight, null);
editText.setBackgroundResource(R.drawable.bg_edit_multiline);
return;
}
editText.setCompoundDrawablesWithIntrinsicBounds(typedArray.getDrawable(R.styleable.SVEditText_iconLeft),
null, typedArray.getDrawable(R.styleable.SVEditText_iconRight), null);
}
public void setText(String value){
editText.setText(value);
}
public void setHint(String hint){
editText.setHint(hint);
}
public void setTitle(String title){
textView.setText(title);
}
public void setCompoundDrawablesWithIntrinsicBounds( #DrawableRes int left, #DrawableRes int top, #DrawableRes int right, #DrawableRes int bottom){
editText.setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom);
}
public void setText(Spannable spannable) {
editText.setText(spannable);
}
}

Finally I found the mistake I made.
I missed this line in xml.
android:inputType="phone"
So it is taken as 0 default from my custom view code.
I updated that default value as 1, now it is working without adding inputtype in xml.

Related

Trouble getting recyclerview to load elements

I am making a networking app's chat section from this tutorial: https://blog.sendbird.com/android-chat-tutorial-building-a-messaging-ui.
I have everything hooked up so that I know that the messages are coming in from the database. It seems to be an issue with how the adapter or recyclerview are set up. I can't see any messages on my activity even though I can see them if I poke in my async/background worker.
This is the adapter class with inner view holders from the tutorial, adapted to my needs:
public class MessageListAdapter extends RecyclerView.Adapter {
private static final int VIEW_TYPE_MESSAGE_SENT = 1;
private static final int VIEW_TYPE_MESSAGE_RECEIVED = 2;
private Activity mContext;
private ArrayList<Message> mMessageList;
public MessageListAdapter(Activity context, ArrayList<Message> messageList) {
mContext = context;
mMessageList = messageList;
}
#Override
public int getItemCount() {
return mMessageList.size();
}
// Determines the appropriate ViewType according to the sender of the message.
#Override
public int getItemViewType(int position) {
Message message = (Message) mMessageList.get(position);
if (message.isOther() == "2") {
// If the current user is the sender of the message
return VIEW_TYPE_MESSAGE_SENT;
} else {
// If some other user sent the message
return VIEW_TYPE_MESSAGE_RECEIVED;
}
}
// Inflates the appropriate layout according to the ViewType.
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
if (viewType == VIEW_TYPE_MESSAGE_SENT) {
view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_message_sent, parent, false);
return new SentMessageHolder(view);
} else if (viewType == VIEW_TYPE_MESSAGE_RECEIVED) {
view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_message_received, parent, false);
return new ReceivedMessageHolder(view);
}
return null;
}
// Passes the message object to a ViewHolder so that the contents can be bound to UI.
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
Message message = mMessageList.get(position);
switch (holder.getItemViewType()) {
case VIEW_TYPE_MESSAGE_SENT:
((SentMessageHolder) holder).bind(message);
break;
case VIEW_TYPE_MESSAGE_RECEIVED:
((ReceivedMessageHolder) holder).bind(message);
}
}
private class SentMessageHolder extends RecyclerView.ViewHolder {
TextView messageText, timeText;
SentMessageHolder(View itemView) {
super(itemView);
messageText = (TextView) itemView.findViewById(R.id.text_message_body);
timeText = (TextView) itemView.findViewById(R.id.text_message_time);
}
void bind(Message message) {
messageText.setText(message.getMessage());
// Format the stored timestamp into a readable String using method.
timeText.setText(message.getCreatedAt());
}
}
private class ReceivedMessageHolder extends RecyclerView.ViewHolder {
TextView messageText, timeText, nameText;
ImageView profileImage;
ReceivedMessageHolder(View itemView) {
super(itemView);
messageText = (TextView) itemView.findViewById(R.id.text_message_body);
timeText = (TextView) itemView.findViewById(R.id.text_message_time);
nameText = (TextView) itemView.findViewById(R.id.text_message_name);
profileImage = (ImageView) itemView.findViewById(R.id.image_message_profile);
}
void bind(Message message) {
messageText.setText(message.getMessage());
// Format the stored timestamp into a readable String using method.
timeText.setText(message.getCreatedAt());
nameText.setText(message.getSender());
Picasso.get().load(message.getProfile())
.transform(new RoundedCornersTransformation(150, 0)).into(profileImage);
// Insert the profile image from the URL into the ImageView.
// Utils.displayRoundImageFromUrl(mContext, message.getSender().getProfileUrl(), profileImage);
}
}
}
I create the adapter and pair it to the recyclerview in a background worker during postExecute()
try {
JSONArray messages = new JSONArray(s);
ArrayList<Message> messageList = new ArrayList<Message>();
for (int i = 0; i < messages.length(); i++) {
String currentMessage = (String) messages.get(i);
String[] fields = currentMessage.split(",", 0);
if (fields.length == 5) {
String isOther = fields[0];
String messageText = fields[1];
String dateTime = fields[2];
String author = fields[3];
String pictureLocation = fields[4];
Message newMessage = new Message(isOther, messageText, dateTime, author, pictureLocation);
messageList.add(newMessage);
}
}
mMessageRecycler = (RecyclerView) ha.findViewById(R.id.reyclerview_message_list);
mMessageRecycler.setLayoutManager(new LinearLayoutManager(ha.getApplicationContext()));
mMessageAdapter = new MessageListAdapter(ha, messageList);
mMessageRecycler.setAdapter(mMessageAdapter);
}
I've tried adding alert dialogs to debug within the OnCreateViewHolder, but can't get them to appear. I've tried using ha, ha.getApplicationContext() on every field. There must be something that's just staring me in the face. I've used this pattern before and it works for another section of my app.
It turns out that the tutorial's recyclerview information is just barely off, so I used the one I had in a previous part of the app:
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF" />

How to hide/show a view in the Activity by clicking a button in the Android Cardview?

I am working on a commercial app as an internship. In one of its activity, I have tab view with two fragments. In each fragment, I'm using the card view to hold the views.
The card view has one image view, two text views, and a button and in the bottom of the activity below the tab view, there is a button which has its visibility mode as "GONE".
Now What I want is, Whenever I click on the button in the card view, the button at the bottom of the activity should hide/show for respective clicks.
Cardcaptionadapter.java
public CaptionedImagesAdapterMenu.ViewHolder onCreateViewHolder(
ViewGroup parent, int viewType){
CardView cv = (CardView) LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_captioned_image_menu, parent, false);
return new ViewHolder(cv);
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position){
CardView cardView = holder.cardView;
ImageView imageView = (ImageView)cardView.findViewById(R.id.info_image);
Drawable drawable = ContextCompat.getDrawable(cardView.getContext(), imageIds[position]);
imageView.setImageDrawable(drawable);
imageView.setContentDescription(captions[position]);
TextView textView = (TextView)cardView.findViewById(R.id.info_text);
textView.setText(captions[position]);
TextView textView1 = cardView.findViewById(R.id.info_menu);
textView1.setText(desc[position]);
TextView textView2 = cardView.findViewById(R.id.info_price);
textView2.setText("₹ " + price[position]);
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null) {
listener.onClick(position);
}
}
});
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(holder.button.getText().equals("ADD")){
holder.button.setText("ADDED");
holder.button.setBackgroundColor(Color.parseColor("#00ff00"));
SharedPreferences sharedPref = context.getSharedPreferences("ADD",0);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("ADDED", 1);
editor.apply();
}
else {
holder.button.setText("ADD");
holder.button.setBackgroundColor(Color.parseColor("#ffffff"));
SharedPreferences sharedPref = context.getSharedPreferences("ADD",0);
SharedPreferences.Editor editor = sharedPref.edit();
editor.clear();
editor.apply();
}
}
});
}
MenuActivity.java
SharedPreferences preferences = getSharedPreferences("ADD",0);
int addvalue = preferences.getInt("ADDED",0);
if(addvalue==1){
orderbutton.setVisibility(View.VISIBLE);
}
else{
orderbutton.setVisibility(View.GONE);
}
orderbutton.setOnClickListener(view -> {
orderbutton.setVisibility(View.GONE);
paybutton.setVisibility(View.VISIBLE);
});
you should add MenuActivity.java code inside public void onBindViewHolder(ViewHolder holder, final int position){ } method also.

Automatically scrolling TextView inside a RecyclerView

My current problem is the following: I have a RecyclerView and each element of this RecyclerView has a TextView. I want that the TextView scrolls automatically. What if tried so far:
Customize TextView:
public class ScrollCustomTextView extends AppCompatTextView {
public ScrollCustomTextView(Context context) {
super(context);
}
public ScrollCustomTextView(Context context, AttributeSet attrs, int defStyle) {
super(context,attrs,defStyle);
}
public ScrollCustomTextView(Context context, AttributeSet attrs) {
super(context,attrs);
}
#Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
if (focused)
super.onFocusChanged(focused, direction, previouslyFocusedRect);
}
#Override
public void onWindowFocusChanged(boolean focused) {
if(focused)
super.onWindowFocusChanged(focused);
}
#Override
public boolean isFocused() {
return true;
}
}
and my .xml file looks like this:
<package.ScrollCustomTextView
android:id="#+id/main_idea_name"
android:scrollHorizontally="true"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/darkGreen"
android:textSize="27dp"
android:layout_marginTop="10dp"
android:maxLines="1"
android:textAppearance="#android:style/TextAppearance.Medium"
/>
And in RecyclerView in the constructor for the ViewHolder I set
textView.setSelected(true);
But it doesn't work. Does anyone have an idea to solve this?
Thanks.
So here is the answer:
I put my TextView inside a HorizontalScrollView and added the following code to my adapter for the RecyclerView:
private void animateTextView(TextView mTextView) {
int textWidth = getTextViewWidth(mTextView);
int displayWidth = getDisplayWidth(mContext);
/* Start animation only when text is longer than dislay width. */
if(displayWidth<=textWidth) {
Animation mAnimation = new TranslateAnimation(
0, -textWidth,
0, 0);
mAnimation.setDuration(10000); // Set custom duration.
mAnimation.setStartOffset(1000); // Set custom offset.
mAnimation.setRepeatMode(Animation.RESTART); // This will animate text back ater it reaches end.
mAnimation.setRepeatCount(Animation.INFINITE); // Infinite animation.
mTextView.startAnimation(mAnimation);
}
}
private int getDisplayWidth(Context context) {
int displayWidth;
WindowManager windowManager = (WindowManager)context.getSystemService(
Context.WINDOW_SERVICE);
Display display = windowManager.getDefaultDisplay();
Point screenSize = new Point();
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB_MR2) {
display.getSize(screenSize);
displayWidth = screenSize.x;
} else {
displayWidth = display.getWidth();
}
return displayWidth;
}
private int getTextViewWidth(TextView textView) {
textView.measure(0, 0); // Need to set measure to (0, 0).
return textView.getMeasuredWidth();
}
And start the animation with:
animateTextView(txtView);
Note: there is no more need for the customized TextView, just use a normal TextView.

MvxRecyclerView ItemDecoration not working in Marshmallow

I am trying to use MvxRecyclerView. I have directly binded the ItemSource from the ViewModel and its redering the list. But i want the ListItemDivider in between,. So i made a custom ItemDecorator and used it with the recycler view. Its working for andorid 7.0 but not for marshmallow. I m not using any Holder, LinearLayoutManager or Adapter separately for the MvxRecyclerView.Please find the code below
Activity class
//****************************************************************************//
[Activity(Label = "EmployeeHub", Theme = "#style/MaterialTheme", ScreenOrientation = AndroidSystem.Content.PM.ScreenOrientation.Portrait)]
public class EmployeeHub : BaseView
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.EmployeeHub);
var reclycleView = this.FindViewById<MvxRecyclerView>(Resource.Id.my_recycler_view);
AndroidSystem.Support.V7.Widget.RecyclerView.ItemDecoration dividerItemDecoration = new DividerItemDecoration(this.ApplicationContext);
reclycleView.AddItemDecoration(dividerItemDecoration);
}
}
ItemDecorator
//********************************************************************//
public class DividerItemDecoration : RecyclerView.ItemDecoration
{
private AndroidSystem.Graphics.Drawables.Drawable divider;
private int[] attributes = new int[] {Attribute.ListDivider };
public DividerItemDecoration(Context context)
{
divider = context.GetDrawable(Resource.Drawable.noBorder);
TypedArray ta = context.ObtainStyledAttributes(attributes);
divider = ta.GetDrawable(0);
ta.Recycle();
}
public override void GetItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state)
{
if (parent.GetChildAdapterPosition(view) == 0)
{
return;
}
outRect.Top = divider.IntrinsicHeight;
}
public override void OnDraw(Canvas c, RecyclerView parent, RecyclerView.State state)
{
int left = parent.PaddingLeft;
int right = parent.Width - parent.PaddingRight;
for (int i = 0; i < parent.ChildCount; i++)
{
View child = parent.GetChildAt(i);
var parameters = child.LayoutParameters.JavaCast<RecyclerView.LayoutParams>();
int top = child.Bottom + parameters.BottomMargin;
int bottom = top + divider.IntrinsicHeight;
divider.SetBounds(left, top, right, bottom);
divider.Draw(c);
}
}
}
// layout **********************************************//
<MvxRecyclerView
android:id="#+id/my_recycler_view"
android:layout_below="#+id/hlhrview1"
android:scrollbars="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
local:MvxItemTemplate="#layout/employee_item_template"
local:MvxBind="ItemsSource Employees; ItemClick SelectedEmployee" />
I also had a problem getting this to work. With a tip from here and a few modifications to your code, I was able to get it working. Specifically, I am using the OnDrawOver as opposed to OnDraw
Here is my modified DividerItemDecoration:
public class DividerItemDecoration : RecyclerView.ItemDecoration
{
private readonly Drawable _divider;
public DividerItemDecoration(Context context)
{
_divider = ResourcesCompat.GetDrawable(context.Resources, Resource.Drawable.recyclerview_line_divider, context.Theme);
}
public override void OnDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state)
{
var left = parent.PaddingLeft;
var right = parent.Width - parent.PaddingRight;
for (var i = 0; i < parent.ChildCount; i++)
{
var child = parent.GetChildAt(i);
var parameters = child.LayoutParameters.JavaCast<RecyclerView.LayoutParams>();
var top = child.Bottom + parameters.BottomMargin;
var bottom = top + _divider.IntrinsicHeight;
_divider.SetBounds(left, top, right, bottom);
_divider.Draw(c);
}
}
}
I also put the binding code in my OnCreateView like this:
var reclycleView = _payformView.FindViewById<MvxRecyclerView>(Resource.Id.my_recycler_view);
RecyclerView.ItemDecoration dividerItemDecoration = new DividerItemDecoration(Application.Context);
reclycleView.AddItemDecoration(dividerItemDecoration);
All this is on a KitKat device.

Recycler View: Inconsistency detected. Invalid view holder adapter positionViewHolder

Recycler View Inconsistency Detected error, coming while scrolling fast or scrolling while loading more items..
FATAL EXCEPTION: main
Process: com.pratap.endlessrecyclerview, PID: 21997
java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder{56a082c position=40 id=-1, oldPos=39, pLpos:39 scrap [attachedScrap] tmpDetached no parent}
at android.support.v7.widget.RecyclerView$Recycler.validateViewHolderForOffsetPosition(RecyclerView.java:4251)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4382)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4363)
at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:1961)
at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1370)
at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1333)
at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:562)
at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:2864)
at android.support.v7.widget.RecyclerView.consumePendingUpdateOperations(RecyclerView.java:1445)
at android.support.v7.widget.RecyclerView.access$400(RecyclerView.java:144)
at android.support.v7.widget.RecyclerView$1.run(RecyclerView.java:282)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
at android.view.Choreographer.doCallbacks(Choreographer.java:670)
at android.view.Choreographer.doFrame(Choreographer.java:603)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
at android.os.Handler.handleCallback(Handler.java:746)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
Adapter
public class DataAdapter extends RecyclerView.Adapter {
private final int VIEW_ITEM = 1;
private final int VIEW_PROG = 0;
private List<Feed> mFeed;
// The minimum amount of items to have below your current scroll position
// before loading more.
private int visibleThreshold = 5;
private int lastVisibleItem, totalItemCount;
private boolean loading;
private OnLoadMoreListener onLoadMoreListener;
public DataAdapter(List<Feed> feeds, RecyclerView recyclerView) {
mFeed = feeds;
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)) {
// End has been reached
// Do something
if (onLoadMoreListener != null) {
onLoadMoreListener.onLoadMore();
}
loading = true;
}
}
});
}
}
#Override
public int getItemViewType(int position) {
return mFeed.get(position) == null ? VIEW_PROG : VIEW_ITEM;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
RecyclerView.ViewHolder vh;
if (viewType == VIEW_ITEM) {
View v = LayoutInflater.from(parent.getContext()).inflate(
R.layout.list_row, parent, false);
vh = new StudentViewHolder(v);
}
else {
View v = LayoutInflater.from(parent.getContext()).inflate(
R.layout.progress_item, parent, false);
vh = new ProgressViewHolder(v);
}
return vh;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof StudentViewHolder) {
Feed singleStudent= (Feed) mFeed.get(position);
((StudentViewHolder) holder).tvName.setText(singleStudent.getTitle());
((StudentViewHolder) holder).student= singleStudent;
} else {
ProgressViewHolder.PROGRESS_BAR.setIndeterminate(true);
}
}
public void setLoaded() {
loading = false;
}
public void addFeed(Feed feed) {
mFeed.add(feed);
//mFeed.addAll(0, (Collection<? extends Feed>) feed);
notifyItemInserted(mFeed.size());
//notifyItemRangeInserted(0,mFeed.size());
notifyDataSetChanged();
//notifyItemInserted(mFeed.size());
//setLoaded();
//notifyItemInserted(mFeed.size());
}
public void removeAll(){
mFeed.clear();
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return mFeed.size();
}
public void setOnLoadMoreListener(OnLoadMoreListener onLoadMoreListener) {
this.onLoadMoreListener = onLoadMoreListener;
}
public static class StudentViewHolder extends RecyclerView.ViewHolder {
public TextView tvName;
public Feed student;
public StudentViewHolder(View v) {
super(v);
tvName = (TextView) v.findViewById(R.id.tvName);
//tvEmailId = (TextView) v.findViewById(R.id.tvEmailId);
}
}
public static class ProgressViewHolder extends RecyclerView.ViewHolder {
//public ProgressBar progressBar;
public static ProgressBar PROGRESS_BAR;
public ProgressViewHolder(View v) {
super(v);
PROGRESS_BAR = (ProgressBar) v.findViewById(R.id.progressBar1);
// progressBar = (ProgressBar) v.findViewById(R.id.progressBar1);
}
}
}
Activity
public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {
private Toolbar toolbar;
private TextView tvEmptyView;
private RecyclerView mRecyclerView;
private DataAdapter mAdapter;
private LinearLayoutManager mLayoutManager;
private RestManager mManager;
private List<Feed> mFeed;
SwipeRefreshLayout mSwipeRefreshLayout;
protected Handler handler;
private int currentPage=1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
tvEmptyView = (TextView) findViewById(R.id.empty_view);
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
mSwipeRefreshLayout= (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
mSwipeRefreshLayout.setOnRefreshListener(this);
//studentList = new ArrayList<Student>();
mFeed = new ArrayList<Feed>();
handler = new Handler();
if (toolbar != null) {
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Android Students");
}
mManager = new RestManager();
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
// use a linear layout manager
mRecyclerView.setLayoutManager(mLayoutManager);
// create an Object for Adapter
mAdapter = new DataAdapter(mFeed,mRecyclerView);
// set the adapter object to the Recyclerview
mRecyclerView.setAdapter(mAdapter);
// mAdapter.notifyDataSetChanged();
loadData(false);
// if (mFeed.isEmpty()) {
// mRecyclerView.setVisibility(View.GONE);
// tvEmptyView.setVisibility(View.VISIBLE);
//
// } else {
// mRecyclerView.setVisibility(View.VISIBLE);
// tvEmptyView.setVisibility(View.GONE);
// }
mAdapter.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
//add null , so the adapter will check view_type and show progress bar at bottom
mFeed.add(null);
mAdapter.notifyItemInserted(mFeed.size() - 1);
handler.postDelayed(new Runnable() {
#Override
public void run() {
// remove progress item
mFeed.remove(mFeed.size() - 1);
// mAdapter.notifyItemRemoved(mFeed.size());
//add items one by one
int start = mFeed.size();
currentPage++;
Log.d("CurrentPage", String.valueOf(currentPage));
Call<Results> listCall = mManager.getFeedApi().getAllFeeds(1);
listCall.enqueue(new Callback<Results>() {
#Override
public void onResponse(Call<Results> call, Response<Results> response) {
mSwipeRefreshLayout.setRefreshing(false);
if (response.isSuccess()) {
if (response.body() != null) {
Results feedList = response.body();
// List<Results> newUsers = response.body();
Log.d("Retrofut", String.valueOf(feedList));
for (int i = 0; i < feedList.results.size(); i++) {
Feed feed = feedList.results.get(i);
// mFeed.add(feed);
mAdapter.addFeed(feed);
// mAdapter.notifyDataSetChanged();
//mAdapter.notifyItemInserted(mFeed.size());
}
// mAdapter.notifyDataSetChanged();
}
}
}
#Override
public void onFailure(Call<Results> call, Throwable t) {
Log.d("Retrofut", "Error");
mFeed.remove(mFeed.size() - 1);
mAdapter.notifyItemRemoved(mFeed.size());
mAdapter.setLoaded();
mSwipeRefreshLayout.setRefreshing(false);
}
});
// for (int i = 1; i <= 20; i++) {
// studentList.add(new Student("Student " + i, "androidstudent" + i + "#gmail.com"));
//
// }
mAdapter.setLoaded();
//or you can add all at once but do not forget to call mAdapter.notifyDataSetChanged();
}
}, 2000);
}
});
}
// load initial data
private void loadData(final boolean removePreData) {
Call<Results> listCall = mManager.getFeedApi().getAllFeeds(1);
listCall.enqueue(new Callback<Results>() {
#Override
public void onResponse(Call<Results> call, Response<Results> response) {
if (response.isSuccess()) {
if (response.body() != null) {
// if(removePreData) mAdapter.removeAll();
Results feedList = response.body();
Log.d("Retrofut", String.valueOf(feedList));
for (int i = 0; i < feedList.results.size(); i++) {
Feed feed = feedList.results.get(i);
// mFeed.add(feed);
//mAdapter.notifyDataSetChanged();
mAdapter.addFeed(feed);
}
mSwipeRefreshLayout.setRefreshing(false);
}
}
}
#Override
public void onFailure(Call<Results> call, Throwable t) {
Log.d("Retrofut", String.valueOf(t));
mFeed.remove(mFeed.size() - 1);
mAdapter.notifyItemRemoved(mFeed.size());
mAdapter.setLoaded();
mSwipeRefreshLayout.setRefreshing(false);
}
}
);
// for (int i = 1; i <= 20; i++) {
// studentList.add(new Student("Student " + i, "androidstudent" + i + "#gmail.com"));
//
// }
mSwipeRefreshLayout.setRefreshing(true);
}
#Override
public void onRefresh() {
mFeed.clear();
mAdapter.notifyDataSetChanged();
loadData(true);
currentPage=1;
}
}
put this line along with setting recyclerView. issue was fixed by
setting ItemAnimator to null for RecyclerView.
in kotlin
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.itemAnimator = null
in java
recyclerView.setItemAnimator(null);
It looks similar with known android bug
There are quite ugly, but working approach
public class WrapContentLinearLayoutManager extends LinearLayoutManager {
//... constructor
#Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
try {
super.onLayoutChildren(recycler, state);
} catch (IndexOutOfBoundsException e) {
Log.e("Error", "IndexOutOfBoundsException in RecyclerView happens");
}
}
}
mRecyclerView.setLayoutManager(new WrapContentGridLayoutManager(getContext(), spanCount));
For me it works without any by-effect.
This issue is a known bug of RecyclerView. The best solution is, clear the list every time before refresh RecyclerView.
For fix this issue just call notifyDataSetChanged() with empty list before updating recycle view.
For example
//Method for refresh recycle view
if (!yourList.isEmpty())
yourList.clear(); //The list for update recycle view
adapter.notifyDataSetChanged();
Use this to refresh a RecyclerView
items.clear(); //here items is an ArrayList populating the RecyclerView
adapter.notifyDataSetChanged();
items.addAll(list);// add new data
adapter.notifyItemRangeInserted(0, items.size);// notify adapter of new data
`
I had similiar issue, and also this solution has helped me, after I've added new item to my RV:
recyclerView.getRecycledViewPool().clear();
adapter.notifyDataSetChanged();
Maybe you can try this before refresh the adapter:
dataList.clear();
patrolListAdapter.notifyDataSetChanged();
In my case I was doing it as notifyItemInserted(position);
That caused me this issue then i used as and it worked perfectly.notifyItemRangeInserted(startIndex,endIndex);
I had this problem when scrolling fast through my endless/paging RecyclerView. The root of my problem came from the fact that I had a “header” item at the beginning of the list, this header item was not a part of the data source, it was just inserted at the beginning of the adapter list. So when scrolling fast and adding new pages of items to the RecyclerView Adapter and notify the adapter that new data had been inserted, I was not taking into account the additional header item, thus making the size of the adapter’s list wrong... and causing this exception...
So in short, if you’re using a header/footer in our RecyclerView adapter make sure you take it into account when updating the adapters data.
Example:
public void addNewPageToList(List<MyData> list)
{ //
// Make sure you account for any header/footer in your list!
//
// Add one to the currentSize to account for the header item.
//
int currentSize = this.adapterList.size() + 1;
this.adapterList.addAll(list);
notifyItemRangeInserted(currentSize, this.adapterList.size());
}
Edit:
I guess you could always just use the adapter method getItemCount() to get the size, instead of getting the size from the “data list” and adding to it. Your getItemCount() method should already be taking into account any additional headers/footers/etc that you have in your list.
The problem is in this line of code:
mFeed = feeds;
you are assigning mFeed to the caller's instance feeds so whenever the caller changes it's variable (may be adding, clearing or removing items), your local mFeed will change
try to change to
mFeed.addAll(feeds);
don't forget to initialize mFeed to any list tat fits your needs like mFeed = new ArrayList<>();
put this line along with setting recyclerView. issue was fixed by setting ItemAnimator to null for RecyclerView.
in kotlin
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.itemAnimator = null
I'm using the recyclerview from mikepenz. And any update to the items using .set(item) was causing this issue.
For some reason, setting recylerView.itemAnimator = null, resolved the issue. This is a known android bug.
In my case, I was using RecyclerView from Firebase UI. Initially, the logic to initialize the RecyclerView was in onCreate(). To fix, I put the logic in onResume() and seems to be working for me. I had this error when going back to the Activity which had the RecyclerView. So, everytime the Activity screen is refreshed, the new data is loaded.
I had similar problem. Removing all views from RecyclerView helped me:
RecyclerView.LayoutManager layoutManager = mRecyclerView.getLayoutManager();
layoutManager.removeAllViews();
For me the issue was I wasn't posting notifyDatasetChanged when the data set changed as I implemented incremental search.
I had a list that was filtered based on what the user searched in the search widget. For each item in the list, I was making a remote request, and when I got the result back, I was updating that particular cell.
I had to do both notifies for the recycler view to work
Filter the original data set then post the dataset change
this.searchResultTable?.post {
this.searchResultTable?.adapter?.notifyDataSetChanged()
}
After receiving response, post notifications again
this.searchResultTable?.post {
this.searchResultTable?.adapter?.notifyItemChanged(index, updateDataHashMap)
}
You have to post updates rather than sending notifiy messages directly in order to prevent the recycler view from crashing when the update comes in before the view is laid out.
Another important gotcha is that when you post the individual updates after the remote response, you have to make sure that the list the user currently sees is the list that existed when the requests were sent.
For my case in adapter there was notifyItemRangeInserted and I replaced it with notifyItemRangeChanged