add section on recyclerView dynamically on runtime (Java) - java

i have a RecyclerView which have some values now i want to add 2 sections one for favourites another for defaults i can do it manually like this :
i have ChannelsAdapter for holding the values :
public class ChannelsAdapter extends RecyclerView.Adapter<ChannelsAdapter.ChannelsViewHolder> implements Filterable {
private LayoutInflater inflater;
private Context context;
List<ChannelsInformation> data = Collections.emptyList();
private final List<ChannelsInformation> filteredChannelsList;
private final MultiSelector mMultiSelector = new MultiSelector();
ArrayList <String> selectedChannelName , selectedChannelID;
private HashMap<String, Boolean> map;
private TabFragment5 tabFragment5;
public ChannelsAdapter(Context context, List<ChannelsInformation> data){
inflater = LayoutInflater.from(context);
this.context = context;
this.data = data;
filteredChannelsList = data;
}
public void remove(int position){
data.remove(position);
notifyItemRemoved(position);
}
#Override
public ChannelsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View rowView = inflater.inflate(R.layout.custom_channel_row, parent, false);
ChannelsViewHolder holder = new ChannelsViewHolder(rowView);
return holder;
}
#Override
public void onBindViewHolder(final ChannelsViewHolder holder, final int position) {
final ChannelsInformation current = data.get(position);
holder.CHANNELNAME.setText(current.channelName);
selectedChannelName = new ArrayList<String>();
selectedChannelID = new ArrayList<String>();
holder.mSolvedCheckBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!selectedChannelID.contains(current.id)) {
holder.mSolvedCheckBox.setChecked(true);
selectedChannelName.add(current.channelName);
selectedChannelID.add(current.id);
} else {
holder.mSolvedCheckBox.setChecked(false);
selectedChannelName.remove(current.channelName);
selectedChannelID.remove(current.id);
}
}
});
}
#Override
public int getItemCount() {
return data.size();
}
#Override
public Filter getFilter() {
return new UserFilter(this ,filteredChannelsList);
}
private static class UserFilter extends Filter {
private final ChannelsAdapter adapter;
private final List<ChannelsInformation> originalList;
private final List<ChannelsInformation> filteredList;
private UserFilter(ChannelsAdapter adapter, List<ChannelsInformation> originalList) {
super();
this.adapter = adapter;
this.originalList = new ArrayList<>(originalList);
this.filteredList = new ArrayList<>();
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
filteredList.clear();
final FilterResults results = new FilterResults();
if (constraint == null || constraint.length() == 0) {
filteredList.addAll(originalList);
} else {
final String filterPattern = constraint.toString().toLowerCase().trim();
for (final ChannelsInformation channel : originalList) {
if ( (channel.channelName != null && channel.channelName.toLowerCase().contains(filterPattern))
)
{
filteredList.add(channel);
}
}
}
results.values = filteredList;
results.count = filteredList.size();
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
adapter.filteredChannelsList.clear();
if ((ArrayList<ChannelsInformation>) results.values != null ) {
adapter.filteredChannelsList.addAll((ArrayList<ChannelsInformation>) results.values);
}
adapter.notifyDataSetChanged();
} }
class ChannelsViewHolder extends SwappingHolder implements View.OnClickListener {
TextView CHANNELNAME;
CheckBox mSolvedCheckBox;
public ChannelsViewHolder(View itemView) {
super(itemView , mMultiSelector);
mMultiSelector.setSelectable(true);
mSolvedCheckBox = (CheckBox) itemView.findViewById(R.id.selectedChannelCheckBox);
itemView.setOnClickListener(this);
CHANNELNAME = (TextView) itemView.findViewById(R.id.ChannelNameTxtView);
}
#Override
public void onClick(View v) {
Toast.makeText(context, ""+CHANNELNAME.getText() ,Toast.LENGTH_SHORT).show();
tabFragment5 = new TabFragment5();
tabFragment5.addFavoriteSectionToRecyclerView(); // here am calling this function which is throwing me error
}
}}
and i have an another adapter for sections SimpleSectionedRecyclerViewAdapter :
public class SimpleSectionedRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final Context mContext;
private static final int SECTION_TYPE = 0;
private boolean mValid = true;
private int mSectionResourceId;
private int mTextResourceId;
private LayoutInflater mLayoutInflater;
private RecyclerView.Adapter mBaseAdapter;
private SparseArray<Section> mSections = new SparseArray<Section>();
public SimpleSectionedRecyclerViewAdapter(Context context, int sectionResourceId, int textResourceId,
RecyclerView.Adapter baseAdapter) {
mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mSectionResourceId = sectionResourceId;
mTextResourceId = textResourceId;
mBaseAdapter = baseAdapter;
mContext = context;
mBaseAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
#Override
public void onChanged() {
mValid = mBaseAdapter.getItemCount()>0;
notifyDataSetChanged();
}
#Override
public void onItemRangeChanged(int positionStart, int itemCount) {
mValid = mBaseAdapter.getItemCount()>0;
notifyItemRangeChanged(positionStart, itemCount);
}
#Override
public void onItemRangeInserted(int positionStart, int itemCount) {
mValid = mBaseAdapter.getItemCount()>0;
notifyItemRangeInserted(positionStart, itemCount);
}
#Override
public void onItemRangeRemoved(int positionStart, int itemCount) {
mValid = mBaseAdapter.getItemCount()>0;
notifyItemRangeRemoved(positionStart, itemCount);
}
});
}
public static class SectionViewHolder extends RecyclerView.ViewHolder {
public TextView title;
public SectionViewHolder(View view,int mTextResourceid) {
super(view);
title = (TextView) view.findViewById(mTextResourceid);
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int typeView) {
if (typeView == SECTION_TYPE) {
final View view = LayoutInflater.from(mContext).inflate(mSectionResourceId, parent, false);
return new SectionViewHolder(view,mTextResourceId);
}else{
return mBaseAdapter.onCreateViewHolder(parent, typeView -1);
}
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder sectionViewHolder, int position) {
if (isSectionHeaderPosition(position)) {
((SectionViewHolder)sectionViewHolder).title.setText(mSections.get(position).title);
}else{
mBaseAdapter.onBindViewHolder(sectionViewHolder,sectionedPositionToPosition(position));
}
}
#Override
public int getItemViewType(int position) {
return isSectionHeaderPosition(position)
? SECTION_TYPE
: mBaseAdapter.getItemViewType(sectionedPositionToPosition(position)) +1 ;
}
public static class Section {
int firstPosition;
int sectionedPosition;
CharSequence title;
public Section(int firstPosition, CharSequence title) {
this.firstPosition = firstPosition;
this.title = title;
}
public CharSequence getTitle() {
return title;
}
}
public void setSections(Section[] sections) {
mSections.clear();
Arrays.sort(sections, new Comparator<Section>() {
#Override
public int compare(Section o, Section o1) {
return (o.firstPosition == o1.firstPosition)
? 0
: ((o.firstPosition < o1.firstPosition) ? -1 : 1);
}
});
int offset = 0; // offset positions for the headers we're adding
for (Section section : sections) {
section.sectionedPosition = section.firstPosition + offset;
mSections.append(section.sectionedPosition, section);
++offset;
}
notifyDataSetChanged();
}
public int positionToSectionedPosition(int position) {
int offset = 0;
for (int i = 0; i < mSections.size(); i++) {
if (mSections.valueAt(i).firstPosition > position) {
break;
}
++offset;
}
return position + offset;
}
public int sectionedPositionToPosition(int sectionedPosition) {
if (isSectionHeaderPosition(sectionedPosition)) {
return RecyclerView.NO_POSITION;
}
int offset = 0;
for (int i = 0; i < mSections.size(); i++) {
if (mSections.valueAt(i).sectionedPosition > sectionedPosition) {
break;
}
--offset;
}
return sectionedPosition + offset;
}
public boolean isSectionHeaderPosition(int position) {
return mSections.get(position) != null;
}
#Override
public long getItemId(int position) {
return isSectionHeaderPosition(position)
? Integer.MAX_VALUE - mSections.indexOfKey(position)
: mBaseAdapter.getItemId(sectionedPositionToPosition(position));
}
#Override
public int getItemCount() {
return (mValid ? mBaseAdapter.getItemCount() + mSections.size() : 0);
}
}
and here is my Fragment where am adding values and sections TabFragment5 like this :
channelsAdapter = new ChannelsAdapter(getActivity(), getData()); // getting values
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
List<SimpleSectionedRecyclerViewAdapter.Section> sections =
new ArrayList<SimpleSectionedRecyclerViewAdapter.Section>();
//Sections , first section by default
sections.add(new SimpleSectionedRecyclerViewAdapter.Section(0, "All Channels"));
//Add your adapter to the sectionAdapter
SimpleSectionedRecyclerViewAdapter.Section[] dummy = new SimpleSectionedRecyclerViewAdapter.Section[sections.size()];
SimpleSectionedRecyclerViewAdapter mSectionedAdapter = new
SimpleSectionedRecyclerViewAdapter(getActivity(),R.layout.section,R.id.section_text,channelsAdapter);
mSectionedAdapter.setSections(sections.toArray(dummy));
recyclerView.setAdapter(mSectionedAdapter);
// well the above is working fine but this is 50% of what i want to accomplished , i want to add the an default section when user haven't set any value to favourite and once the user makes any value favourite i want to add the second section Favourites i don't know how can i do it dynamically on runtime , i tried this off course didn't worked i got an error :
public void addFavoriteSectionToRecyclerView(){
Toast.makeText(context, "Function Called" ,Toast.LENGTH_SHORT).show();
channelsAdapter = new ChannelsAdapter(getActivity(), getData());
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
List<SimpleSectionedRecyclerViewAdapter.Section> sections =
new ArrayList<SimpleSectionedRecyclerViewAdapter.Section>();
//Sections
sections.add(new SimpleSectionedRecyclerViewAdapter.Section(0, "Favorites")); // adding second Section dynamically
sections.add(new SimpleSectionedRecyclerViewAdapter.Section(0, "All Channels"));
//Add your adapter to the sectionAdapter
SimpleSectionedRecyclerViewAdapter.Section[] dummy = new SimpleSectionedRecyclerViewAdapter.Section[sections.size()];
SimpleSectionedRecyclerViewAdapter mSectionedAdapter = new
SimpleSectionedRecyclerViewAdapter(getActivity(),R.layout.section,R.id.section_text,channelsAdapter);
mSectionedAdapter.setSections(sections.toArray(dummy));
recyclerView.setAdapter(mSectionedAdapter);
}
my error :
03-08 13:50:41.397 4237-4237/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: pb.myPackage, PID: 4237
java.lang.NullPointerException
at android.view.LayoutInflater.from(LayoutInflater.java:211)
at pb.myPackage.ChannelsAdapter.<init>(ChannelsAdapter.java:52)
at pb.myPackage.TabFragment5.addFavoriteSectionToRecyclerView(TabFragment5.java:420)
at pb.myPackage.ChannelsAdapter$ChannelsViewHolder.onClick(ChannelsAdapter.java:236)
at android.view.View.performClick(View.java:4469)
at android.view.View$PerformClick.run(View.java:18468)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5021)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:827)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:643)
at dalvik.system.NativeStart.main(Native Method)
any idea guys why am getting this error ? if yes then please point out the problem or if my approach for adding this section on runtime is not good enough then please suggest me a better approach, any help or guidance will be much appreciated and helpful for me , thanks
P.S. for adding this sections i followed this SimpleSectionedRecyclerViewAdapter
UPDATE:
please see the image for better understanding , i have a normal RecyclerView where i putted a section named as default . now by default there's only first section which is named as default now if user selects any value as favourite i want to add another section named as Favourites and move the selected value to favourites section

tabFragment5 = new TabFragment5();
tabFragment5.addFavoriteSectionToRecyclerView(); // here am calling this function which is throwing me error
If TabFragment5 is indeed a Fragment, then the above code builds a brand new TabFragment5 and then calls addFavoriteSectionToRecyclerView().
Reading between the lines, I'm assuming you want to call this method on the current instance of TabFragment5, and that you don't want to create a new one.
For that, the simplest approach I can recommend is to use an EventBus.
Create an "Event" class as per the EventBus documention, i.e.:
public class AddFavoriteSectionEvent {
public AddFavoriteSectionEvent();
}
Register your Fragment to listen for events:
#Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
#Override
public void onStop() {
EventBus.getDefault().unregister(this);
super.onStop();
}
Add a method to your Fragment to respond to these events:
#Subscribe
public void onAddFavoriteEvent(AddFavoriteSectionEvent event){
addFavoriteSectionToRecyclerView();
}
And replace the two lines causing your NPE with:
EventBus.getDefault().post(new AddFavoriteSectionEvent());
This should resolve your NPE at least.

Related

How to flow Data from One RecyclerView to Another RecyclerView when an item in first RecyclerView is clicked?

Hi, I faced an issue here.. I was creating a chatbot in which user can type a text to send it and also can select a text out of the recommended texts
so I created two RecycleViews
My goal is - when the user selects one of the recommended text, then that text should appear in the Chatting RecycleView
here is my main Activity Class
public class Charts extends AppCompatActivity {
private static final String USER_KEY = "user";
private static final String BOT_KEY = "bot";
RecyclerView chart_recycle,auto_texts;
EditText message_text;
ImageView send_btn,mic_button;
ImageView setting_button;
ChartsAdapter chartsAdapter;
RecyclerView.LayoutManager linearLayout;
ArrayList<ChartModeClass> modeClassesArrayList = new ArrayList<>();
AutoAdapter autoAdapter;
RecyclerView.LayoutManager horizontal;
List<Texts> list = new ArrayList();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chatting_hole);
message_text = findViewById(R.id.message_text);
send_btn = findViewById(R.id.send_btn);
mic_button = findViewById(R.id.mic_btn);
setting_button = findViewById(R.id.setting_button);
chart_recycle = findViewById(R.id.chart_recycle);
chart_recycle.setHasFixedSize(true);
auto_texts = findViewById(R.id.auto_texts);
auto_texts.setHasFixedSize(true);
linearLayout = new LinearLayoutManager(getApplicationContext(), RecyclerView.VERTICAL, false);
chart_recycle.setLayoutManager(linearLayout);
//Auto text
horizontal = new LinearLayoutManager(getApplicationContext(),RecyclerView.HORIZONTAL, false);
auto_texts.setLayoutManager(horizontal);
chartsAdapter = new ChartsAdapter(modeClassesArrayList, Charts.this);
chart_recycle.setAdapter(chartsAdapter);
//Auto texts
autoAdapter = new AutoAdapter(getApplicationContext(),list);
auto_texts.setAdapter(autoAdapter);
addInputs();
BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(Charts.this);
mic_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
bottomSheetDialog.setContentView(R.layout.record);
bottomSheetDialog.show();
}
});
message_text.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (charSequence.toString().trim().length()==0){
mic_button.setVisibility(View.VISIBLE);
send_btn.setVisibility(View.GONE);
}else {
send_btn.setVisibility(View.VISIBLE);
mic_button.setVisibility(View.GONE);
}
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (charSequence.toString().trim().isEmpty()){
// Toast.makeText(getApplicationContext(),"Enter text",Toast.LENGTH_LONG).show();
mic_button.setVisibility(View.VISIBLE);
send_btn.setVisibility(View.GONE);
}else {
send_btn.setVisibility(View.VISIBLE);
mic_button.setVisibility(View.GONE);
}
}
#Override
public void afterTextChanged(Editable editable) {
if (editable.toString().length()==0){
mic_button.setVisibility(View.VISIBLE);
send_btn.setVisibility(View.GONE);
}
}
});
send_btn.setOnClickListener(view -> {
if (message_text.getText().toString().isEmpty()) {
Toast.makeText(Charts.this, "Please enter text..", Toast.LENGTH_SHORT).show();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
returnResponse(message_text.getText().toString());
}
message_text.setText("");
});
}
#SuppressLint("NotifyDataSetChanged")
private void returnResponse(String message) {
modeClassesArrayList.add(new ChartModeClass(message, USER_KEY));
chartsAdapter.notifyDataSetChanged();
chart_recycle.scrollToPosition(modeClassesArrayList.size()-1);
String url = "http://xxxxxxxxxxxxxxxx"+message;
String BASE_URL = "https://xxxxxxxxx";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
RetrofitApi retrofitApi = retrofit.create(RetrofitApi.class);
Call<MessageModeClass> call = retrofitApi.getMessage(url);
call.enqueue(new Callback<MessageModeClass>() {
#Override
public void onResponse(#NonNull Call<MessageModeClass> call, #NonNull Response<MessageModeClass> response) {
if (response.isSuccessful()) {
MessageModeClass messageModeClass = response.body();
if (messageModeClass != null) {
modeClassesArrayList.add(new ChartModeClass(messageModeClass.getCnt(), BOT_KEY));
}
chartsAdapter.notifyDataSetChanged();
chart_recycle.scrollToPosition(modeClassesArrayList.size() - 1);
} else {
Toast.makeText(Charts.this, "response is null", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(#NonNull Call<MessageModeClass> call, #NonNull Throwable t) {
modeClassesArrayList.add(new ChartModeClass("No response check your network connection!", BOT_KEY));
chartsAdapter.notifyDataSetChanged();
chart_recycle.scrollToPosition(modeClassesArrayList.size() - 1);
}
});
}
#SuppressLint("NotifyDataSetChanged")
#Override
protected void onStart() {
super.onStart();
String lang = getIntent().getExtras().getString("lang");
if (lang.equals("english")){
modeClassesArrayList.add(new ChartModeClass("Hey welcome back am fema bot", BOT_KEY));
chartsAdapter.notifyDataSetChanged();
chart_recycle.scrollToPosition(modeClassesArrayList.size() - 1);
}else if (lang.equals("swahili")){
modeClassesArrayList.add(new ChartModeClass("Habari karibu miminni bot niliyetengenezw", BOT_KEY));
chartsAdapter.notifyDataSetChanged();
chart_recycle.scrollToPosition(modeClassesArrayList.size() - 1);
}else {
modeClassesArrayList.add(new ChartModeClass("Hey welcome back am fema bot", BOT_KEY));
chartsAdapter.notifyDataSetChanged();
chart_recycle.scrollToPosition(modeClassesArrayList.size() - 1);
}
}
private void addInputs() {
Texts text1 = new Texts("gender?");
Texts text2 = new Texts("gender equality");
Texts text3 = new Texts("what is good about females");
Texts text4 = new Texts("un goals");
Texts text5 = new Texts("about men");
list.addAll(Arrays.asList(new Texts[]{text1,text2,text3,text4,text5}));
}
}
here is my Adapter class class codes
public class AutoAdapter extends RecyclerView.Adapter<AutoAdapter.ViewHolderClass> {
Context context;
List<Texts> list;
public AutoAdapter(Context context, List<Texts> list) {
this.context = context;
this.list = list;
}
#NonNull
#Override
public ViewHolderClass onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.text_list,parent,false);
ViewHolderClass viewHolderClass = new ViewHolderClass(view);
return viewHolderClass;
}
#Override
public void onBindViewHolder(#NonNull ViewHolderClass holder, #SuppressLint("RecyclerView") int position) {
holder.input_text.setText(list.get(position).getText());
holder.input_text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// my stack
}
});
}
#Override
public int getItemCount() {
return list.size();
}
public class ViewHolderClass extends RecyclerView.ViewHolder {
TextView input_text;
public ViewHolderClass(#NonNull View itemView) {
super(itemView);
input_text = itemView.findViewById(R.id.input_text);
}
}
}
You can add a list of your recommendations in another RecyclerView
Then in the ViewHolder of each item of the RecyclerView add Callback to listen on click events when a user clicks one of the item like the following
public class ViewHolderClass extends RecyclerView.ViewHolder {
private TextView input_text;
private final Callback callback; // custom callback
public ViewHolderClass(#NonNull View itemView, Callback callback) {
super(itemView);
this.callback = callback;
input_text = itemView.findViewById(R.id.input_text);
// now add onClickListener of the itemView to fire custom callback
itemView.setOnClickListener(view -> {
this.callback.onItemClick(getAdapterPosition());
});
}
// this is my custom callback for return click event
public interface Callback {
void onItemClick(int position);
}
}
Now inside your adapter add the callback from viewholder
public class AutoAdapter extends RecyclerView.Adapter<AutoAdapter.ViewHolderClass> {
private Context context;
private List<Texts> list;
private AutoAdapterCallback callback;
public AutoAdapter(Context context, List<Texts> list) {
this.context = context;
this.list = list;
}
public setCallback(AutoAdapterCallback callback) {
this.callback = callback;
}
#NonNull
#Override
public ViewHolderClass onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.text_list,parent,false);
ViewHolderClass viewHolderClass = new ViewHolderClass(view, new ViewHolderClass.Callback() {
#Override
public void onItemClick(int position) {
// forward callback to adapter callback
if (callback != null) {
// get actual item from its position
final Texts texts = getItemByPosition(position);
// send to adapter callback
callback.onItemClick(texts);
}
});
return viewHolderClass;
}
#Override
public void onBindViewHolder(#NonNull ViewHolderClass holder, #SuppressLint("RecyclerView") int position) {
holder.input_text.setText(list.get(position).getText());
// I haven't used this inteady I added callback on viewholder side
// holder.input_text.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View view) {
// // my stack
// }
// });
}
#Override
public int getItemCount() {
return list.size();
}
// return Texts object by given position
public Texts getItemByPosition(int position) {
return this.list.get(position);
}
// add adapter callback to be called by viewholder
public interface AdapterCallback {
void onItemClick(Texts texts);
}
}
After that, now on your Activity you can easily listen on any item when a user clicks and get its corresponding Texts object from list as following:
//code ...
// here
//Auto texts
autoAdapter = new AutoAdapter(getApplicationContext(),list);
//set callback to listen for click events
autoAdapter.setCallback(new AutoAdapter.AutoAdapterCallback() {
#Override
public void onItemClick(Texts texts) {
// you can get your clicked item here
// now you can put texts object to another RecyclerView :)
}
});
auto_texts.setAdapter(autoAdapter);
//code ...

implementing interface in android LinearLayout class - RecycleViewGenericAdapter [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 1 year ago.
I have a generic RecycleView for which I have different row classes, in this row class I would like to implement an interface, my objective is to pass the text from OnQueryTextListener to an activity or fragment where the interface is implemented.
public class PlantDocHeader extends LinearLayout implements RecycleViewGenericAdapter.RecyclerViewRowHeader<PlantDocViewModel> {
private Button buttonQuestion;
private Button buttonPosts;
private TextView searchTxtField;
private ImageView imageViewExpandSearch;
private SearchView searchView;
private boolean expand = true;
SearchView.OnQueryTextListener onQueryTextListener;
private onTextChange onTextChange;
Resources res;
public PlantDocHeader(Context context) {
super(context);
}
public PlantDocHeader(Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
}
public PlantDocHeader(Context context, #Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
#Override
protected void onFinishInflate() {
super.onFinishInflate();
searchTxtField = findViewById(R.id.textView_plant_doc_header_search);
imageViewExpandSearch = findViewById(R.id.imageView_plant_doc_header_expand_button);
searchView = findViewById(R.id.searchView_plant_doc_header);
buttonQuestion = findViewById(R.id.button_plant_doc_header_filter_my_posts);
buttonPosts = findViewById(R.id.button_plant_doc_header_filter_question);
}
#Override
public void showData(PlantDocViewModel item) {
res = getResources();
buttonQuestion.setText(res.getString(R.string.question));
buttonQuestion.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
AskQuestionFragment askQuestionFragment = new AskQuestionFragment();
ChangeFragment(askQuestionFragment, (Activity) getContext(), false);
}
});
buttonPosts.setText(res.getString(R.string.my_posts));
buttonPosts.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
PlantDocMyPostsFragment myPostsFragment = new PlantDocMyPostsFragment();
ChangeFragment(myPostsFragment, (Activity) getContext(), false);
}
});
searchTxtField.setText(res.getString(R.string.search));
imageViewExpandSearch.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(expand){
searchView.setVisibility(VISIBLE);
imageViewExpandSearch.setImageResource(R.drawable.collapse);
expand = false;
}else{
searchView.setVisibility(GONE);
imageViewExpandSearch.setImageResource(R.drawable.expand);
expand = true;
}
}
});
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
Toast.makeText(getContext(), ""+newText, Toast.LENGTH_SHORT).show();
onTextChange.textSearch(newText);
return true;
}
});
}
public interface onTextChange {
void textSearch(String searchText);
}
}
This is the error I am getting
Attempt to invoke interface method 'void
com.gardify.android.UI.PlantDoc.PlantDocHeader$onTextChange.textSearch(java.lang.String)'
on a null object reference
RecycleViewGenericAdapter
/**
* #param <T> is generic parameter type provided to List, OnRecyclerViewItemClickListener and RecyclerViewRow
* #param <V> generic type for header view Model
* #param <E> generic type for footer view Model
*/
public class RecycleViewGenericAdapter<T, V, E> extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<T> mDataset;
private V mHeaderData;
private E mFooterData;
private static final int TYPE_HEADER = 000;
private static final int TYPE_ITEM = 111;
private static final int TYPE_FOOTER = 222;
private OnItemClickListener<T> onItemClickListener;
private OnItemClickListenerHeader<V> onItemClickListenerHeader;
private OnItemClickListenerFooter<E> onItemClickListenerFooter;
private int layoutId, layoutIdHeader, layoutIdFooter;
public RecycleViewGenericAdapter(List<T> mDataset, int layoutId, V mHeaderData, int layoutIdHeader,
E mFooterData, int layoutIdFooter, OnItemClickListener<T> onItemClickListener,
OnItemClickListenerHeader onItemClickListenerHeader, OnItemClickListenerFooter onItemClickListenerFooter) {
this.onItemClickListener = onItemClickListener;
this.onItemClickListenerHeader = onItemClickListenerHeader;
this.onItemClickListenerFooter = onItemClickListenerFooter;
this.mDataset = mDataset;
this.mHeaderData = mHeaderData;
this.mFooterData = mFooterData;
this.layoutId = layoutId;
this.layoutIdHeader = layoutIdHeader;
this.layoutIdFooter = layoutIdFooter;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder vh = null;
if (viewType == TYPE_ITEM) {
RecyclerViewRow<T> row = (RecyclerViewRow<T>) LayoutInflater.from(parent.getContext()).inflate(layoutId, parent, false);
vh = new ItemViewHolder(row);
}else if (viewType == TYPE_HEADER) {
RecyclerViewRowHeader<V> rowHeader = (RecyclerViewRowHeader<V>) LayoutInflater.from(parent.getContext()).inflate(layoutIdHeader, parent, false);
vh = new HeaderViewHolder(rowHeader);
} else if(viewType == TYPE_FOOTER) {
RecyclerViewRowFooter<E> footerRow = (RecyclerViewRowFooter<E>) LayoutInflater.from(parent.getContext()).inflate(layoutIdFooter, parent, false);
vh = new FooterViewHolder(footerRow);
}
return vh;
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, final int position) {
if (holder instanceof RecycleViewGenericAdapter.ItemViewHolder) {
ItemViewHolder itemViewHolder = (ItemViewHolder) holder;
itemViewHolder.onBind((mHeaderData!=null? position-1 : position), itemViewHolder);
} else if (holder instanceof RecycleViewGenericAdapter.HeaderViewHolder) {
HeaderViewHolder headerViewHolder = (HeaderViewHolder) holder;
headerViewHolder.onBind(headerViewHolder);
} else if (holder instanceof RecycleViewGenericAdapter.FooterViewHolder) {
FooterViewHolder footerViewHolder = (FooterViewHolder) holder;
footerViewHolder.onBind(footerViewHolder);
}
}
#Override
public int getItemCount() {
if (mHeaderData != null && mFooterData != null) {
return mDataset.size() + 2;
} else if (mHeaderData != null || mFooterData != null) {
return mDataset.size() + 1;
}
return mDataset.size();
}
private int getLastPosition() {
return getItemCount() - 1;
}
private boolean isLastPosition(int position) {
return position == getLastPosition();
}
#Override
public int getItemViewType(int position) {
if (position == 0 && mHeaderData!=null) {
return TYPE_HEADER;
} else if (isLastPosition(position) && mFooterData!=null) {
return TYPE_FOOTER;
} else {
return TYPE_ITEM;
}
}
/**
* Item ViewHolder
**/
public class ItemViewHolder extends RecyclerView.ViewHolder {
public RecyclerViewRow<T> mRow;
public ItemViewHolder(RecyclerViewRow<T> itemView) {
super((View) itemView);
mRow = itemView;
}
private void onBind(final int position, ItemViewHolder viewHolder) {
viewHolder.mRow.showData(mDataset.get(position));
((View) viewHolder.mRow).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (onItemClickListener != null) {
onItemClickListener.onItemClick(mDataset.get(position));
}
}
});
}
}
public interface RecyclerViewRow<T> {
void showData(T item);
}
public interface OnItemClickListener<T> {
void onItemClick(T position);
}
public void updateList(List<T> _mDataset){
this.mDataset= _mDataset;
notifyDataSetChanged();
}
/**
* Header ViewHolder
**/
public class HeaderViewHolder extends RecyclerView.ViewHolder {
public RecyclerViewRowHeader<V> mRowHeader;
public HeaderViewHolder(RecyclerViewRowHeader<V> itemView) {
super((View) itemView);
mRowHeader = itemView;
}
private void onBind(HeaderViewHolder viewHolder) {
viewHolder.mRowHeader.showData(mHeaderData);
((View) viewHolder.mRowHeader).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (onItemClickListenerHeader != null) {
onItemClickListenerHeader.onItemClickHeader(mHeaderData);
}
}
});
}
}
public interface RecyclerViewRowHeader<V> {
void showData(V item);
}
public interface OnItemClickListenerHeader<V> {
void onItemClickHeader(V position);
}
/**
* Footer ViewHolder
**/
public class FooterViewHolder extends RecyclerView.ViewHolder {
public RecyclerViewRowFooter<E> mRowFooter;
public FooterViewHolder(RecyclerViewRowFooter<E> itemView) {
super((View) itemView);
mRowFooter = itemView;
}
private void onBind(FooterViewHolder viewHolder) {
viewHolder.mRowFooter.showData(mFooterData);
((View) viewHolder.mRowFooter).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (onItemClickListenerFooter != null) {
onItemClickListenerFooter.onItemClickFooter(mFooterData);
}
}
});
}
}
public interface RecyclerViewRowFooter<E> {
void showData(E item);
}
public interface OnItemClickListenerFooter<E> {
void onItemClickFooter(E position);
}
}
Usage in Fragment
public class PlantDocFragment extends Fragment implements RecycleViewGenericAdapter.OnItemClickListener<PlantDocViewModel>, PlantDocHeader.OnTextChangeListener {
//...
RecycleViewGenericAdapter<PlantDocViewModel, PlantDocViewModel, Nullable> adapter = new RecycleViewGenericAdapter<>(plantDocList, R.layout.recycler_view_plant_doc_row_item, plantDocHeader, R.layout.recycler_view_plant_doc_header,
null, 0, this, null, null);
//...
#Override
public void textSearch(String searchText) {
Toast.makeText(getContext(), "searched text : "+searchText, Toast.LENGTH_SHORT).show();
}
the generic recycleview that i am using can be found here
Basically you need to pass fragments reference to the HeaderView .
For this first of all you have to have a setter in PlantDocHeader as below . I have removed the interface also it seems useless.
public class PlantDocHeader<T> extends LinearLayout {
private OnTextChangeListener onTextChangeListener;
public void setOnTextChangeListener(OnTextChangeListener onTextChangeListener) {
this.onTextChangeListener = onTextChangeListener;
}
public void setData(T data) {
}
}
Rephrase your Adapters constructor a bit its taking a lots of argument a Builder will probably help or you can create separate setters for optional properties.
public class RecycleViewGenericAdapter<T, V, E> extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private OnItemClickListener<T> onItemClickListener;
private OnItemClickListenerHeader<V> onItemClickListenerHeader;
private OnItemClickListenerFooter<E> onItemClickListenerFooter;
private PlantDocHeader.OnTextChangeListener onTextChangeListener;
private int layoutId, layoutIdHeader, layoutIdFooter;
public RecycleViewGenericAdapter(List<T> mDataset, int layoutId, V mHeaderData, int layoutIdHeader,
E mFooterData, int layoutIdFooter) {
this.mDataset = mDataset;
this.mHeaderData = mHeaderData;
this.mFooterData = mFooterData;
this.layoutId = layoutId;
this.layoutIdHeader = layoutIdHeader;
this.layoutIdFooter = layoutIdFooter;
}
}
Create separate setters for all listeners and set them as they needed from the calling component. Now when you done setting you need to pass onTextChangeListener to header view.
public class HeaderViewHolder extends RecyclerView.ViewHolder {
public RecyclerViewRowHeader<V> mRowHeader;
public HeaderViewHolder(RecyclerViewRowHeader<V> itemView) {
super((View) itemView);
mRowHeader = itemView;
}
private void onBind(HeaderViewHolder viewHolder) {
viewHolder.mRowHeader.setOnTextChangeListener(onTextChangeListener);
viewHolder.mRowHeader.showData(mHeaderData);
((View) viewHolder.mRowHeader).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (onItemClickListenerHeader != null) {
onItemClickListenerHeader.onItemClickHeader(mHeaderData);
}
}
});
}
}
Now it should work . also you might wanna consider passing position between listener because there can be multiple headers also if not then it will be 0 always.
PS- If you are trying to create a generic adapter you should consider creating a abstract Adapter class right now your class does not seems generic because you are passing way too many arguments in constructor which should in child class only its not flexible at all. You might wanna check some open source generic adapter for this to see .
You have not told what to do when I call textSearch() method.
You have to implement onTextChange interface (Please follow Java naming convention when declaring interface/class/variables) in some class where you will override textSearch() method and then pass the reference (implemented class) to the variable onTextChange (you have given same name of interface and instance variable so to avoid confusion you can give another name to variable).
Then when you call textSearch() in this line onTextChange.textSearch(newText); you will have implementation. And your code will work.
In your adapter create a public method:
public void setOnTextChange(onTextChange onTextChange) {
this.onTextChange = onTextChange;
}
In your fragment, change your implements to implement your interface:
implements PlantDocHeader.OnTextChange
Then set the onTextChange:
adapter.setOnTextChange(this);

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.

How to display the Auto Scrolling RecyclerView position on TextView?

I am doing an app which auto-scrolls images, at the bottom of the screen there is a static layout, which I need to display the value of images that have already passed (i.e. position).
I get the correct value of images passed by implementing :
int position = holder.getAdapterPosition();
in the RecyclerViewListAdapter.java
now I need to display this value in the RecyclerViewListActivity.java
on a text view at the static layout beneath the Recycler view?
public class RecyclerViewListAdapter extends RecyclerView.Adapter {
Context context;
List<Data> dataList;
private SharedPreferences preferences;
public RecyclerViewListAdapter(Context context, List<Data> dataList) {
this.context = context;
this.dataList = dataList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_recycler_list, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
holder.mImage.setImageResource(dataList.get(position).getImage());
holder.mImage.setImageResource(dataList.get(position).getImage());
**int position = holder.getAdapterPosition();**
}
#Override
public int getItemCount() {
if (dataList == null || dataList.size() == 0)
return 0;
return dataList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView mNumberText,mText;
ImageView mImage;
LinearLayout mLinearLayout;
public MyViewHolder(View itemView) {
super(itemView);
mImage = (ImageView) itemView.findViewById(R.id.quran_page);
mLinearLayout = (LinearLayout) itemView.findViewById(R.id.linearLayout);
}
}
}
public class RecyclerViewListActivity extends AppCompatActivity {
RecyclerView mListRecyclerView;
ArrayList<Data> dataArrayList;
RecyclerViewListAdapter recyclerViewListAdapter ;
Runnable updater;
private boolean isTouch = false;
TextViewRemaining;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recycler_view_list);
final TextView TextViewRemaining = (TextView) findViewById(R.id.TextViewRemaining);
**TextViewRemaining.setText("Position: "+position);**
initializeView();
mListRecyclerView.addOnItemTouchListener(new RecyclerTouchListener(this,
mListRecyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
}
#Override
public void onLongClick(View view, int position) {
Toast.makeText(RecyclerViewListActivity.this, "Long press on position :" + position,
Toast.LENGTH_LONG).show();
}
}));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
public static interface ClickListener{
public void onClick(View view,int position);
public void onLongClick(View view,int position);
}
class RecyclerTouchListener implements RecyclerView.OnItemTouchListener{
private ClickListener clicklistener;
private GestureDetector gestureDetector;
//#RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
public RecyclerTouchListener(Context context, final RecyclerView recycleView, final ClickListener clicklistener){
this.clicklistener=clicklistener;
gestureDetector=new GestureDetector(context,new GestureDetector.SimpleOnGestureListener(){
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child=recycleView.findChildViewUnder(e.getX(),e.getY());
if(child!=null && clicklistener!=null){
clicklistener.onLongClick(child,recycleView.getChildAdapterPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child=rv.findChildViewUnder(e.getX(),e.getY());
if(child!=null && clicklistener!=null && gestureDetector.onTouchEvent(e)){
clicklistener.onClick(child,rv.getChildAdapterPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
private void initializeView()
{
mListRecyclerView = (RecyclerView) findViewById(R.id.vR_recyclerViewList);
setValues();
}
private void setValues(){
prepareData();
recyclerViewListAdapter = new RecyclerViewListAdapter(RecyclerViewListActivity.this,dataArrayList);
mListRecyclerView.setLayoutManager(new LinearLayoutManager(RecyclerViewListActivity.this)); // original
mListRecyclerView.setItemAnimator(new DefaultItemAnimator());
mListRecyclerView.setHasFixedSize(false);
mListRecyclerView.setAdapter(recyclerViewListAdapter);
recyclerViewListAdapter.notifyDataSetChanged();
final int speedScroll = 2000; //default is 2000 it need to be 30000
final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
int count = 0;
// boolean flag = true;
#Override
public void run() {
boolean x=true;
// while(x) {
if (count < recyclerViewListAdapter.getItemCount()) {
if (count == recyclerViewListAdapter.getItemCount() - 1) {
flag = false;
} else if (count == 0) {
flag = true;
}
}
if (flag) count++;
// else count--;
mListRecyclerView.smoothScrollToPosition(count);
handler.postDelayed(this, speedScroll);
}
};
handler.postDelayed(runnable,speedScroll);
}
private void prepareData(){
dataArrayList = new ArrayList<>();
Data data1 = new Data();
data1.setImage(R.drawable.p1);
dataArrayList.add(data1);
Data data2 = new Data();
data2.setImage(R.drawable.p2);
dataArrayList.add(data2);
Data data3 = new Data();
data3.setImage(R.drawable.p3);
dataArrayList.add(data3);
Data data4 = new Data();
data4.setImage(R.drawable.p4);
dataArrayList.add(data4);
Data data5 = new Data();
data5.setImage(R.drawable.p5);
dataArrayList.add(data5);
}
}
So, How can I show the position value on textView in a real-time, as position is a dynamic value, I expect the output on the textView to change as the images passed to the top.
Many Thanks in advance.
This how I solve my problem:
I save the position value in a power Preference(an easier version of shared Preferences)-many thanks to:
Ali Asadi(https://android.jlelse.eu/powerpreference-a-simple-approach-to-store-data-in-android-a2dad4ddc4ac)
I use a Thread that updates the textview every second-many thanks to:
https://www.youtube.com/watch?v=6sBqeoioCHE&t=149s
Thanks for all.

I want to display an image from drawable and combine it with data from json-api into recylerview

I have an application project for news media using java programming, I
want to display images for categories from drawable into recylerview
that are based on json-api, is there any one who can help me?
How I do for load image from drawable and combine it with data from json-api into RecylerView can anyone provide specific code here
this is my AdapterCategory.java
public class AdapterCategory extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<Category> items = new ArrayList<>();
private Context ctx;
private OnItemClickListener mOnItemClickListener;
private int c;
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 ImageView imageView;
public ViewHolder(View v) {
super(v);
name = (TextView) v.findViewById(R.id.name);
post_count = (TextView) v.findViewById(R.id.post_count);
imageView = (ImageView)v.findViewById(R.id.image_category);
lyt_parent = (LinearLayout) v.findViewById(R.id.lyt_parent);
//imageView.setImageResource(image_array.length);
}
}
#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(RecyclerView.ViewHolder holder, final int position) {
if(holder instanceof ViewHolder) {
final Category c = items.get(position);
ViewHolder vItem = (ViewHolder) holder;
vItem.name.setText(Html.fromHtml(c.title));
vItem.post_count.setText(c.post_count + "");
Picasso.with(ctx).load(imageUri).into(vItem.imageView);
vItem.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();
}
}
This is my FragmentCategory.java for display data
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 GridLayoutManager(getActivity(),3));
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);
}
});
}
And this is my ModeCategory.java
public class Category implements Serializable {
public int id = -1;
public String slug = "";
public String type = "";
public String url = "";
public String title = "";
public String title_plain = "";
public String content = "";
public String excerpt = "";
public String date = "";
public String modified = "";
public String description = "";
public int parent = -1;
public int post_count = -1;
public Author author;
public List<Category> categories = new ArrayList<>();
public List<Comment> comments = new ArrayList<>();
public List<Attachment> attachments = new ArrayList<>();
public CategoryRealm getObjectRealm(){
CategoryRealm c = new CategoryRealm();
c.id = id;
c.url = url;
c.slug = slug;
c.title = title;
c.description = description;
c.parent = parent;
c.post_count = post_count;
return c;
}
}

Categories

Resources