I get this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setLayoutManager(android.support.v7.widget.RecyclerView$LayoutManager)' on a null object reference
Here is the RecyclerFragment:
public class ThreeFragment extends Fragment{
private TextView tvEmptyView;
private RecyclerView mRecyclerView;
private DataAdapter mAdapter;
private LinearLayoutManager mLayoutManager;
private List<Student> studentList;
protected Handler handler;
public ThreeFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.fragment_one, container, false);
tvEmptyView = (TextView) rootview.findViewById(R.id.empty_view);
mRecyclerView = (RecyclerView) rootview.findViewById(R.id.my_recycler_view);
studentList = new ArrayList<Student>();
handler = new Handler();
loadData();
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getActivity());
mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
// use a linear layout manager
mRecyclerView.setLayoutManager(mLayoutManager);
// create an Object for Adapter
mAdapter = new DataAdapter(studentList, mRecyclerView);
// set the adapter object to the Recyclerview
mRecyclerView.setAdapter(mAdapter);
// mAdapter.notifyDataSetChanged();
if (studentList.isEmpty()) {
mRecyclerView.setVisibility(View.GONE);
tvEmptyView.setVisibility(View.VISIBLE);
} else {
mRecyclerView.setVisibility(View.VISIBLE);
tvEmptyView.setVisibility(View.GONE);
}
mAdapter.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
//add null , so the adapter will check view_type and show progress bar at bottom
studentList.add(null);
mAdapter.notifyItemInserted(studentList.size() - 1);
handler.postDelayed(new Runnable() {
#Override
public void run() {
// remove progress item
studentList.remove(studentList.size() - 1);
mAdapter.notifyItemRemoved(studentList.size());
//add items one by one
int start = studentList.size();
int end = start + 20;
for (int i = start + 1; i <= end; i++) {
studentList.add(new Student("Student " + i, "AndroidStudent" + i + "#gmail.com"));
mAdapter.notifyItemInserted(studentList.size());
}
mAdapter.setLoaded();
//or you can add all at once but do not forget to call mAdapter.notifyDataSetChanged();
}
}, 2000);
}
});
return rootview;
}
// load initial data
private void loadData() {
for (int i = 1; i <= 20; i++) {
studentList.add(new Student("Student " + i, "androidstudent" + i + "#gmail.com"));
}
}
}
Here is the adapter:
public class DataAdapter extends RecyclerView.Adapter {
private final int VIEW_ITEM = 1;
private final int VIEW_PROG = 0;
private List<Student> studentList;
// The minimum amount of items to have below your current scroll position
// before loading more.
private int visibleThreshold = 5;
private int lastVisibleItem, totalItemCount;
private boolean loading;
private OnLoadMoreListener onLoadMoreListener;
public DataAdapter(List<Student> students, RecyclerView recyclerView) {
studentList = students;
if (recyclerView.getLayoutManager() instanceof LinearLayoutManager) {
final LinearLayoutManager mLayoutManager = (LinearLayoutManager) recyclerView
.getLayoutManager();
recyclerView
.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView,
int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
totalItemCount = mLayoutManager.getItemCount();
lastVisibleItem = mLayoutManager
.findLastVisibleItemPosition();
if (!loading
&& totalItemCount <= (lastVisibleItem + visibleThreshold)) {
// End has been reached
// Do something
if (onLoadMoreListener != null) {
onLoadMoreListener.onLoadMore();
}
loading = true;
}
}
});
}
}
#Override
public int getItemViewType(int position) {
return studentList.get(position) != null ? VIEW_ITEM : VIEW_PROG;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
RecyclerView.ViewHolder vh;
if (viewType == VIEW_ITEM) {
View v = LayoutInflater.from(parent.getContext()).inflate(
R.layout.list_row, parent, false);
vh = new StudentViewHolder(v);
} else {
View v = LayoutInflater.from(parent.getContext()).inflate(
R.layout.progress_item, parent, false);
vh = new ProgressViewHolder(v);
}
return vh;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof StudentViewHolder) {
Student singleStudent = (Student) studentList.get(position);
((StudentViewHolder) holder).tvName.setText(singleStudent.getName());
((StudentViewHolder) holder).tvEmailId.setText(singleStudent.getEmailId());
((StudentViewHolder) holder).student = singleStudent;
} else {
((ProgressViewHolder) holder).progressBar.setIndeterminate(true);
}
}
public void setLoaded() {
loading = false;
}
#Override
public int getItemCount() {
return studentList.size();
}
public void setOnLoadMoreListener(OnLoadMoreListener onLoadMoreListener) {
this.onLoadMoreListener = onLoadMoreListener;
}
//
public static class StudentViewHolder extends RecyclerView.ViewHolder {
public TextView tvName;
public TextView tvEmailId;
public Student student;
public StudentViewHolder(View v) {
super(v);
tvName = (TextView) v.findViewById(R.id.tvName);
tvEmailId = (TextView) v.findViewById(R.id.tvEmailId);
v.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(),
"OnClick :" + student.getName() + " \n " + student.getEmailId(),
Toast.LENGTH_SHORT).show();
}
});
}
}
public static class ProgressViewHolder extends RecyclerView.ViewHolder {
public ProgressBar progressBar;
public ProgressViewHolder(View v) {
super(v);
progressBar = (ProgressBar) v.findViewById(R.id.progressBar1);
}
}
}
Related
I have an issue with Recyclerview item selection , which is set up in a fragment , the problem is each page which is created by ViewVager has its own instance of the Recyclerview so the output is that selecting Recyclerview items will reset the scroll state of the Recyclerview, so I'm looking for a solution to to save scroll state of a Recyclerview when an item is clicked.
Fragment onViewCreated
// setting RecyclerView
mEpisodesList = (CustomRecyclerView) view.findViewById(R.id.episodesLIST);
// getting episodeslist
ArrayList<PlanetModel> episodeslist = new ArrayList<>();
for (TvShowEpisode e : mEpisodes) {
episodeslist.add(new PlanetModel(e.mEpisode));
}
// Setting LinearLayoutManager
LinearLayoutManager layoutManager
= new LinearLayoutManager(mContext.getApplicationContext(), LinearLayoutManager.HORIZONTAL, false);
//mEpisodesList.setLayoutManager(new LinearLayoutManager(mContext));
mEpisodesList.setLayoutManager(layoutManager);
// Setting RecyclerView Adapter
int currentPosition = getArguments().getInt("position");
planetAdapter = new PlanetAdapter(episodeslist, currentPosition, new PlanetAdapter.OnItemClickListener() {
#Override
public void onItemClick(final int pos) {
int scrollValue = mEpisodesList.getHorizontalScrollOffset();
mCallback.sendText(pos, scrollValue);
}
});
mEpisodesList.setAdapter(planetAdapter);
int scrollValue = getArguments().getInt("scrollValue");
new Handler().postDelayed(() -> mEpisodesList.scrollBy(scrollValue, 0), 100);
activity
public class TvShowEpisodeDetails extends MizActivity implements TvShowEpisodeDetailsFragment.TextClicked {
#Override
protected int getLayoutResource() {
return R.layout.viewpager_with_toolbar_overlay;
}
#Override
public void onCreate(Bundle savedInstanceState) {
mBus = MizuuApplication.getBus();
super.onCreate(savedInstanceState);
// Set theme
setTheme(R.style.Mizuu_Theme_NoBackground);
ViewUtils.setupWindowFlagsForStatusbarOverlay(getWindow(), true);
ViewUtils.setProperToolbarSize(this, mToolbar);
mShowId = getIntent().getExtras().getString(SHOW_ID);
mSeason = getIntent().getExtras().getInt("season");
mEpisode = getIntent().getExtras().getInt("episode");
mDatabaseHelper = MizuuApplication.getTvEpisodeDbAdapter();
Cursor cursor = mDatabaseHelper.getEpisodes(mShowId);
try {
while (cursor.moveToNext()) {
mEpisodes.add(new TvShowEpisode(this, mShowId,
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_TITLE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_PLOT)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SEASON)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_AIRDATE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_DIRECTOR)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_WRITER)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_GUESTSTARS)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_RATING)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_HAS_WATCHED)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_FAVOURITE))
));
}
} catch (Exception e) {
} finally {
cursor.close();
}
final ArrayList<PlanetModel> episodeslist = new ArrayList<>();
for (TvShowEpisode e : mEpisodes) {
episodeslist.add(new PlanetModel(e.mEpisode));
}
mShowTitle = MizuuApplication.getTvDbAdapter().getShowTitle(mShowId);
setTitle(mShowTitle);
mViewPager = (ViewPager) findViewById(R.id.awesomepager);
mViewPager.setAdapter(new TvShowEpisodeDetailsAdapter(getSupportFragmentManager()));
for (int i = 0; i < mEpisodes.size(); i++)
fragments.add(TvShowEpisodeDetailsFragment
.newInstance(mShowId, Integer.parseInt(mEpisodes.get(i).getSeason()), Integer.parseInt(mEpisodes.get(i).getEpisode()), i, mScrollValue));
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
for (int i = 0; i < episodeslist.size(); i++) {
episodeslist.get(i).setPlanetSelected(false);
}
episodeslist.get(position).setPlanetSelected(true);
//notify your recycler views adaper
ViewUtils.updateToolbarBackground(TvShowEpisodeDetails.this, mToolbar, 0, mEpisodes.get(position).getTitle(), Color.TRANSPARENT);
}
});
if (savedInstanceState != null) {
mViewPager.setCurrentItem(savedInstanceState.getInt("tab", 0));
} else {
for (int i = 0; i < mEpisodes.size(); i++) {
if (mEpisodes.get(i).getSeason().equals(MizLib.addIndexZero(mSeason)) && mEpisodes.get(i).getEpisode().equals(MizLib.addIndexZero(mEpisode))) {
mViewPager.setCurrentItem(i);
SharedPreferences setPref = this.getSharedPreferences("TvShowEpisodeDetails", Context.MODE_PRIVATE);
setPref.edit().putInt("i", i).apply();
break;
}
}
}
}
private class TvShowEpisodeDetailsAdapter extends FragmentPagerAdapter {
public TvShowEpisodeDetailsAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
// return TvShowEpisodeDetailsFragment.newInstance(mShowId, Integer.parseInt(mEpisodes.get(index).getSeason()), Integer.parseInt(mEpisodes.get(index).getEpisode()));
return fragments.get(index);
}
#Override
public int getCount() {
return mEpisodes.size();
}
}
Recyclerview adapter
public class PlanetAdapter extends RecyclerView.Adapter<PlanetAdapter.PlanetViewHolder> {
public interface OnItemClickListener {
void onItemClick(int item);
}
private final ArrayList<PlanetModel> episodeslist;
private final OnItemClickListener listener;
SharedPreferences getPref = getContext().getSharedPreferences("TvShowEpisodeDetails", Context.MODE_PRIVATE);
int pos = getPref.getInt("i", 0);
int isPlanetSelected = pos;
private final int highlightedPos;
public PlanetAdapter(ArrayList<PlanetModel> episodeslist, int highlightedPosition, OnItemClickListener listener) {
this.episodeslist = episodeslist;
this.listener = listener;
this.highlightedPos = highlightedPosition;
}
#NonNull
#Override
public PlanetAdapter.PlanetViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.planet_row, parent, false);
return new PlanetViewHolder(v);
}
#Override
public void onBindViewHolder(PlanetAdapter.PlanetViewHolder vh, final int position) {
TextView tv = (TextView) vh.itemView;
PlanetModel planetModel = episodeslist.get(position);
tv.setText(planetModel.getPlanetName());
tv.setCompoundDrawablesWithIntrinsicBounds(R.drawable.bg, 0, 0, 0);
if (highlightedPos == position) {
vh.itemView.setBackgroundColor(getContext().getResources().getColor(R.color.colorPrimaryLight));
} else {
vh.itemView.setBackgroundColor(getContext().getResources().getColor(R.color.colorPrimaryDark));
}
//holder.image.setImageResource(R.drawable.planetimage);
//vh.text.setText(episodeslist.get(position).toString());
}
#Override
public int getItemCount() {
return episodeslist.size();
}
public class PlanetViewHolder extends RecyclerView.ViewHolder {
protected TextView text;
public PlanetViewHolder(View itemView) {
super(itemView);
text = (TextView) itemView.findViewById(R.id.text_id);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("LOG_TAG", "onClick: current item: " + highlightedPos);
final int previousItem = isPlanetSelected;
isPlanetSelected = getPosition();
SharedPreferences setPref = v.getContext().getSharedPreferences("PlanetAdapter", Context.MODE_PRIVATE);
setPref.edit().putInt("newPosition", getPosition()).apply();
listener.onItemClick(getPosition());
}
});
}
// public void bind(final PlanetModel item, final OnItemClickListener listener) {
// }
}
You can solve this by tracking the current scroll value of the RecyclerView, and whenever you hit an a ReyclerView item; add a new parameter to the listener callback with this tracked scroll value to update the new fragment that will be shown on the ViewPager.
Track the scroll value:
mEpisodesList.setOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
scrollValue += dx;
}
});
Pass it as interface callback:
planetAdapter = new PlanetAdapter(episodeslist, currentPosition, new PlanetAdapter.OnItemClickListener() {
#Override
public void onItemClick(final int pos) {
mCallback.sendText(pos, scrollValue);
}
});
And update that in the list of ViewPager fragments before scrolling to the new page:
#Override
public void sendText(int position, int scrollValue) {
mScrollValue = scrollValue;
TvShowEpisodeDetailsFragment frag = fragments.get(position);
Bundle arguments = frag.getArguments();
arguments.putInt("scrollValue", scrollValue);
mViewPager.setCurrentItem(position, false);
}
try this
// save
recyclerViewState = binding.mainList.layoutManager?.onSaveInstanceState()
// restore
recyclerViewState?.let {
binding.mainList.layoutManager?.onRestoreInstanceState(it)
}
I down know if made it right. I have a RecyclerView with 2 ViewHolders. ProgramHolder and CountDownTimerHolder. In the CountDownTimerHolder is the time where the countdown starts predifined.
If you click on the Settings Button, I start a new Activity where I set Minutes and Seconds for the Timer.
My question is: Can I pass the data that I get from the Activity to change the predifined starting time in the CountDownTimerHolder?
Sry but I am still a noob at Programming. If there are any questions let me know.
CountDownTimerHolder
public class CountdownTimerHolder extends RecyclerView.ViewHolder {
private static final String TAG = "CountdownTimerHolder";
Context context;
private TextView mTextViewCountdown;
private Button btnStartPauseTimer, btnStopTimer, btnSetTimerSettings;
private CountDownTimer countDownTimer;
private boolean timerRunning;
//THIS ARE THE VARIABLES TO BE UPDATED
public long START_TIME_IN_MILLI_SEC = 1000000;
private long timeLeftInMilliSec = START_TIME_IN_MILLI_SEC;
public CountdownTimerHolder(#NonNull View itemView) {
super(itemView);
Log.d(TAG, "CountdownTimerHolder: IT IS CALLED");
context = itemView.getContext();
mTextViewCountdown = itemView.findViewById(R.id.timer);
btnStartPauseTimer = itemView.findViewById(R.id.playBtn);
btnStopTimer = itemView.findViewById(R.id.stopBtn);
btnSetTimerSettings = itemView.findViewById(R.id.btnSetTimerSettings);
btnStartPauseTimer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (timerRunning) {
pauseTimer();
}else {
startTimer();
}
}
});
btnStopTimer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
resetTimer();
}
});
btnSetTimerSettings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, SettingCountdownTimer.class);
context.startActivity(intent);
}
});
updateCountDownText();
}
private void startTimer() {
countDownTimer = new CountDownTimer(timeLeftInMilliSec, 1000) {
#Override
public void onTick(long millisUntilFinished) {
timeLeftInMilliSec = millisUntilFinished;
updateCountDownText();
}
#Override
public void onFinish() {
timerRunning = false;
btnStartPauseTimer.setBackgroundResource(R.drawable.ic_play_arrow_black_24dp);
}
}.start();
timerRunning = true;
btnStartPauseTimer.setBackgroundResource(R.drawable.ic_pause_black_24dp);
}
private void pauseTimer() {
countDownTimer.cancel();
timerRunning = false;
btnStartPauseTimer.setBackgroundResource(R.drawable.ic_play_arrow_black_24dp);
}
private void resetTimer() {
countDownTimer.cancel();
timeLeftInMilliSec = START_TIME_IN_MILLI_SEC;
updateCountDownText();
btnStartPauseTimer.setBackgroundResource(R.drawable.ic_play_arrow_black_24dp);
}
private void updateCountDownText() {
int minutes = (int) (timeLeftInMilliSec / 1000) /60;
int seconds = (int) (timeLeftInMilliSec /1000) % 60;
String timeLeftFormatted = String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds);
mTextViewCountdown.setText(timeLeftFormatted);
}
}
SettingCountdownTimerActivity
public class SettingCountdownTimer extends AppCompatActivity {
EditText editTextMinutes, editTextSeconds;
Button btnSetTimer;
public long minutesToMillisInput;
public long secondsToMillisInput;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.countdown_timer_settings);
editTextMinutes = findViewById(R.id.editTextMinutes);
editTextSeconds = findViewById(R.id.editTextSeconds);
btnSetTimer = findViewById(R.id.btnSetTimer);
btnSetTimer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String inputMinutes = editTextMinutes.getText().toString();
String inputSeconds = editTextSeconds.getText().toString();
if (inputMinutes.length() == 0 && inputSeconds.length() == 0) {
Toast.makeText(SettingCountdownTimer.this, "Minuten und Sekunden koennen nicht leer sein",
Toast.LENGTH_SHORT).show();
return;
}
minutesToMillisInput = Long.parseLong(inputMinutes) * 60000;
secondsToMillisInput = Long.parseLong(inputSeconds) * 1000;
if (minutesToMillisInput == 0 && secondsToMillisInput == 0) {
Toast.makeText(SettingCountdownTimer.this, "Minuten und Sekunden koennen nicht 0 sein",
Toast.LENGTH_SHORT).show();
return;
}
//HERE I WANT TO PASS THE NEW VARIABLES TO VIEWHOLDER
finish();
}
});
}
}
Adapter
public class PickedExercisesAdapter extends RecyclerView.Adapter {
OnItemClickListener mlistener;
private static final String TAG = "PickedExercisesRecycler started";
private ArrayList<ExerciseModel> mlist;
private static int EXERCISE_CARD_TYPE = 0;
private static int COUNTDOWN_TIMER_TYPE = 1;
public PickedExercisesAdapter(ArrayList<ExerciseModel> list) {
this.mlist = list;
}
#Override
public int getItemViewType(int position) {
if (position % 2 == 0) {
return EXERCISE_CARD_TYPE;
}
return COUNTDOWN_TIMER_TYPE;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view;
if (viewType == EXERCISE_CARD_TYPE) {
view = layoutInflater.inflate(R.layout.exercise_card_view, parent, false);
return new ProgramHolder(view);
} else {
view = layoutInflater.inflate(R.layout.countdown_timer, parent, false);
return new CountdownTimerHolder(view);
}
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
ExerciseModel exerciseModel = null;
if (position % 2 == EXERCISE_CARD_TYPE) {
if (position == 0) {
exerciseModel = mlist.get(0);
} else {
int listposition = position / 2;
exerciseModel = mlist.get(listposition);
}
ProgramHolder programHolder = (ProgramHolder) holder;
Glide.with(programHolder.itemView.getContext())
.load(exerciseModel.getExerciseImage())
.placeholder(R.drawable.ic_launcher_foreground)
.into(programHolder.exerciseImage);
programHolder.exerciseTitle.setText(exerciseModel.getExerciseTitle());
programHolder.exerciseTitle.setText(exerciseModel.getExerciseTitle());
programHolder.exerciseBodyPart.setText(exerciseModel.getExerciseBodyPart());
programHolder.exerciseDifficulty.setText(String.valueOf(exerciseModel.getDifficulty()));
programHolder.exerciseDescription.setText(exerciseModel.getExerciseDescription());
} else {
CountdownTimerHolder countDownTimerHolder = (CountdownTimerHolder) holder;
}
}
#Override
public int getItemCount() {
int listsizedouble = mlist.size() * 2;
return listsizedouble;
}
class ProgramHolder extends RecyclerView.ViewHolder {
OnItemClickListener mlistener;
TextView exerciseTitle, exerciseDifficulty, exerciseBodyPart, exerciseDescription;
ConstraintLayout expandableLayout;
Button arrowBtn;
ImageView exerciseImage;
CardView cardView;
public ProgramHolder(final View itemView) {
super(itemView);
arrowBtn = itemView.findViewById(R.id.arrowBtn);
expandableLayout = itemView.findViewById(R.id.constraintExpendable);
exerciseTitle = itemView.findViewById(R.id.exerciseTitle);
exerciseDifficulty = itemView.findViewById(R.id.exerciseDifficulty);
exerciseBodyPart = itemView.findViewById(R.id.exerciseBodyPart);
exerciseImage = itemView.findViewById(R.id.exerciseImage);
exerciseDescription = itemView.findViewById(R.id.exerciseDescription);
cardView = itemView.findViewById(R.id.cardView);
arrowBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION && mlistener != null) {
mlistener.onItemClick(position);
}
}
});
}
private void setExerciseDetails(ExerciseModel exerciseModel) {
exerciseTitle.setText(exerciseModel.getExerciseTitle());
}
}
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
this.mlistener = listener;
}
}
RecyclerViewFragment
public class PickedExerciseRecyclerViewFragment extends Fragment {
private static final String TAG = "PickedExerciseRecyclerV";
RecyclerView recyclerView;
PickedExercisesAdapter adapter;
RecyclerView.LayoutManager manager;
View view;
private ArrayList<ExerciseModel> list;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.picked_exercise_recycler_view, container, false);
list = getArguments().getParcelableArrayList("exerciseProgram");
recyclerView = view.findViewById(R.id.pickedExerciseRecyclerView);
manager = new LinearLayoutManager(getContext());
adapter = new PickedExercisesAdapter(list);
recyclerView.setLayoutManager(manager);
recyclerView.setHasFixedSize(true);
recyclerView.setAdapter(adapter);
adapter.setOnItemClickListener(new PickedExercisesAdapter.OnItemClickListener() {
#Override
public void onItemClick(int position) {
Log.d(TAG, "onItemClick: clicked " + position);
View view1 = recyclerView.getLayoutManager().findViewByPosition(position);
ConstraintLayout constraintLayout = view1.findViewById(R.id.constraintExpendable);
Button arrowBtn = view1.findViewById(R.id.arrowBtn);
CardView cardView = view1.findViewById(R.id.cardView);
if (constraintLayout.getVisibility() == View.GONE) {
cardView.getMaxCardElevation();
TransitionManager.beginDelayedTransition(cardView, new AutoTransition());
constraintLayout.setVisibility(View.VISIBLE);
arrowBtn.setBackgroundResource(R.drawable.ic_keyboard_arrow_up_black_24dp);
} else {
TransitionManager.beginDelayedTransition(cardView, new AutoTransition());
constraintLayout.setVisibility(View.GONE);
arrowBtn.setBackgroundResource(R.drawable.ic_keyboard_arrow_down_black_24dp);
}
}
});
return view;
}
}
I am creating a movie app using TMDB api, Retrofit, Gson and Glide. I have two recyclerView and two layout to inflate. But I am unable to inflate 2 layout in recyclerView adapter.
I have already implemented popular and upcoming movie list in 2 different recyclerView. But they are showing using 1 single layout. I want to inflate popular movies in one layout and upcoming movies in another layout. I can't set the condition for getItemViewType() method. How can I check for popular and upcoming movies list in getItemViewType() method and implement it on onCreateViewHolder() method of recyclerView.
MovieAdapter class:
public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.MovieViewHolder> {
private Context context;
private ArrayList<Movie> movieArrayList;
public MovieAdapter(Context context, ArrayList<Movie> movieArrayList) {
this.context = context;
this.movieArrayList = movieArrayList;
}
#NonNull
#Override
public MovieViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.movie_list_item, parent, false);
return new MovieViewHolder(view);
}
#Override
public int getItemViewType(int position) {
return super.getItemViewType(position);
}
#Override
// Set values to the list item components
public void onBindViewHolder(#NonNull MovieViewHolder holder, int position) {
holder.movieTitle.setText(movieArrayList.get(position).getOriginalTitle());
holder.rating.setText(String.valueOf(movieArrayList.get(position).getVoteAverage()));
String imagePath = "https://image.tmdb.org/t/p/w500" + movieArrayList.get(position).getPosterPath();
Glide.with(context)
.load(imagePath)
.placeholder(R.drawable.loading)
.into(holder.movieImage);
}
#Override
public int getItemCount() {
return movieArrayList == null ? 0 : movieArrayList.size();
}
public class MovieViewHolder extends RecyclerView.ViewHolder {
TextView movieTitle, rating;
ImageView movieImage;
public MovieViewHolder(#NonNull View itemView) {
super(itemView);
movieImage = itemView.findViewById(R.id.ivMovieImage);
movieTitle = itemView.findViewById(R.id.tvTitle);
rating = itemView.findViewById(R.id.tvRating);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
Movie selectedMovie = movieArrayList.get(position);
Intent intent = new Intent(context, MovieActivity.class);
intent.putExtra("movie", selectedMovie);
context.startActivity(intent);
}
}
});
}
}
}
MainActivity class:
public class MainActivity extends AppCompatActivity {
private ArrayList<Movie> popularMovie, topRatedMovie;
private RecyclerView recyclerViewPopular, recyclerViewUpcoming;
private MovieAdapter movieAdapter, upcomingAdapter;
private SwipeRefreshLayout swipeRefreshLayout;
private static ViewPager mPager;
private static int currentPage = 0;
private static int NUM_PAGES = 0;
String[] urls = new String[] {
"https://image.tmdb.org/t/p/w500/udDclJoHjfjb8Ekgsd4FDteOkCU.jpg",
"https://image.tmdb.org/t/p/w500//2bXbqYdUdNVa8VIWXVfclP2ICtT.jpg",
"https://image.tmdb.org/t/p/w500//zfE0R94v1E8cuKAerbskfD3VfUt.jpg",
"https://image.tmdb.org/t/p/w500//lcq8dVxeeOqHvvgcte707K0KVx5.jpg",
"https://image.tmdb.org/t/p/w500//w9kR8qbmQ01HwnvK4alvnQ2ca0L.jpg"
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initSlider();
getPopularMovies();
getUpcomingMovies();
swipeRefreshLayout = findViewById(R.id.swipe_layout);
swipeRefreshLayout.setColorSchemeResources(R.color.colorPrimaryDark);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
getPopularMovies();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(false);
}
}, 4000);
}
});
}
public void getPopularMovies() {
MovieDataService movieDataService = RetrofitInstance.getService();
Call<MovieDBResponse> callPopular = movieDataService.getPopularMovies(this.getString(R.string.apiKey));
callPopular.enqueue(new Callback<MovieDBResponse>() {
#Override
public void onResponse(Call<MovieDBResponse> call, Response<MovieDBResponse> response) {
MovieDBResponse movieDBResponse = response.body();
if(movieDBResponse!=null && movieDBResponse.getMovies()!=null) {
popularMovie = (ArrayList<Movie>) movieDBResponse.getMovies();
showOnRecyclerView();
}
}
#Override
public void onFailure(Call<MovieDBResponse> call, Throwable t) { }
});
}
public void getUpcomingMovies() {
MovieDataService movieDataService = RetrofitInstance.getService();
Call<MovieDBResponse> callUpcoming = movieDataService.getUpcomingMovies(this.getString(R.string.apiKey));
callUpcoming.enqueue(new Callback<MovieDBResponse>() {
#Override
public void onResponse(Call<MovieDBResponse> call, Response<MovieDBResponse> response) {
MovieDBResponse movieDBResponse = response.body();
if(movieDBResponse!=null && movieDBResponse.getMovies()!=null) {
topRatedMovie = (ArrayList<Movie>) movieDBResponse.getMovies();
showOnRecyclerView();
}
}
#Override
public void onFailure(Call<MovieDBResponse> call, Throwable t) { }
});
}
private void showOnRecyclerView() {
recyclerViewPopular = findViewById(R.id.rvMovies);
recyclerViewUpcoming = findViewById(R.id.rvTopMovies);
RecyclerView.LayoutManager popularLayoutManager = new LinearLayoutManager(this);
RecyclerView.LayoutManager upcomingLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
recyclerViewUpcoming.setLayoutManager(upcomingLayoutManager);
recyclerViewPopular.setLayoutManager(popularLayoutManager);
movieAdapter = new MovieAdapter(this, popularMovie);
upcomingAdapter = new MovieAdapter(this, topRatedMovie);
if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
recyclerViewPopular.setLayoutManager(new GridLayoutManager(this, 2));
}else {
recyclerViewPopular.setLayoutManager(new GridLayoutManager(this, 4));
}
recyclerViewPopular.setItemAnimator(new DefaultItemAnimator());
recyclerViewUpcoming.setItemAnimator(new DefaultItemAnimator());
recyclerViewPopular.setAdapter(movieAdapter);
recyclerViewUpcoming.setAdapter(upcomingAdapter);
movieAdapter.notifyDataSetChanged();
upcomingAdapter.notifyDataSetChanged();
}
}
I want to inflate 2 different layout "movie_list_item.xml" and "upcoming_movie_list_item.xml" in onCreateViewHolder() method.
With in your adapter class(MovieAdapter) create a new constructor and add extra params of Int or enum whatever simple for you i am just giving you simple example:-
public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.MovieViewHolder> {
private Context context;
private ArrayList<Movie> movieArrayList;
private int viewType;
public MovieAdapter(Context context, ArrayList < Movie > movieArrayList, int viewType) {
this.context = context;
this.movieArrayList = movieArrayList;
this.viewType=viewType;
}
#NonNull
#Override
public MovieViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view;
if (viewType == 1) {
//Popular movie layout
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.movie_list_item, parent, false);
} else {
//upcoming movie layout
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.movie_list_item, parent, false);
}
return new MovieViewHolder(view);
}
#Override
public int getItemViewType(int position) {
if (viewType == 1)
return 1; //Popular Movie Layout
else
return 2; //Upcoming Movie Layout
// return super.getItemViewType(position);
}
#Override
// Set values to the list item components
public void onBindViewHolder(#NonNull MovieViewHolder holder, int position) {
holder.movieTitle.setText(movieArrayList.get(position).getOriginalTitle());
holder.rating.setText(String.valueOf(movieArrayList.get(position).getVoteAverage()));
String imagePath = "https://image.tmdb.org/t/p/w500" + movieArrayList.get(position).getPosterPath();
Glide.with(context)
.load(imagePath)
.placeholder(R.drawable.loading)
.into(holder.movieImage);
}
#Override
public int getItemCount() {
return movieArrayList == null ? 0 : movieArrayList.size();
}
public class MovieViewHolder extends RecyclerView.ViewHolder {
TextView movieTitle, rating;
ImageView movieImage;
public MovieViewHolder(#NonNull View itemView) {
super(itemView);
movieImage = itemView.findViewById(R.id.ivMovieImage);
movieTitle = itemView.findViewById(R.id.tvTitle);
rating = itemView.findViewById(R.id.tvRating);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
Movie selectedMovie = movieArrayList.get(position);
Intent intent = new Intent(context, MovieActivity.class);
intent.putExtra("movie", selectedMovie);
context.startActivity(intent);
}
}
});
}
}
and within your activity change on this method only
private void showOnRecyclerView() {
recyclerViewPopular = findViewById(R.id.rvMovies);
recyclerViewUpcoming = findViewById(R.id.rvTopMovies);
RecyclerView.LayoutManager popularLayoutManager = new LinearLayoutManager(this);
RecyclerView.LayoutManager upcomingLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
recyclerViewUpcoming.setLayoutManager(upcomingLayoutManager);
recyclerViewPopular.setLayoutManager(popularLayoutManager);
movieAdapter = new MovieAdapter(this, popularMovie,1);
upcomingAdapter = new MovieAdapter(this, topRatedMovie,2);
if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
recyclerViewPopular.setLayoutManager(new GridLayoutManager(this, 2));
} else {
recyclerViewPopular.setLayoutManager(new GridLayoutManager(this, 4));
}
recyclerViewPopular.setItemAnimator(new DefaultItemAnimator());
recyclerViewUpcoming.setItemAnimator(new DefaultItemAnimator());
recyclerViewPopular.setAdapter(movieAdapter);
recyclerViewUpcoming.setAdapter(upcomingAdapter);
movieAdapter.notifyDataSetChanged();
upcomingAdapter.notifyDataSetChanged();
}
Create layout for movie_empty_item
public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.MovieViewHolder> {
private Context context;
private ArrayList<Movie> movieArrayList;
//add this two line
private static final int EMPTY_VIEW_TYPE = 0;
private static final int NORMAL_VIEW_TYPE = 1;
public MovieAdapter(Context context, ArrayList<Movie> movieArrayList) {
this.context = context;
this.movieArrayList = movieArrayList;
}
#NonNull
#Override
public MovieViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
//return viewholder replace like this
if(viewType == NORMAL_VIEW_TYPE) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.movie_list_item, parent, false);
return new MovieViewHolder(view);
}else {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.movie_empty_item, parent, false);
return new EmptyViewHolder(view);
};
}
//getItemViewType return replace like this
#Override
public int getItemViewType(int position) {
return movieArrayList.size()>0?NORMAL_VIEW_TYPE:EMPTY_VIEW_TYPE;
}
#Override
// Set values to the list item components
public void onBindViewHolder(#NonNull MovieViewHolder holder, int position) {
holder.movieTitle.setText(movieArrayList.get(position).getOriginalTitle());
holder.rating.setText(String.valueOf(movieArrayList.get(position).getVoteAverage()));
String imagePath = "https://image.tmdb.org/t/p/w500" + movieArrayList.get(position).getPosterPath();
Glide.with(context)
.load(imagePath)
.placeholder(R.drawable.loading)
.into(holder.movieImage);
}
#Override
public int getItemCount() {
return movieArrayList.size() ? movieArrayList.size():1 ;
}
public class MovieViewHolder extends RecyclerView.ViewHolder {
TextView movieTitle, rating;
ImageView movieImage;
public MovieViewHolder(#NonNull View itemView) {
super(itemView);
movieImage = itemView.findViewById(R.id.ivMovieImage);
movieTitle = itemView.findViewById(R.id.tvTitle);
rating = itemView.findViewById(R.id.tvRating);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
Movie selectedMovie = movieArrayList.get(position);
Intent intent = new Intent(context, MovieActivity.class);
intent.putExtra("movie", selectedMovie);
context.startActivity(intent);
}
}
});
}
}
public class EmptyViewHolder extends RecyclerView.ViewHolder {
public EmptyViewHolder(#NonNull View itemView) {
super(itemView);
}
}
}
I have RecycleView List with an ExpandableLinearLayout ( i use a third party library). In my ExpandableLinearLayout I have a ListView, with an custom ArrayAdapter.
I set my Adapter in the RecycleViewAdapter and submit one ArrayList that contains 4 ArrayLists and the position from the onBindViewHolder() method , too fill the different sections in the RecycleView.
I pass the data in the correct section but i get only the first element of each ArrayList. I Log some stuff and the problem is the position from the getView method in my ArrayAdapter is always 0..
I search and played around a bit but i didnt found a solution.. I hope somebody can help..
Sorry for my bad grammar
This is my RecycleView :
public class EmergencyPassAdapter extends RecyclerView.Adapter<EmergencyPassAdapter.EmergencyPassViewHolder> {
private static final String LOG_TAG = EmergencyPassAdapter.class.getName();
private Context context;
private ArrayList<CellInformation> cellInformations;
private SparseBooleanArray expandState = new SparseBooleanArray();
EmergencyPassExpandAdapter emergencyPassExpandAdapter;
public EmergencyPassAdapter(Context context, ArrayList<CellInformation> cellInformations) {
this.context = context;
this.cellInformations = cellInformations;
for (int i = 0; i < cellInformations.size(); i++) {
expandState.append(i, false);
}
}
#Override
public EmergencyPassViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cell_emergency_pass, parent, false);
return new EmergencyPassViewHolder(view);
}
#Override
public void onBindViewHolder(final EmergencyPassViewHolder holder, final int position) {
CellInformation cellInformation = cellInformations.get(position);
holder.imageViewIcon.setImageDrawable(cellInformation.getIcon());
holder.textViewTitle.setText(cellInformation.getTitel());
emergencyPassExpandAdapter = new EmergencyPassExpandAdapter(context, EmergencyPassExpandDetailFactory.getExpandCellInformation(context), position);
holder.listView.setAdapter(emergencyPassExpandAdapter);
if (cellInformation.getTitel().equals(context.getResources().getString(R.string.emergency_informations_health_insurance_emergency_contacts))) {
holder.expandableLinearLayout.setExpanded(expandState.get(position));
holder.expandableLinearLayout.setListener(new ExpandableLayoutListenerAdapter() {
#Override
public void onPreOpen() {
expandState.put(position, true);
holder.imageViewArrow.setRotation(180);
}
#Override
public void onPreClose() {
expandState.put(position, false);
holder.imageViewArrow.setRotation(360);
}
});
} else if (cellInformation.getTitel().equals(context.getResources().getString(R.string.emergency_informations_health_insurance_legal_guardian))) {
holder.expandableLinearLayout.setExpanded(expandState.get(position));
holder.expandableLinearLayout.setListener(new ExpandableLayoutListenerAdapter() {
#Override
public void onPreOpen() {
expandState.put(position, true);
holder.imageViewArrow.setRotation(180);
}
#Override
public void onPreClose() {
expandState.put(position, false);
holder.imageViewArrow.setRotation(360);
}
});
} else {
holder.expandableLinearLayout.setExpanded(expandState.get(position));
holder.expandableLinearLayout.setListener(new ExpandableLayoutListenerAdapter() {
#Override
public void onPreOpen() {
expandState.put(position, true);
holder.imageViewArrow.setRotation(180);
}
#Override
public void onPreClose() {
expandState.put(position, false);
holder.imageViewArrow.setRotation(360);
}
});
}
holder.relativeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!holder.expandableLinearLayout.isExpanded()) {
Log.i(LOG_TAG, "expand");
holder.expandableLinearLayout.expand();
} else {
Log.i(LOG_TAG, "collapse");
holder.expandableLinearLayout.collapse();
}
}
});
}
#Override
public int getItemCount() {
return cellInformations.size();
}
public static class EmergencyPassViewHolder extends RecyclerView.ViewHolder {
TextView textViewTitle, textViewExpandText;
ImageView imageViewIcon, imageViewArrow;
ExpandableLinearLayout expandableLinearLayout;
RelativeLayout relativeLayout;
ListView listView;
public EmergencyPassViewHolder(View itemView) {
super(itemView);
textViewTitle = (TextView) itemView.findViewById(R.id.cell_emergency_pass_title_tv);
textViewExpandText = (TextView) itemView.findViewById(R.id.cell_emergency_pass_expand_detail_tv);
imageViewIcon = (ImageView) itemView.findViewById(R.id.cell_emergency_pass_icon_iv);
imageViewArrow = (ImageView) itemView.findViewById(R.id.cell_emergency_pass_arrow_icon_iv);
expandableLinearLayout = (ExpandableLinearLayout) itemView.findViewById(R.id.cell_emergency_pass_arrow_expandable_list);
relativeLayout = (RelativeLayout) itemView.findViewById(R.id.cell_emergency_pass_root_rl);
listView = (ListView) itemView.findViewById(R.id.cell_emergency_pass_expand_lv);
}
}
}
My ArrayAdapter
public class EmergencyPassExpandAdapter extends ArrayAdapter<CellExpandInformation>{
private static final String LOG_TAG = EmergencyPassExpandAdapter.class.getName();
private ArrayList<CellExpandInformation> values;
private int checkPosition;
private Context context;
public EmergencyPassExpandAdapter(Context context, ArrayList<CellExpandInformation> values, int checkPosition) {
super(context, -1, values);
this.context = context;
this.values = values;
this.checkPosition = checkPosition;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Log.i(LOG_TAG,"View");
Log.i(LOG_TAG,"Position: " + position);
EmergencyPassExpandViewHolder viewHolder;
CellExpandInformation cellExpandInformation = values.get(position);
if (convertView == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
convertView = inflater.inflate(R.layout.cell_emergency_pass_expand, parent, false);
viewHolder = new EmergencyPassExpandViewHolder();
viewHolder.textViewExpandTitle = (TextView) convertView.findViewById(R.id.cell_emergency_pass_expand_detail_tv);
convertView.setTag(viewHolder);
} else {
viewHolder = (EmergencyPassExpandViewHolder) convertView.getTag();
}
Log.i(LOG_TAG,"CheckPosition: " + checkPosition);
if (values != null) {
if (checkPosition == 0) {
viewHolder.textViewExpandTitle.setText(cellExpandInformation.getMedications().get(position).getMedicationName());
Log.i(LOG_TAG, "Medications: " + cellExpandInformation.getMedications().get(position).getMedicationName());
} else if (checkPosition == 1) {
viewHolder.textViewExpandTitle.setText(cellExpandInformation.getAllergies().get(position).getAllgergiesName());
} else if (checkPosition == 2) {
viewHolder.textViewExpandTitle.setText(cellExpandInformation.getDiseases().get(position).getDiseasesName());
} else if (checkPosition == 3) {
viewHolder.textViewExpandTitle.setText(cellExpandInformation.getLegalGuradian().get(position).getGuradianName());
} else if (checkPosition == 4) {
viewHolder.textViewExpandTitle.setText(cellExpandInformation.getEmergencyContact().get(position).getEmergencyContactName());
}
}
for(int i = 0; i < cellExpandInformation.getMedications().size(); i++){
Log.i(LOG_TAG,"Medis: " + cellExpandInformation.getMedications().get(i).getMedicationName());
}
return convertView;
}
static class EmergencyPassExpandViewHolder {
TextView textViewExpandTitle;
ImageView imageViewPhone, imageViewEmail, imageViewAdd;
}
}
I have a RecyclerViewAdapter which fill my List with StoreName,image etc, I had model for listitems.ok, I'm migrating from a ListView to recylerview. i want to click on any item and get that items data(like Store name) and intent to another activity, now problem is that when i click on item it give wrong storename. but when i was using onItemclickListener that provide correct input. i will show u..
This my RecyclerViewAdapter.
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.DataObjectHolder> {
private static String LOG_TAG = "MyRecyclerViewAdapter";
private List<StoresItem> mDataset;
private static MyClickListener myClickListener;
Context context;
Bitmap xx;
public MyRecyclerViewAdapter(Context context, List<StoresItem> myDataset)
{
mDataset = myDataset;
}
public static class DataObjectHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView txtStoreName,txtDeliveryTime;
ImageView storeImg;
RatingBar ratingBar;
public DataObjectHolder(View itemView)
{
super(itemView);
txtStoreName = (TextView) itemView.findViewById(R.id.txtStoreName);
txtDeliveryTime = (TextView) itemView.findViewById(R.id.txtDeliveryTime);
storeImg = (ImageView) itemView.findViewById(R.id.storeImg);
ratingBar=(RatingBar)itemView.findViewById(R.id.ratingBar);
Log.i(LOG_TAG, "Adding Listener");
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v)
{
myClickListener.onItemClick(getLayoutPosition(), v);
}
}
public void setOnItemClickListener(MyClickListener myClickListener)
{
this.myClickListener = myClickListener;
}
#Override
public DataObjectHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.storelist, parent, false);
DataObjectHolder dataObjectHolder = new DataObjectHolder(view);
return dataObjectHolder;
}
#Override
public void onBindViewHolder(DataObjectHolder holder, int position)
{
ImageView storeImg;
holder.txtStoreName.setText(mDataset.get(position).gettxtStoreName().toString());
holder.txtDeliveryTime.setText(mDataset.get(position).gettxtDeliveryTime().toString());
holder.ratingBar.setFocusable(false);
int loader = R.drawable.image;
String url = mDataset.get(position).getstoreImg().toString();
ImageLoader imgLoader = new ImageLoader(context);
imgLoader.DisplayImage(url,loader,holder.storeImg);
}
public void addItem(StoresItem dataObj, int index) {
mDataset.add(dataObj);
notifyItemInserted(index);
}
public void deleteItem(int index) {
mDataset.remove(index);
notifyItemRemoved(index);
}
#Override
public int getItemCount() {
return mDataset.size();
}
public interface MyClickListener
{
public void onItemClick(int position, View v);
}
public Object getItem(int position)
{
return mDataset.get(position);
}
#Override
public long getItemId(int position)
{
return mDataset.indexOf(getItem(position));
}
#Override
public int getItemViewType(int position)
{
return super.getItemViewType(position);
}
}
This is my StoreModel.
public class StoresItem
{
private String txtStoreName, txtDeliveryTime, storeImg;
public StoresItem(String txtStoreName, String txtDeliveryTime,String storeImg)
{
this.txtStoreName = txtStoreName;
this.txtDeliveryTime = txtDeliveryTime;
this.storeImg = storeImg;
}
public String gettxtStoreName()
{
return txtStoreName;
}
public void settxtStoreName(String txtStoreName)
{
this.txtStoreName = txtStoreName;
}
public String gettxtDeliveryTime()
{
return txtDeliveryTime;
}
public void settxtDeliveryTime(String txtDeliveryTime)
{
this.txtDeliveryTime = txtDeliveryTime;
}
public String getstoreImg()
{
return storeImg;
}
public void setstoreImg(String storeImg)
{
this.storeImg = storeImg;
}
}
And this is my Fragment where i using onclickListner.
public class RecylerFragment extends Fragment
{
ListView storeListView;
List<StoresItem> storesItem;
StoresListAdaptor adapter;
String selectedStore;
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
public static final String[] storeNameGrocery = new String[]
{
"Value Store", "Grocery Mart", "Wild Water-Sadar Bazar", "Store99","Coco-Buzz", "Wild Water - Sector 46"
};
public static final String[] storeNameFresh = new String[]
{
"Mother's Love", "The Flower Shop", "Flower N Emotions"
};
public static final String[] storeNameElectronics = new String[]
{
"Molife-Sheetla Mata Road", "Apple Store- Shona Road", "Vandana Communication", "Samsung Store","JMD Mobile - Sector 14", "Sterling - Gurgaon"
};
public static final String[] storeNameVegetable = new String[]
{
"Fortune Store", "Best Food - Mega Mall", "Sadar Bazar", "MTR Store","Coco-Buzz"
};
public static final String[] deliveryTime = new String[]
{
"20min", "10min", "9min", "15min","30min", "1hr","20min","20min", "10min", "9min", "15min","30min", "1hr","20min" };
private static final String KEY_POSITION="position";
public static final String[] iconsUrl = new String[]
{
"http://icons.iconarchive.com/icons/femfoyou/angry-birds/96/angry-bird-icon.png",
"http://icons.iconarchive.com/icons/rokey/the-blacy/96/grimace-icon.png",
"http://wcdn1.dataknet.com/static/resources/icons/set106/fec007de.png",
"http://cdn4.aptoide.com/imgs/7/6/e/76e0376928b8393227a150fbed5d6b4a_icon_96x96.png",
"http://vaivocabulary.com/vai/images/android.png",
"http://cdn4.aptoide.com/imgs/7/6/e/76e0376928b8393227a150fbed5d6b4a_icon_96x96.png",
"http://vaivocabulary.com/vai/images/android.png",
"http://wcdn1.dataknet.com/static/resources/icons/set106/fec007de.png",
};
public RecylerFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.activity_recycler_view, container, false);
Bundle bundle = this.getArguments();
String myString = bundle.getString("page_position");
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
RecyclerView.ItemDecoration itemDecoration = new DividerItemDecoration(getActivity(), LinearLayoutManager.VERTICAL);
mRecyclerView.addItemDecoration(itemDecoration);
// Code to Add an item with default animation
//((MyRecyclerViewAdapter) mAdapter).addItem(obj, index);
// Code to remove an item with default animation
//((MyRecyclerViewAdapter) mAdapter).deleteItem(index);
storesItem = new ArrayList<StoresItem>();
if(myString.equals("999")) {
for (int i = 0; i < storeNameGrocery.length; i++) {
StoresItem item = new StoresItem(storeNameGrocery[i], "Delivery Time " + deliveryTime[i],iconsUrl[i]);
storesItem.add(item);
}
}
else if(myString.equals("888")) {
for (int i = 0; i < storeNameFresh.length; i++) {
StoresItem item = new StoresItem(storeNameFresh[i], "Delivery Time " + deliveryTime[i], iconsUrl[i]);
storesItem.add(item);
}
}
else if(myString.equals("777")) {
for (int i = 0; i < storeNameElectronics.length; i++) {
StoresItem item = new StoresItem(storeNameElectronics[i], "Delivery Time " + deliveryTime[i], iconsUrl[i]);
storesItem.add(item);
}
}
else if(myString.equals("666")) {
for (int i = 0; i < storeNameVegetable.length; i++) {
StoresItem item = new StoresItem(storeNameVegetable[i], "Delivery Time " + deliveryTime[i], iconsUrl[i]);
storesItem.add(item);
}
}
mAdapter = new MyRecyclerViewAdapter(getActivity(), storesItem);
mRecyclerView.setAdapter(mAdapter);
return rootView;
}
**#Override
public void onResume() {
super.onResume();
((MyRecyclerViewAdapter) mAdapter).setOnItemClickListener(new MyRecyclerViewAdapter.MyClickListener()
{
#Override
public void onItemClick(int position, View v)
{
System.out.println(" Clicked on Item " + position);
StoresItem storesItems = (StoresItem) ((MyRecyclerViewAdapter) mAdapter).getItem(position);
Bundle args = new Bundle();
Intent in = new Intent(getActivity(), ProductActivity.class);
args.putString("SelectedStoreName", storesItems.gettxtStoreName().toString());
in.putExtras(args);
startActivity(in);
}
});
}**
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
}
okk...there is something wrong with recyclerviews-onItemclicklister because listviews - onItemCLicklistner()
provide Adapterview and i can simply get Item by using parent.getItematposition(position) like this.
storeListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
StoresItem storesItems = (StoresItem) parent.getItemAtPosition(position);
Bundle args = new Bundle();
Intent in = new Intent(getActivity(), ProductActivity.class);
args.putString("SelectedStoreName", storesItems.gettxtStoreName().toString());
in.putExtras(args);
startActivity(in);
}
});
Can Any one tell me whats the reason why getWrong StoreName.??
You are using myClickListener.onItemClick(getLayoutPosition(), v); you have to use myClickListener.onItemClick(getAdapterPosition(), v);