mAdapter.notifyItemChanged(i) crashes on Android - java

I am trying to update a single TextView in my RecyclerView. I tried using mAdapter.notifyItemChanged(1); but this crashes the app and I can't figure out why. Calling mNumbersList.setAdapter(mAdapter); works fine.
Here is my adapter:
public class GreenAdapter extends RecyclerView.Adapter<GreenAdapter.NumberViewHolder> {
private final String TAG = GreenAdapter.class.getSimpleName();
private int mNumberItems;
public GreenAdapter(int numberOfItems) {
mNumberItems = numberOfItems;
}
#Override
public NumberViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
Context context = viewGroup.getContext();
int layoutIdForListItem;
if (viewType==1) { layoutIdForListItem = R.layout.first; } else { layoutIdForListItem = R.layout.number_list_item; }
LayoutInflater inflater = LayoutInflater.from(context);
boolean shouldAttachToParentImmediately = false;
View view = inflater.inflate(layoutIdForListItem, viewGroup, shouldAttachToParentImmediately);
NumberViewHolder viewHolder = new NumberViewHolder(view);
return viewHolder;
}
#Override
public int getItemViewType(int position) {
int First;
switch (position) {
case 0: First=1;
break;
default:
First = 0;
}
return First;
}
#Override
public void onBindViewHolder(NumberViewHolder holder, int position) {
Log.d(TAG, "#" + position);
holder.bind(position);
}
#Override
public int getItemCount() {
return mNumberItems;
}
class NumberViewHolder extends RecyclerView.ViewHolder {
TextView listItemNumberView;
public NumberViewHolder(View itemView) {
super(itemView);
listItemNumberView = (TextView) itemView.findViewById(R.id.TV1);
}
void bind(int listIndex) {
//String[] messages = getResources().getStringArray(R.array.messageArray);
//listItemNumberView.setText(messages[listIndex]);
switch (listIndex) {
case 0: if (setStatusError) {Status="Cannot connect to eve-central";} listItemNumberView.setText(Status);
break;
case 1: listItemNumberView.setText(Buy[listIndex-1]+" "+Sell[listIndex-1]);
break;
case 2: listItemNumberView.setText(Buy[listIndex-1]+" "+Sell[listIndex-1]);
break;
default:listItemNumberView.setText(String.valueOf(listIndex));
}
}
}
}
EDIT: Nevermind I am stupid. I had a handler that does this but it already starts before the RecyclerView is called...

Related

How to get data from nested Recycler View having CheckBox?

Actually this screen displays a set of questions and the task is to read the user entered or selected answer.
So the my question is, how to get the value from ChooseAdapter to QuestionAdapter and then get all the value from QuestionAdapter to my Activity.
My english is little bit weak, sorry for that.
And thanks in advance.
Main adapter : QuestionAdapter.java
public class QuestionsAdapter extends RecyclerView.Adapter<QuestionsAdapter.RecyclerViewHolder> {
private ArrayList<Question> mRecyclerViewItems;
private static final int MENU_ITEM_VIEW_TYPE = 0;
private static final String TAG = QuestionsAdapter.class.getSimpleName();
private static Context mContext;
private NetworkManager nm;
private boolean visibility = false;
private ChoiceAdapter adapter;
private ArrayList<QuestionsAnswer> questionsAnswers = new ArrayList<>();
ArrayList<ChoiceAnswer> choiceAnswers;
public QuestionsAdapter(Context context, ArrayList<Question> recyclerViewItems) {
this.mContext = context;
this.mRecyclerViewItems = recyclerViewItems;
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//this view contains recycler view under recycler view
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_question, parent, false);
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(v);
return recyclerViewHolder;
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
int viewType = getItemViewType(position);
switch (viewType) {
case MENU_ITEM_VIEW_TYPE:
default:
final RecyclerViewHolder recyclerViewHolder = (RecyclerViewHolder) holder;
Question data = (Question) mRecyclerViewItems.get(position);
try {
recyclerViewHolder.txtQuestion.setText(data.getQuestion());
recyclerViewHolder.txtQuestionType.setText(data.getQuestionType());
if (data.getQuestionType().equals("MULT")) {
recyclerViewHolder.mRecyclerChoice.setVisibility(View.VISIBLE);
recyclerViewHolder.edtQuestion.setVisibility(View.GONE);
if (data.getChoices().size() > 0) {
adapter = new ChoiceAdapter(mContext, data.getChoices(), position);
recyclerViewHolder.mRecyclerChoice.setAdapter(adapter);
}
} else {
recyclerViewHolder.mRecyclerChoice.setVisibility(View.GONE);
recyclerViewHolder.edtQuestion.setVisibility(View.VISIBLE);
}
recyclerViewHolder.btnOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (data.getQuestionType().equals("MULT")) {
Log.v(TAG, "array Data : " + adapter.getChoiceAnswer());
} else {
Log.v(TAG, "array Data : " + recyclerViewHolder.edtQuestion.getText().toString());
}
}
});
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}
#Override
public int getItemCount() {
return mRecyclerViewItems.size();
}
class RecyclerViewHolder extends RecyclerView.ViewHolder {
TextView txtQuestion,txtQuestionType;
EditText edtQuestion;
RecyclerView mRecyclerChoice;
Button btnOk;
private LinearLayoutManager linearLayoutManager;
public RecyclerViewHolder(View view) {
super(view);
txtQuestion = view.findViewById(R.id.txt_question);
edtQuestion = view.findViewById(R.id.edt_question);
mRecyclerChoice = view.findViewById(R.id.recycler_choice);
btnOk = view.findViewById(R.id.btn_ok);
txtQuestionType = view.findViewById(R.id.txt_question_type);
initRecyclerView();
btnOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (txtQuestionType.getText().toString().equals("MULT")) {
Log.v(TAG, "array Data : " + adapter.getChoiceAnswer());
} else {
Log.v(TAG, "array Data : " + edtQuestion.getText().toString());
}
}
});
}
private void initRecyclerView() {
//setting properties of recyclerView
mRecyclerChoice.setHasFixedSize(true);
mRecyclerChoice.setHasFixedSize(true);
linearLayoutManager = new LinearLayoutManager(mContext);
mRecyclerChoice.setLayoutManager(linearLayoutManager);
}
}
public static void validation() {
Toast.makeText(mContext, "testing", Toast.LENGTH_SHORT).show();
}}
for list of CheckBox : ChooseAdapter.java
public class ChoiceAdapter extends RecyclerView.Adapter<ChoiceAdapter.RecyclerViewHolder> {
private ArrayList<Choice> mRecyclerViewItems;
private static final int MENU_ITEM_VIEW_TYPE = 0;
private static final String TAG = ChoiceAdapter.class.getSimpleName();
private Context mContext;
private NetworkManager nm;
// private OnItemClickListener mOnItemClickListener;
private boolean visibility = false;
private static ArrayList<ChoiceAnswer> choiceAnswerArrayList;
private ChoiceAnswer choiceAnswer;
String arrayData;
public ChoiceAdapter(Context context, ArrayList<Choice> recyclerViewItems, int position) {
this.mContext = context;
this.mRecyclerViewItems = recyclerViewItems;
// choiceAnswer.key = 0;
choiceAnswerArrayList = new ArrayList<>();
//initializing choiceAnswer
choiceAnswer = new ChoiceAnswer();
choiceAnswer.values = new ArrayList<>();
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//this view contains recycler view under recycler view
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_radio_button, parent, false);
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(v);
return recyclerViewHolder;
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
int viewType = getItemViewType(position);
switch (viewType) {
case MENU_ITEM_VIEW_TYPE:
default:
final RecyclerViewHolder recyclerViewHolder = (RecyclerViewHolder) holder;
Choice data = (Choice) mRecyclerViewItems.get(position);
try {
recyclerViewHolder.checkChoice.setText(data.getChoiceName());
recyclerViewHolder.checkChoice.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
arrayData = "";
for (int i = 0; i < mRecyclerViewItems.size(); i++) {
if (isChecked) {
if (!choiceAnswer.values.contains(data.getChoiceID())) {
choiceAnswer.values.add(i, data.getChoiceID());
}
} else {
choiceAnswer.values.remove(data.getChoiceID());
// arrayData = choiceAnswer.values.toString().replace("[", "").replace("]", "").trim();
}
try {
arrayData = arrayData + "," + choiceAnswer.values.get(i);
}catch (IndexOutOfBoundsException e){
e.printStackTrace();
}
}
}
});
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}
public String getChoiceAnswer() {
return arrayData;
}
#Override
public int getItemCount() {
return mRecyclerViewItems.size();
}
class RecyclerViewHolder extends RecyclerView.ViewHolder {
CheckBox checkChoice;
public RecyclerViewHolder(View view) {
super(view);
checkChoice = view.findViewById(R.id.check_choice);
}
}}
Please help me guys I am trying this since last 3 days...
I've implemented my own login too, but it didn't working properly.

recyclerview.onBindviewholder always in position 0

recyclerview.onbindviewholder always in position 0
public class NoteAdapter extends RecyclerView.Adapter<NoteAdapter.ViewHolder> {
public static final int UNCOMPLETED = 0;
public static final int COMPLETED = 1;
public static final int HIGHTLIGHT = 2;
public static final int HIGHTLIGHT_COMPETED = 3;
Cursor cursor;
Context context;
public NoteAdapter(Context context, Cursor cursor) {
this.context = context;
this.cursor = cursor;
}
public Cursor getCursor() {
return this.cursor;
}
public void setCursor(Cursor cursor) {
this.cursor = cursor;
}
public Context getContext() {
return context;
}
public void setContext(Context context) {
this.context = context;
}
#Override
public int getItemViewType(int position) {
if (cursor.moveToPosition(position)) {
cursor.move(position);
String content = cursor.getString(cursor.getColumnIndex(DatabaseHandler.KEY_CONTENT));
int completed = cursor.getInt(cursor.getColumnIndex(DatabaseHandler.KEY_COMPLETED));
int hightlight = cursor.getInt(cursor.getColumnIndex(DatabaseHandler.KEY_HIGHTLIGHT));
if (completed == 1) {
if (hightlight == 1) {
return HIGHTLIGHT_COMPETED;
}
return COMPLETED;
}
if (hightlight == 1 && completed == 0) {
return HIGHTLIGHT;
}
return UNCOMPLETED;
}
return -1;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.item_row, parent, false);
switch (viewType) {
case UNCOMPLETED:
view = inflater.inflate(R.layout.item_row, parent, false);
break;
case COMPLETED:
view = inflater.inflate(R.layout.item_row_completed, parent, false);
break;
case HIGHTLIGHT:
view = inflater.inflate(R.layout.item_row_hightlight, parent, false);
break;
case HIGHTLIGHT_COMPETED:
view = inflater.inflate(R.layout.item_row_hightlight_completed, parent, false);
break;
}
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, int position) {
if (!cursor.moveToPosition(position)) {
return;
}
String content = cursor.getString(cursor.getColumnIndex(DatabaseHandler.KEY_CONTENT));
Date date = Utilities.stringToDate(cursor.getString(cursor.getColumnIndex(DatabaseHandler.KEY_DEADLINE)));
int completed = cursor.getInt(cursor.getColumnIndex(DatabaseHandler.KEY_COMPLETED));
holder.tvContent.setText(content);
holder.tvDate.setText(Utilities.dateToString(date));
if(completed == 1){
holder.imgIcon.performClick();
}
}
#Override
public int getItemCount() {
return (cursor.getCount());
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView tvContent;
TextView tvDate;
ImageButton imgIcon;
public ViewHolder(#NonNull final View itemView) {
super(itemView);
tvContent = itemView.findViewById(R.id.tvContent);
tvDate = itemView.findViewById(R.id.tvDate);
imgIcon = itemView.findViewById(R.id.imgCheck);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = getAdapterPosition();
cursor.move(position);
Note note = Utilities.cursorToNote(cursor);
Intent intent = new Intent(itemView.getContext(), AddNoteActivity.class);
intent.putExtras(note.sendNoteBundle());
intent.putExtra("type", true);
itemView.getContext().startActivity(intent);
}
});
}
}
}
The program does not contain any errors.
When I run the program, it always only shows the element at the 0 position, the remaining positions do not show.
function getItemCount works normally, returning 20 elements.
English is not my native language, sorry for any grammatical errors. Thanks, everyone.
Make sure the android:layout_height for your parent layout in the layout(xml) files for the various ViewHolders has been set to wrap_content instead of match_parent.

Where to manipulate the data in Recyclerview Adapter (Android)

My datetime is currently stored as UNIX time stamp. I want to display it as h:mm a in my Recyclerview.
Where should I convert the UNIX time stamp into normal time in the RecyclerView Adapter/Viewholder (in terms of the best performance)?
Should I do it in the getItemViewType(int position) of the RecyclerView.Adapter, or the onBindViewHolder or the bind function of the ViewHolder class?
Edit: My code
public class ChatListAdapter extends RecyclerView.Adapter {
private final LayoutInflater mInflater;
private List<Chat> mChats;
private final String ownerMe = "OWNER_ME";
private static final int VIEW_TYPE_MESSAGE_ME = 1;
private static final int VIEW_TYPE_MESSAGE_ME_CORNER = 2;
private static final int VIEW_TYPE_MESSAGE_BF = 3;
private static final int VIEW_TYPE_MESSAGE_BF_CORNER = 4;
ChatListAdapter(Context context) {mInflater = LayoutInflater.from(context);}
#Override
public int getItemViewType(int position) {
Chat chat = mChats.get(position);
if(chat.getUser().equals(ownerMe)) {
if(position == mChats.size()-1) {
return VIEW_TYPE_MESSAGE_ME_CORNER;
}
if(chat.getUser().equals(mChats.get(position+1).getUser())) {
return VIEW_TYPE_MESSAGE_ME;
} else {
return VIEW_TYPE_MESSAGE_ME_CORNER;
}
} else {
if(position == mChats.size()-1) {
return VIEW_TYPE_MESSAGE_BF_CORNER;
}
if(chat.getUser().equals(mChats.get(position+1).getUser())) {
return VIEW_TYPE_MESSAGE_BF;
} else {
return VIEW_TYPE_MESSAGE_BF_CORNER;
}
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
if(viewType == VIEW_TYPE_MESSAGE_ME || viewType == VIEW_TYPE_MESSAGE_ME_CORNER) {
view = mInflater.inflate(R.layout.recyclerview_item_right, parent, false);
return new MeMessageHolder(view);
} else if (viewType == VIEW_TYPE_MESSAGE_BF || viewType == VIEW_TYPE_MESSAGE_BF_CORNER) {
view = mInflater.inflate(R.layout.recyclerview_item_left, parent, false);
return new BfMessageHolder(view);
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (mChats != null) {
Chat current = mChats.get(position);
long unixTime= current.getUnixTime();
Date time = new java.util.Date(unixTime*1000L);
SimpleDateFormat sdf = new java.text.SimpleDateFormat("h:mm a");
String formattedTime = sdf.format(time);
switch (holder.getItemViewType()) {
case VIEW_TYPE_MESSAGE_ME:
((MeMessageHolder) holder).bind(current, formattedTime, false);
break;
case VIEW_TYPE_MESSAGE_ME_CORNER:
((MeMessageHolder) holder).bind(current, formattedTime, true);
break;
case VIEW_TYPE_MESSAGE_BF:
((BfMessageHolder) holder).bind(current, formattedTime, false);
break;
case VIEW_TYPE_MESSAGE_BF_CORNER:
((BfMessageHolder) holder).bind(current, formattedTime, true);
break;
}
}
}
class MeMessageHolder extends RecyclerView.ViewHolder {
private final TextView chatItemView;
private final ImageView cornerRightIImageView;
private final ConstraintLayout constraintLayout;
private final TextView timeItemView;
private MeMessageHolder(View itemView) {
super(itemView);
chatItemView = itemView.findViewById(R.id.textView);
cornerRightIImageView = itemView.findViewById(R.id.corner_view_right);
constraintLayout = itemView.findViewById(R.id.chat_bubble_id);
timeItemView = itemView.findViewById(R.id.text_message_time);
}
void bind(Chat chat, String formattedTime, boolean isCorner) {
chatItemView.setText(chat.getMessage());
timeItemView.setText(formattedTime);
if(isCorner) {
constraintLayout.setBackgroundResource(R.drawable.chat_bubble_v2);
} else {
cornerRightIImageView.setVisibility(View.INVISIBLE);
}
}
}
class BfMessageHolder extends RecyclerView.ViewHolder {
private final TextView chatItemView;
private final ImageView cornerLeftImageView;
private final ConstraintLayout constraintLayout;
private final TextView timeItemView;
private BfMessageHolder(View itemView) {
super(itemView);
chatItemView = itemView.findViewById(R.id.textView);
cornerLeftImageView = itemView.findViewById(R.id.corner_view_left);
constraintLayout = itemView.findViewById(R.id.chat_bubble_id);
timeItemView = itemView.findViewById(R.id.text_message_time);
}
void bind(Chat chat, String formattedTime, boolean isCorner) {
chatItemView.setText(chat.getMessage());
timeItemView.setText(formattedTime);
if(isCorner) {
constraintLayout.setBackgroundResource(R.drawable.chat_bubble_v3);
} else {
cornerLeftImageView.setVisibility(View.INVISIBLE);
}
}
}
void setChats(List<Chat> chats) {
mChats = chats;
notifyDataSetChanged();
}
#Override
public int getItemCount() {
if(mChats!=null)
return mChats.size();
else return 0;
}
}
This is method correct? I formatted the date in the onBindViewHoldermethod
It depends whether you want to display different dates on different items of the recyclerview, or the same date on all items of the recyclerview.
If you want to show same date to all items, better to do it outside of the adapter and then pass the parsed date to the recyclerview adapter.
Or, if you want to show different dates on each item, you should do it inside onBindViewHolder as it has access to the item position.
Remember, getItemViewType is used for getting a view type out of the available ones. This is used in case you are inflating multiple views. Think of a chatapp where view1 will display message on the left, and view2 will display message on the right; all within the same recyclerview.
The onBindViewHolder method simply performs a generic binding task. Binds what : the item of the inflated view and the data.
It seems like business logic. So, i recommend to move you UNIX time stamp convertation in Model for example.
class Chat {
private Long unixTime;
// another code
public Long getUnixTime() {
return unixTime;
}
public String convertedUnixTimeToString(String format) {
// Also need to add some format validation
if(format == null) {
// do some action, like trowing exception, or setting default value in format
}
Date time = new java.util.Date(unixTime*1000L);
SimpleDateFormat sdf = new java.text.SimpleDateFormat(format);
return sdf.format(time);
}
}
I recommend you to use JodaTime for date&time formatting. Very useful thing.
And then, just modify your code
public class ChatListAdapter extends RecyclerView.Adapter {
private final LayoutInflater mInflater;
private List<Chat> mChats;
private final String ownerMe = "OWNER_ME";
private static final int VIEW_TYPE_MESSAGE_ME = 1;
private static final int VIEW_TYPE_MESSAGE_ME_CORNER = 2;
private static final int VIEW_TYPE_MESSAGE_BF = 3;
private static final int VIEW_TYPE_MESSAGE_BF_CORNER = 4;
ChatListAdapter(Context context) {mInflater = LayoutInflater.from(context);}
#Override
public int getItemViewType(int position) {
Chat chat = mChats.get(position);
if(chat.getUser().equals(ownerMe)) {
if(position == mChats.size()-1) {
return VIEW_TYPE_MESSAGE_ME_CORNER;
}
if(chat.getUser().equals(mChats.get(position+1).getUser())) {
return VIEW_TYPE_MESSAGE_ME;
} else {
return VIEW_TYPE_MESSAGE_ME_CORNER;
}
} else {
if(position == mChats.size()-1) {
return VIEW_TYPE_MESSAGE_BF_CORNER;
}
if(chat.getUser().equals(mChats.get(position+1).getUser())) {
return VIEW_TYPE_MESSAGE_BF;
} else {
return VIEW_TYPE_MESSAGE_BF_CORNER;
}
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
if(viewType == VIEW_TYPE_MESSAGE_ME || viewType == VIEW_TYPE_MESSAGE_ME_CORNER) {
view = mInflater.inflate(R.layout.recyclerview_item_right, parent, false);
return new MeMessageHolder(view);
} else if (viewType == VIEW_TYPE_MESSAGE_BF || viewType == VIEW_TYPE_MESSAGE_BF_CORNER) {
view = mInflater.inflate(R.layout.recyclerview_item_left, parent, false);
return new BfMessageHolder(view);
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (mChats != null) {
Chat current = mChats.get(position);
switch (holder.getItemViewType()) {
case VIEW_TYPE_MESSAGE_ME:
((MeMessageHolder) holder).bind(current, false);
break;
case VIEW_TYPE_MESSAGE_ME_CORNER:
((MeMessageHolder) holder).bind(current, true);
break;
case VIEW_TYPE_MESSAGE_BF:
((BfMessageHolder) holder).bind(current, false);
break;
case VIEW_TYPE_MESSAGE_BF_CORNER:
((BfMessageHolder) holder).bind(current, true);
break;
}
}
}
class MeMessageHolder extends RecyclerView.ViewHolder {
private final TextView chatItemView;
private final ImageView cornerRightIImageView;
private final ConstraintLayout constraintLayout;
private final TextView timeItemView;
private MeMessageHolder(View itemView) {
super(itemView);
chatItemView = itemView.findViewById(R.id.textView);
cornerRightIImageView = itemView.findViewById(R.id.corner_view_right);
constraintLayout = itemView.findViewById(R.id.chat_bubble_id);
timeItemView = itemView.findViewById(R.id.text_message_time);
}
void bind(Chat chat, boolean isCorner) {
chatItemView.setText(chat.getMessage());
timeItemView.setText(chat.convertedUnixTimeToString("h:mm a"));
if(isCorner) {
constraintLayout.setBackgroundResource(R.drawable.chat_bubble_v2);
} else {
cornerRightIImageView.setVisibility(View.INVISIBLE);
}
}
}
class BfMessageHolder extends RecyclerView.ViewHolder {
private final TextView chatItemView;
private final ImageView cornerLeftImageView;
private final ConstraintLayout constraintLayout;
private final TextView timeItemView;
private BfMessageHolder(View itemView) {
super(itemView);
chatItemView = itemView.findViewById(R.id.textView);
cornerLeftImageView = itemView.findViewById(R.id.corner_view_left);
constraintLayout = itemView.findViewById(R.id.chat_bubble_id);
timeItemView = itemView.findViewById(R.id.text_message_time);
}
void bind(Chat chat, boolean isCorner) {
chatItemView.setText(chat.getMessage());
timeItemView.setText(chat.convertedUnixTimeToString("h:mm a"));
if(isCorner) {
constraintLayout.setBackgroundResource(R.drawable.chat_bubble_v3);
} else {
cornerLeftImageView.setVisibility(View.INVISIBLE);
}
}
}
void setChats(List<Chat> chats) {
mChats = chats;
notifyDataSetChanged();
}
#Override
public int getItemCount() {
if(mChats!=null)
return mChats.size();
else return 0;
}
}
You should be updating the UI changes in onBindViewHolder method. You can call bind method of ViewHolder in onBindViewHolder.
Example:
public class SampleAdapter extends RecyclerView.Adapter<SampleAdapter.ViewHolder> {
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.sample_view, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder viewHolder, int i) {
viewHolder.bind(i);
}
public class ViewHolder extends RecyclerView.ViewHolder {
public ViewHolder(#NonNull View itemView) {
super(itemView);
}
void bind(int position) {
// Do your data updates here.
}
}
}
Just Use SimpleDateFormat with yyyy-MM-dd pattern .
Apply SimpleDateFormat.format(millis) in onBindViewHolder method of RecyclerView.
You need to convert it to milliseconds by multiplying the timestamp by 1000:
java.util.Date dateTime=new java.util.Date((long)timeStamp*1000);
then first you need to convert UNIX timestamp to datetime format
final long unixTime = 1372339860;
final String formattedDtm = Instant.ofEpochSecond(unixTime)
.atZone(ZoneId.of("GMT-4"))
.format(formatter);
System.out.println(formattedDtm); // => '2013-06-27 09:31:00'
then you want to store this data to field value of RecyclerView
then you can format it from this time format like h:mm

How can I add onClickListener in Materialviewpage Adapter?

I am using this library from github: https://github.com/florent37/MaterialViewPager. I want the diffrent card views to open diffrent activities. How can I achieve it?
I couldn"t find any solution in wiki there
TestRecyclerViewAdapter.java
public class TestRecyclerViewAdapter extends
RecyclerView.Adapter<RecyclerView.ViewHolder> {
List<Object> contents;
static final int TYPE_HEADER = 0;
static final int TYPE_CELL = 1;
public TestRecyclerViewAdapter(List<Object> contents) {
this.contents = contents;
}
#Override
public int getItemViewType(int position) {
switch (position) {
case 0:
return TYPE_HEADER;
default:
return TYPE_CELL;
}
}
#Override
public int getItemCount() {
return contents.size();
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = null;
switch (viewType) {
case TYPE_HEADER: {
view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item_card_big, parent, false);
return new RecyclerView.ViewHolder(view) {
};
}
case TYPE_CELL: {
view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item_card_small, parent, false);
return new RecyclerView.ViewHolder(view) {
};
}
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
switch (getItemViewType(position)) {
case TYPE_HEADER:
break;
case TYPE_CELL:
break;
}
}
}
Well,
if you don't want to implement a custom viewHolder you can do something like this in the onBindViewHolder(RecyclerView.ViewHolder holder, int position):
holder.itemView.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
//start which activity you want
}
})
Otherwise you can implement a custom ViewHolder. Here is a guide:
https://developer.android.com/guide/topics/ui/layout/recyclerview

Setting RecyclerView Header without overriding first element

Hello i have a recyclerView which displays cards containing data fetched from mysql with retrofit. In my adapter, I was able to set the first card to a static element which is the user's profile picture as suggested by the accepted answer here. However they didn't notice that the method overrides the former first element (element at position 0). The first element gets replaced by the static view but i don't want that. I want
static card,
cardview 0,
cardview 1,
cardview 2,
etc
Any ideas? thanks
There isn't an easy way like listview.addHeaderView() but you can achieve this by adding a type to your adapter for header.
Here is an example
public class HeaderAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int TYPE_HEADER = 0;
private static final int TYPE_ITEM = 1;
String[] data;
public HeaderAdapter(String[] data) {
this.data = data;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == TYPE_ITEM) {
//inflate your layout and pass it to view holder
return new VHItem(null);
} else if (viewType == TYPE_HEADER) {
//inflate your layout and pass it to view holder
return new VHHeader(null);
}
throw new RuntimeException("there is no type that matches the type " + viewType + " + make sure your using types correctly");
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof VHItem) {
String dataItem = getItem(position);
//cast holder to VHItem and set data
} else if (holder instanceof VHHeader) {
//cast holder to VHHeader and set data for header.
}
}
#Override
public int getItemCount() {
return data.length + 1;
}
#Override
public int getItemViewType(int position) {
if (isPositionHeader(position))
return TYPE_HEADER;
return TYPE_ITEM;
}
private boolean isPositionHeader(int position) {
return position == 0;
}
private String getItem(int position) {
return data[position - 1];
}
class VHItem extends RecyclerView.ViewHolder {
TextView title;
public VHItem(View itemView) {
super(itemView);
}
}
class VHHeader extends RecyclerView.ViewHolder {
Button button;
public VHHeader(View itemView) {
super(itemView);
}
}
}
Use 'viewType' in 'RecyclerView.Adapter'.
onCreateViewHolder in RecyclerView
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
int layout = -1;
switch (viewType) {
case RecyclerViewItem.USER_PROFILE:
layout = R.layout.driving_item;
break;
case RecyclerViewItem.OTHER_USER_PROFILE:
layout = R.layout.date_item;
break;
case RecyclerViewItem.DATE:
layout = R.layout.send_button_item;
break;
}
View v = LayoutInflater.from(context).inflate(layout, parent, false);
return new MyViewHolder(v);
}
onBindViewHolder in RecyclerView
#Override
public void onBindViewHolder(final MyViewHolder myViewHolder, final int position) {
final int pos = myViewHolder.getAdapterPosition();
if (pos == -1) {
return;
}
final RecyclerViewItem item = ArrayList.get(pos);
switch (item.getType()) {
case RecyclerViewItem.USER_PROFILE:
//By type you want to do differently.
break;
case RecyclerViewItem.OTHER_USER_PROFILE:
//By type you want to do differently.
break;
case RecyclerViewItem.DATE:
//By type you want to do differently.
break;
}
}
f you have any additional questions, please let me know by comment.

Categories

Resources