I have a fragment that is suppose to display the results of my alert dialog in my RecyclerView. Every time I click the "ADD" in my dialog, it adds duplicated results to my RecyclerView. I've searched and searched but cannot seem to find what I am doing wrong. I've tried adding .clear(); but if I add that, nothing shows up in my RecyclerView at all. I've added in my adapter getItemId and getItemViewType to return position; but the items still get duplicated. I've added adapter.setData(model) followed by adapter.notifyDataSetChange(); and my RecyclerView still shows duplicated items. The app runs so I have no logcat to post. Thank you.
Model
public class SubjectsModel
{
//private long id;
private String mTitle;
private String mTeacher;
public String getmTitle()
{
return mTitle;
}
public void setmTitle(String title)
{
this.mTitle = title;
}
public String getmTeacher()
{
return mTeacher;
}
public void setmTeacher(String teacher)
{
this.mTeacher = teacher;
}
}
Fragment
public class SubjectsFrag extends DialogFragment implements
SubjectsEditor.OnAddSubjectListener
{
private static final String TAG = SubjectsFrag.class.getSimpleName();
#NonNull
Context context;
private EditText titleView, teacherView;
private String sTitle, sTeacher;
public EmptyRecyclerView recyclerView;
public RecyclerView.LayoutManager layoutManager;
public RecyclerSubAdapter recyclerSubAdapter;
public ArrayList<SubjectsModel> subMod = new ArrayList<>();
DbHelper helper;
#BindView(R.id.main_root)
ViewGroup root;
public SubjectsFrag() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_subjects, container, false);
FloatingActionButton fab = view.findViewById(R.id.fab_sub);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showDialog();
}
});
helper = new DbHelper(getActivity());
helper.getSubject();
titleView = view.findViewById(R.id.edit_subject);
teacherView = view.findViewById(R.id.edit_subject_teacher);
View emptyView = view.findViewById(R.id.empty_subject_view);
recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerSubAdapter = new RecyclerSubAdapter(getContext(), subMod);
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(recyclerSubAdapter);
return view;
}
#Override
public void OnAddSubjectSubmit(String title, String teacher)
{
SubjectsModel model = new SubjectsModel();
model.setmTitle(title);
model.setmTeacher(teacher);
//subMod.clear();
subMod.add(model);
recyclerSubAdapter.setData(subMod);
recyclerSubAdapter.notifyDataSetChanged();
}
private void showDialog()
{
SubjectsEditor addSubjectDialog = new SubjectsEditor();
addSubjectDialog.setTargetFragment(this, 0);
addSubjectDialog.show(getFragmentManager(), null);
}
}
Adapter
public class RecyclerSubAdapter extends RecyclerView.Adapter<RecyclerSubAdapter.ViewHolder>
{
private static final String TAG = RecyclerSubAdapter.class.getSimpleName();
public List<SubjectsModel> subMod = new ArrayList<>();
private OnItemClicked onClick;
static ClickListener clickListener;
Context context;
DbHelper helper;
public RecyclerSubAdapter(Context context, ArrayList<SubjectsModel> subMod)
{
this.context = context;
this.subMod = subMod;
this.helper = new DbHelper(context);
}
#NonNull
#Override
public RecyclerSubAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.subjects_item_list, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(final RecyclerSubAdapter.ViewHolder holder, final int position)
{
SubjectsModel currentSubject = subMod.get(position);
holder.titleView.setText(currentSubject.getmTitle());
holder.teacher.setText(currentSubject.getmTeacher());
//helper.addClass(subMod.get(position));
}
public class ViewHolder extends RecyclerView.ViewHolder implements
View.OnClickListener
{
TextView titleView;
TextView teacher;
CardView cardView;
public ViewHolder(View itemView)
{
super(itemView);
titleView = itemView.findViewById(R.id.subject_subject);
teacher = itemView.findViewById(R.id.subject_teacher_text);
cardView = itemView.findViewById(R.id.card_view);
}
#Override
public void onClick(View view)
{
if (clickListener != null)
{
}
}
}
#Override
public int getItemCount()
{
if (subMod == null)
{
Log.d(TAG, "sub is null");
}
return subMod.size();
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public int getItemViewType(int position)
{
return position;
}
public interface OnItemClicked
{
void onItemClick(int position);
}
public void setOnClick(OnItemClicked onClick)
{
this.onClick = onClick;
}
public void setClickListener(ClickListener clicked)
{
RecyclerSubAdapter.clickListener = clicked;
}
public interface ClickListener
{
void itemClicked(SubjectsModel model, int position);
}
public void setData(ArrayList<SubjectsModel> data)
{
this.subMod = data;
//this.subMod.clear();
this.subMod.addAll(data);
notifyDataSetChanged();
}
}
XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/main_root">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.example.ashleighwilson.schoolscheduler.adapter.EmptyRecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="60dp"/>
</LinearLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true">
<TextView
android:id="#+id/empty_subject_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:visibility="gone"
android:text="#string/no_subjects"/>
</RelativeLayout>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab_sub"
style="#style/FAB" />
</RelativeLayout>
In OnAddSubjectSubmit() you call subMod.add(model);
and then you call recyclerSubAdapter.setData(subMod); which in turn calls this.subMod.addAll(data);.
Check it yourself. I believe it's there where you add the new item twice.
Suggestion: comment out recyclerSubAdapter.setData(subMod); from OnAddSubjectSubmit().
this.subMod = data;
this.subMod.addAll(data);
You initilize subMod by assigning data to it, and later you add data again:
this.subMod.addAll(data);
Related
In below image, when user clicks on the item of recyclerview, "ADDED TO WORDS"
ADDED TO WORDS
But after closing and opening the App again, it changes back to "ADD TO WORDS"
ADD TO WORDS
I want to keep this same when user reopens the app.
TodayFragment.java
public class TodayFragment extends Fragment {
private RecyclerView wordRecyclerView;
private DbHelper dbHelper;
private SQLiteDatabase mDatabase;
private Context mContext;
WordAdapter mWordAdapter;
private static final String LOG_TAG = "TodayFragment";
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dbHelper = new DbHelper(mContext);
mDatabase = dbHelper.getWritableDatabase();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
Log.d(LOG_TAG,"onAttach");
mContext = context;
}
#Override
public void onDetach() {
super.onDetach();
Log.d(LOG_TAG,"onDetach");
mContext = null;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_today,container,false);
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
wordRecyclerView = view.findViewById(R.id.word_recycler_view);
// wordRecyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
wordRecyclerView.setLayoutManager(linearLayoutManager);
String query = "select * from wordhistory;";
Cursor c = mDatabase.rawQuery(query, new String[] {});
Log.d(LOG_TAG,"cursor count, "+c.getCount());
Log.d(LOG_TAG,"onViewCreated set recycler view");
mWordAdapter = new WordAdapter(mContext);
wordRecyclerView.setAdapter(mWordAdapter);
mWordAdapter.swapCursor(c);
mWordAdapter.notifyDataSetChanged();
}
}
fragment_today.xml
<androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
tools:context=".fragment.TodayFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:id="#+id/word_recycler_view" />
</LinearLayout>
</androidx.core.widget.NestedScrollView>
WordAdapter.java
public class WordAdapter extends BaseCursorAdapter<WordAdapter.WordViewHolder> {
private static final String LOG_TAG = "WordAdapter";
Context mContext;
private OnItemClickListener mListener;
private int touchCount=0;
Cursor mCursor;
public WordAdapter(Context mContext) {
super(null);
this.mContext = mContext;
}
public interface OnItemClickListener{
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener){
mListener = listener;
}
#NonNull
#Override
public WordViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view;
view = layoutInflater.inflate(R.layout.word_card_layout,parent,false);
Log.d(LOG_TAG,"onCreateViewHolder: ");
return new WordViewHolder(view);
}
#Override
public void onBindViewHolder(WordViewHolder holder, Cursor cursor) {
int wordColumnIndex = cursor.getColumnIndex(DictionaryContract.DictionaryEntry.COLUMN_WORD);
int defColumnIndex = cursor.getColumnIndex(DictionaryContract.DictionaryEntry.COLUMN_WORD_DEFINITION);
int audioColumnIndex = cursor.getColumnIndex(DictionaryContract.DictionaryEntry.COLUMN_WORD_AUDIOURL);
int synonymColumnIndex = cursor.getColumnIndex(DictionaryContract.DictionaryEntry.COLUMN_WORD_SYNONYMS);
int antonymColumnIndex = cursor.getColumnIndex(DictionaryContract.DictionaryEntry.COLUMN_WORD_ANTONYMS);
String wordStr = cursor.getString(wordColumnIndex);
String wordDefStr = cursor.getString(defColumnIndex);
String audioStr = cursor.getString(audioColumnIndex);
String synonymStr = cursor.getString(synonymColumnIndex);
String antonymStr = cursor.getString(antonymColumnIndex);
Log.d(LOG_TAG,"onBindViewHolder wordStr: "+wordStr);
Log.d(LOG_TAG,"onBindViewHolder wordDefStr: "+wordDefStr);
holder.wordTextView.setText(wordStr);
holder.defTextView.setText(wordDefStr);
}
/* #Override
public int getItemCount() {
return mCursor.getCount();
}*/
#Override
public void swapCursor(Cursor newCursor) {
super.swapCursor(newCursor);
}
public class WordViewHolder extends RecyclerView.ViewHolder {
TextView wordTextView;
ImageView audioImageView;
TextView defTextView;
TextView wordTrickTextView;
TextView defTrickTextView;
ImageView shareImageView;
ImageView favUnselectImageView;
ImageView favSelectImageView;
TextView addWordTextView;
TextView addedWordTextView;
ImageView tickImageView;
RelativeLayout addWordRelativeLayout;
public WordViewHolder(#NonNull View itemView) {
super(itemView);
Log.d(LOG_TAG,"WordViewHolder itemView: "+itemView);
wordTextView = itemView.findViewById(R.id.wordText);
audioImageView = itemView.findViewById(R.id.wordAudio);
defTextView = itemView.findViewById(R.id.wordDef);
wordTrickTextView = itemView.findViewById(R.id.memorisingTrickWord);
defTrickTextView = itemView.findViewById(R.id.memorisingTrickDef);
shareImageView = itemView.findViewById(R.id.wordShare);
favUnselectImageView = itemView.findViewById(R.id.wordFavUnselect);
favSelectImageView = itemView.findViewById(R.id.wordFavSelect);
addWordTextView = itemView.findViewById(R.id.addWordText);
addedWordTextView = itemView.findViewById(R.id.addedWordText);
tickImageView = itemView.findViewById(R.id.tickImage);
addWordRelativeLayout = itemView.findViewById(R.id.addWordRelativeLayout);
addedWordTextView.setVisibility(View.GONE);
tickImageView.setVisibility(View.GONE);
addWordRelativeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (touchCount==0){
addWordTextView.setVisibility(View.GONE);
addedWordTextView.setVisibility(View.VISIBLE);
tickImageView.setVisibility(View.VISIBLE);
((Animatable) tickImageView.getDrawable()).start();
touchCount=1;
} else{
addWordTextView.setVisibility(View.VISIBLE);
addedWordTextView.setVisibility(View.GONE);
tickImageView.setVisibility(View.GONE);
((Animatable) tickImageView.getDrawable()).stop();
touchCount=0;
}
}
});
}
}
}
User should be able to see those changes they did in any item of recycler view even after reopening the app
When you close an app, the system automatically destroys the activity. Thus when you open it again, the activity is recreated.
You can save data for the activity before the activity is destroyed using savedInstanceState.
You need to override the onSaveInstanceState method in your activity and add to the bundle. Below is an example code:
#Override
public void onSaveInstanceState(Bundle saveInstanceState){
// example, save if text is added
saveInstanceState.putBoolean("Herbivore", true);
super.onSaveInstanceState(saveInstanceState);
}
Then when your activity starts, you can receive the bundle from OnCreate.
#Override
boolean herbivoreAdded;
public void OnCreate(Bundle onSaveInstanceState){
super.OnCreate(saveInstanceState);
// access saved value
herbivoreAdded = saveInstanceState.getBoolean("Herbivore");
}
This question already has answers here:
ReyclerView isn't working
(6 answers)
Closed 4 years ago.
I have been making an app that uses a RecyclerView but its not showing any thing..why contents of the recycler view have not been showing up.my codes are bellow
activity_history.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".HistoryActivity"
android:fitsSystemWindows="true"
android:orientation="vertical"
android:id="#+id/layout">
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/historyRecyclerView"
android:scrollbars="vertical">
</android.support.v7.widget.RecyclerView>
</android.support.v4.widget.NestedScrollView>
HistoryActivity.java
public class HistoryActivity extends AppCompatActivity {
private RecyclerView mHistoryRecyclerView;
private RecyclerView.Adapter mHistoryAdapter;
private RecyclerView.LayoutManager mHistoryLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
Toast.makeText(this, "dddd", Toast.LENGTH_SHORT).show();
mHistoryRecyclerView = (RecyclerView) findViewById(R.id.historyRecyclerView);
mHistoryRecyclerView.setNestedScrollingEnabled(false);
mHistoryRecyclerView.setHasFixedSize(true);
mHistoryLayoutManager = new LinearLayoutManager(HistoryActivity.this);
mHistoryRecyclerView.setLayoutManager(mHistoryLayoutManager);
mHistoryAdapter = new HistoryAdapter(getDataSetHistory(), HistoryActivity.this);
mHistoryRecyclerView.setAdapter(mHistoryAdapter);
HistoryObject obj=new HistoryObject("12345");
resultsHistory.add(obj);
mHistoryAdapter.notifyDataSetChanged();
}
private ArrayList resultsHistory = new ArrayList<HistoryObject>();
private List<HistoryObject> getDataSetHistory() {
return resultsHistory;
}
}
HistoryAdapter.java
public class HistoryAdapter extends RecyclerView.Adapter<HistoryViewHolders> {
private List<HistoryObject> itemList;
private Context context;
public HistoryAdapter(List<HistoryObject> itemList, Context context) {
this.itemList = itemList;
this.context = context;
Toast.makeText(context,itemList.size()+"" , Toast.LENGTH_SHORT).show();
}
#NonNull
#Override
public HistoryViewHolders onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_history, null, false);
HistoryViewHolders rcv = new HistoryViewHolders(layoutView);
return rcv;
}
#Override
public void onBindViewHolder(#NonNull HistoryViewHolders holder, int position) {
holder.rideId.setText(itemList.get(position).getRideId());
Toast.makeText(context, holder.rideId.getText().toString(), Toast.LENGTH_SHORT).show();
}
#Override
public int getItemCount() {
return 0;
}
}
HistoryObject
package com.example.ikramkhan.insta.historyRecyclerView;
public class HistoryObject {
private String rideId;
public HistoryObject(String rideId) {
this.rideId = rideId;
}
public String getRideId() {
return rideId;
}
public void setRideId(String rideId) {
this.rideId = rideId;
}
}
HistoryViewHolders.java
public class HistoryViewHolders extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView rideId;
public HistoryViewHolders(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
rideId = (TextView) itemView.findViewById( R.id.rideId);
}
#Override
public void onClick(View v) {
}
}
You're returning zero for the itemCount, therefore your adapter thinks you don't have any items. Try this in your adapter:
#Override
public int getItemCount() {
return itemList.size();
}
I have one query related to RecyclerView. I want to get clicked items and set it to textview in the same layout then after that set the values to textview, update the adapter.
This is my recyclerview.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:id="#+id/rl_container"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/imageView_flag"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:layout_marginLeft="10dp"
android:src="#drawable/usa" />
<TextView
android:id="#+id/textview_currency_info"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1 USD(United States of America)"
android:layout_centerVertical="true"
android:textColor="#000"
android:layout_toEndOf="#+id/imageView_flag"
android:layout_marginStart="14dp" />
</RelativeLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view_exchange_rate"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/rl_container"/>
</RelativeLayout>
This is my fragment class:
public class ExchangeRatesFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private OnFragmentInteractionListener mListener;
private String mParam1;
private String mParam2;
RetrofitClient retrofitClient;
RestInterface service;
ArrayList<ExchangeRate> exchangeRatesArraylist;
private RecyclerView mRecyclerView;
private ExchangeRateAdapter exchangeRateAdapter;
TextView textview_currency_info;
ImageView imageView_flag;
public ExchangeRatesFragment() {}
public static ExchangeRatesFragment newInstance(String param1, String param2) {
ExchangeRatesFragment fragment = new ExchangeRatesFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_exchange_rates, container, false);
exchangeRatesArraylist = new ArrayList<>();
retrofitClient = new RetrofitClient();
service = retrofitClient.getAPIClient(WebServiceUrls.DOMAIN_MAIN);
textview_currency_info = (TextView) rootView.findViewById(R.id.textview_currency_info);
imageView_flag = (ImageView) rootView.findViewById(R.id.imageView_flag);
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view_exchange_rate);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(layoutManager);
get_exchange_rate("USD");
return rootView;
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
public void get_exchange_rate(String from){
service.exchange_rate(from, new Callback<JsonElement>() {
#Override
public void success(JsonElement jsonElement, Response response) {
//this method call if webservice success
try {
JSONObject jsonObject = new JSONObject(jsonElement.toString());
final JSONArray exchange_rate = jsonObject.getJSONArray("exchange_rate");
for(int i=0; i<exchange_rate.length(); i++){
JSONObject currencyNews = exchange_rate.getJSONObject(i);
String short_name = currencyNews.getString("short_name");
String full_name = currencyNews.getString("full_name");
String flag = currencyNews.getString("flag");
String chang_value =currencyNews.getString("chang_value");
ExchangeRate currencyConverter = new ExchangeRate(short_name, full_name, flag, chang_value);
exchangeRatesArraylist.add(currencyConverter);
}
exchangeRateAdapter = new ExchangeRateAdapter(getContext(), exchangeRatesArraylist);
mRecyclerView.setAdapter(exchangeRateAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void failure(RetrofitError error) {
Toast.makeText(getActivity(),"Please check your internet connection", Toast.LENGTH_LONG ).show();
}
});
}
This is my adapter class:
public class ExchangeRateAdapter extends RecyclerView.Adapter<ExchangeRateAdapter.ViewHolder>{
private ArrayList<ExchangeRate> mArrayList;
private Context context;
private final LayoutInflater mInflater;
public ExchangeRateAdapter(Context context, ArrayList<ExchangeRate> arrayList) {
this.mInflater = LayoutInflater.from(context);
mArrayList = arrayList;
context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.exchange_rate_items, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int i) {
holder.relativeLayout.setOnClickListener(clickListener);
holder.textView_full_name.setTag(holder);
holder.textView_short_name.setText(mArrayList.get(i).getShort_name());
holder.textView_full_name.setText(mArrayList.get(i).getFull_name());
holder.textview_currency_value.setText(mArrayList.get(i).getChang_value());
Picasso.with(context).load("http://uploads/country_flag/"+ mArrayList.get(i).getFlag()).into(holder.imageView_flag);
}
private View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
ViewHolder holder = (ViewHolder) view.getTag();
int position = holder.getPosition();
ExchangeRate person = mArrayList.get(position);
String businessids = person.getFull_name();
Intent intent = new Intent(context, test.class);
intent.putExtra("businessids", businessids);
context.startActivity(intent);
}
};
#Override
public int getItemCount() {
return mArrayList.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
private TextView textView_short_name, textView_full_name, textview_currency_value;
private ImageView imageView_flag;
RelativeLayout relativeLayout;
ViewHolder(View itemView) {
super(itemView);
textView_short_name = (TextView)itemView.findViewById(R.id.textView_short_name);
textView_full_name = (TextView)itemView.findViewById(R.id.textView_full_name);
imageView_flag = (ImageView) itemView.findViewById(R.id.imageView_flag);
textview_currency_value = (TextView)itemView.findViewById(R.id.textview_currency_value);
relativeLayout = (RelativeLayout) itemView.findViewById(R.id.rl);
}
}
}
I have tried many options which published on SO but I didn't any solution. How to solve this query? When I set the onclicklistener to ViewHolder so I'm getting the position values only -1 on every item clicklistener.
A few things:
You are setting a tag on "holder.textView_full_name.setTag(holder)" while you are getting the tag from the view which was clicked (which would be the relative layout, as that is where you set the click listener (holder.relativeLayout.setOnClickListener(clickListener);)
This isn't necessary anyways.
In your click listener, call 'getAdapterPosition()', which should return what you are expecting.
Edit: Codepath has a nice overview of the RecyclerView, a little dated, but still relevant.
You can use this dependencies
implementation 'io.reactivex:rxjava:1.2.1'
implementation 'io.reactivex:rxandroid:1.2.1'
Just for example:
Reference
as with this you can click on RecyclerView
adapter.busNoItemClick().doOnNext(this::getBusNum).subscribe();
private void getBusNum(String busNo){
((TextView)findViewById(R.id.txtBusNumberStudent)).setText(busNo);
}
in adapter you have to write this:
#Override
public void onBindViewHolder(AdapterBusRouteParent.ViewHolder holder, int position) {
holder.busNumber.setOnClickListener(view -> publishSubject.onNext(busRouteParents.get(position)));
}
public Observable<String>busNoItemClick(){
return publishSubject.observeOn(AndroidSchedulers.mainThread());
}
Hope this might help you.
One way would be to have a
Variable which stores the selected item,
Set OnClickistener to the ItemView,
In the OnClickListener, set the SELECTED_INDEX as getAdapterPosition() and notify the adapter.
In the onBindViewHolder method, check if current position is equal to SELECTED_INDEX and implement the required steps.
:
int SELECTED_INDEX = 0;
public void setSelectedItemIndex(int position){
SELECTED_INDEX = position;
/*if(adapterCallback!=null) { //If you have a callback interface
adapterCallback.onItemClick(position);
}*/
notifyDataSetChanged();
}
Holder Class:
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
//Item Declarations
public MyViewHolder(View itemView) {
super(itemView);
//View Binding
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v){
if(v==itemView){
setSelectedItemIndex(getAdapterPosition());
}
}
}
In onBindViewHolder method:
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
if(position==SELECTED_INDEX){
//Implement your steps
}
else{
//Default Value
}
}
Hope it helps!
I need to make a ecommerce app type screen with multiple viewpager and recycler views.
I implemented it but my 1 out of 2 view pager is visible in recycler view and once I rotate the device, my first view pager also disappear.
My Activity:
public class MainActivity extends AppCompatActivity {
private List<ProductEntity> productEntities = new ArrayList<>();
private RecyclerView productlist;
private HomeAdapter homeAdapter;
private RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
productlist = (RecyclerView)findViewById(R.id.mainlist);
//productlist.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
productlist.setLayoutManager(mLayoutManager);
homeAdapter = new HomeAdapter(this,getSupportFragmentManager(),productEntities);
productlist.setAdapter(homeAdapter);
new ParserJsonTask().execute();
}
public String loadJSONFromAsset() {
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(getAssets().open(
"f_two.json")));
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close(); // stop reading
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
private class ParserJsonTask extends AsyncTask<Void, Integer, List<ProductEntity>> {
#Override
protected List<ProductEntity> doInBackground(Void... params) {
try{
return JsonParser.getInstance().parseJson(loadJSONFromAsset());
}catch(Exception e){
Log.d("Exception", e.toString());
}
return null;
}
#Override
protected void onPostExecute(List<ProductEntity> result) {
Log.e("Length",""+result.size());
if(result != null) {
productEntities = result;
homeAdapter.setProduct(productEntities);
}
}
}
My view pager Fragment:
public class ImageFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_IMAGE_URL = "image_url";
private Context context;
private String image_url;
public ImageFragment() {
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.context = context;
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static ImageFragment newInstance(String image) {
ImageFragment fragment = new ImageFragment();
Bundle args = new Bundle();
args.putString(ARG_IMAGE_URL, image);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
image_url = getArguments().getString(ARG_IMAGE_URL);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_image, container, false);
ImageView image = (ImageView) rootView.findViewById(R.id.image);
Log.e("Pager Item Image",""+image_url);
if(!TextUtils.isEmpty(image_url))
Picasso.with(context).load(image_url).into(image);
return rootView;
}
}
My Main adapter for recycler view:
public class HomeAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<ProductEntity> productEntities;
private Context context;
private FragmentManager fragmentManager;
private OnItemClickListener mItemClickListener;
private static final int TYPE_FIRST = 0;
private static final int TYPE_SECOND = 1;
private static final int TYPE_THIRD = 2;
private static final String TEMPLATE_FIRST ="product-template-1";
private static final String TEMPLATE_SECOND ="product-template-2";
private static final String TEMPLATE_THIRD ="product-template-3";
public HomeAdapter(Context context , FragmentManager fragmentManager ,List<ProductEntity> productEntities) {
this.productEntities = productEntities;
this.context = context;
this.fragmentManager = fragmentManager;
}
#Override
public int getItemCount() {
Log.e("Item count",""+productEntities.size());
return productEntities.size();
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if(holder instanceof ImageViewHolder) {
ImageViewHolder imageViewHolder = (ImageViewHolder) holder;
ProductEntity productEntity = productEntities.get(position);
Log.e("Template Item Image",""+productEntity.getItemEntities().get(0).getImage());
Picasso.with(context).load(productEntity.getItemEntities().get(0).getImage()).into(imageViewHolder.imageView);
} else if(holder instanceof PagerViewHolder) {
PagerViewHolder pagerViewHolder = (PagerViewHolder) holder;
ProductEntity productEntity = productEntities.get(position);
pagerViewHolder.viewPager.setAdapter(new PagerAdapter(fragmentManager,productEntity.getItemEntities()));
} else if (holder instanceof HorizontalViewHolder) {
HorizontalViewHolder horizontalViewHolder = (HorizontalViewHolder) holder;
ProductEntity productEntity = productEntities.get(position);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
horizontalViewHolder.recyclerView.setLayoutManager(linearLayoutManager);
horizontalViewHolder.recyclerView.setAdapter(new SliderAdapter(context,productEntity.getItemEntities()));
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder (ViewGroup parent, int viewType) {
if(viewType == TYPE_FIRST) {
View v = LayoutInflater.from (parent.getContext ()).inflate (R.layout.content_image, parent, false);
return new ImageViewHolder (v);
} else if(viewType == TYPE_SECOND) {
View v = LayoutInflater.from (parent.getContext ()).inflate (R.layout.content_horizontal, parent, false);
return new HorizontalViewHolder (v);
} else {
View v = LayoutInflater.from (parent.getContext ()).inflate (R.layout.content_pager, parent, false);
return new PagerViewHolder(v);
}
}
#Override
public int getItemViewType (int position) {
if(productEntities.get(position).getTemplate().equalsIgnoreCase(TEMPLATE_FIRST)) {
Log.e("Item type",""+TYPE_FIRST);
return TYPE_FIRST;
} else if(productEntities.get(position).getTemplate().equalsIgnoreCase(TEMPLATE_SECOND)) {
Log.e("Item type",""+TYPE_SECOND);
return TYPE_SECOND;
} else {
Log.e("Item type",""+TYPE_THIRD);
return TYPE_THIRD;
}
}
class PagerViewHolder extends RecyclerView.ViewHolder {
protected ViewPager viewPager;
public PagerViewHolder (View itemView) {
super (itemView);
this.viewPager = (ViewPager) itemView.findViewById (R.id.viewpager);
}
}
class ImageViewHolder extends RecyclerView.ViewHolder {
protected ImageView imageView;
public ImageViewHolder (View itemView) {
super (itemView);
this.imageView = (ImageView) itemView.findViewById (R.id.image);
}
}
public class HorizontalViewHolder extends RecyclerView.ViewHolder {
protected RecyclerView recyclerView;
public HorizontalViewHolder(View v) {
super(v);
recyclerView = (RecyclerView)v.findViewById(R.id.horizontallist);
}
}
public void setProduct(List<ProductEntity> data) {
productEntities.clear();
productEntities.addAll(data);
notifyDataSetChanged();
}
public interface OnItemClickListener {
void onItemClick(View view, int position);
}
public void SetOnItemClickListener(final OnItemClickListener mItemClickListener) {
this.mItemClickListener = mItemClickListener;
}
}
My view pager adapter:
public class PagerAdapter extends FragmentPagerAdapter {
private List<ItemEntity> itemEntities;
public PagerAdapter(FragmentManager fm, List<ItemEntity> itemEntities) {
super(fm);
this.itemEntities = itemEntities;
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return ImageFragment.newInstance(itemEntities.get(position).getImage());
}
#Override
public int getCount() {
// Show 3 total pages.
return itemEntities.size();
}
}
My horizontal recyclerview adapter:
public class SliderAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<ItemEntity> itemEntities;
private Context context;
private OnItemClickListener mItemClickListener;
public SliderAdapter(Context context , List<ItemEntity> notesEntities) {
this.itemEntities = notesEntities;
this.context = context;
}
#Override
public int getItemCount() {
return itemEntities.size();
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
ItemViewHolder itemViewHolder = (ItemViewHolder) holder;
ItemEntity itemEntity = itemEntities.get(position);
itemViewHolder.productName.setText(itemEntity.getLabel());
Log.e("Item Image",""+itemEntity.getImage());
if(!TextUtils.isEmpty(itemEntity.getImage()))
Picasso.with(context).load(itemEntity.getImage()).into(itemViewHolder.productImage);
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder (ViewGroup parent, int viewType) {
View v = LayoutInflater.from (parent.getContext ()).inflate (R.layout.recycler_card_layout, parent, false);
return new ItemViewHolder (v);
}
public class ItemViewHolder extends RecyclerView.ViewHolder {
protected TextView productName;
protected ImageView productImage;
public ItemViewHolder(View v) {
super(v);
productName = (TextView) v.findViewById(R.id.product_name);
productImage = (ImageView) v.findViewById(R.id.product_image);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mItemClickListener != null)
mItemClickListener.onItemClick(v, getAdapterPosition());
}
});
}
}
public void setItems(List<ItemEntity> data) {
itemEntities.clear();
itemEntities.addAll(data);
notifyDataSetChanged();
}
public interface OnItemClickListener {
void onItemClick(View view, int position);
}
public void SetOnItemClickListener(final OnItemClickListener mItemClickListener) {
this.mItemClickListener = mItemClickListener;
}
}
Main activity layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".activity.MainActivity"
tools:showIn="#layout/activity_main">
<android.support.v7.widget.RecyclerView
android:id="#+id/mainlist"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
Horizontal scrolling layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".activity.MainActivity"
tools:showIn="#layout/activity_main">
<android.support.v7.widget.RecyclerView
android:id="#+id/horizontallist"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
View pager layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="200dp">
</android.support.v4.view.ViewPager>
</RelativeLayout>
As per my JSON data, it should have 2 view pager inside recycler view and but it is showing only 1 in portrait mode and once I rotate the device, both are disappear. I thing data is not visible inside recycler view as I can see white space in recycler view while scrolling.
Any help would be appreciated.
Simple change :
extends FragmentPagerAdapter
to
extends FragmentStatePagerAdapter
i'm searching function that programmatically click method. so i found some method. 'performClick()'
like that :
recyclerView.findViewHolderForAdapterPosition(position).itemView.performClick();
but it dosen't work in my case. I can't find solution. How do i use the performClick in Activity???
my Adapter - ViewHolder:
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView virtNo;
private TextView score01;
private TextView score02;
private TextView score03;
private TextView totalScore;
private LinearLayout linearLayout;
public ViewHolder(View itemView) {
super(itemView);
this.virtNo = (TextView) itemView.findViewById(R.id.tv_virtNo);
this.score01 = (TextView) itemView.findViewById(R.id.tv_score01);
this.score02 = (TextView) itemView.findViewById(R.id.tv_score02);
this.score03 = (TextView) itemView.findViewById(R.id.tv_score03);
this.totalScore = (TextView) itemView.findViewById(R.id.tv_totalScore);
this.linearLayout = (LinearLayout) itemView.findViewById(R.id.ll_item_score);
virtNo.setOnClickListener(this);
score01.setOnClickListener(this);
score02.setOnClickListener(this);
score03.setOnClickListener(this);
score10.setOnClickListener(this);
}
#Override
public void onClick(View v) {
onClickListener.onClick(v, getAdapterPosition(), items.get(getAdapterPosition()));
}
}
public void setOnClickListener(OnClickListener<Score> onClickListener) {
this.onClickListener = onClickListener;
}
public interface OnClickListener<T> {
void onClick(View v, int position, T item);
}
my Adapter - onBindViewHolder
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Score item = items.get(position);
holder.virtNo.setText(item.virtNo);
holder.score01.setText(item.score01);
holder.score02.setText(item.score02);
holder.score03.setText(item.score03);
holder.totalScore.setText(itemSum(item));
}
}
I have tried to keep things easy to understand here, it is a complete example for listening to click event on individual items in RecyclerView, there are other ways to do it as well. This code works, You may modify it as it fits you, in case you have any question write them in comments. code is also available at GitHub
public class RecyclerViewOneActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recycler_view_one);
initializeUI();
}
private void initializeUI() {
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.RecyclerViewOneActivity_RecyclerView);
RecyclerView.LayoutManager linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
ArrayList<String> strings = new ArrayList<>();
strings.add("first");
strings.add("second");
MyAdapter adapter = new MyAdapter(getApplicationContext(), strings);
recyclerView.setAdapter(adapter);
}
private class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private Context context;
private ArrayList<String> strings;
private LayoutInflater layoutInflater;
public MyAdapter(Context context, ArrayList<String> strings) {
this.context = context;
this.strings = strings;
layoutInflater = LayoutInflater.from(this.context);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = layoutInflater.inflate(R.layout.single_item_recycler_view_one, parent, false);
MyViewHolder myViewHolder = new MyViewHolder(view);
return myViewHolder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
final String text = this.strings.get(position);
holder.textView.setText("" + text);
holder.linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, ""+text, Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return strings.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
private LinearLayout linearLayout;
private TextView textView;
public MyViewHolder(View itemView) {
super(itemView);
linearLayout = (LinearLayout) itemView.findViewById(R.id.single_item_recycler_view_one_linear_layout);
textView = (TextView) itemView.findViewById(R.id.single_item_recycler_view_one_textView);
}
}
}
}
single_item_recycler_view_one.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:id="#+id/single_item_recycler_view_one_linear_layout"
android:orientation="vertical">
<TextView
android:id="#+id/single_item_recycler_view_one_textView"
android:layout_width="match_parent"
android:textColor="#000"
android:layout_height="wrap_content"
android:text="Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>