SetOnItemClickListener not working inside Fragment - android

I am using RecycleView to display list of Name and Description. I am using Fragment to view the desired layout. Now, I want to open new Activity onItemClick. I have declared SetOnItemClickListener inside the Fragment, i.e. in "View onCreateView". But it is not working. Here is my code:
This is my java class:
public class TabsHeaderActivity extends AppCompatActivity {
private static final String TAG = TabsHeaderActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabs_header);
final Toolbar toolbar = (Toolbar) findViewById(R.id.htab_toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) getSupportActionBar().setTitle("TECHNOLOGY");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final ViewPager viewPager = (ViewPager) findViewById(R.id.htab_viewpager);
setupViewPager(viewPager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.htab_tabs);
tabLayout.setupWithViewPager(viewPager);
final CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.htab_collapse_toolbar);
try {
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.header);
Palette.from(bitmap).generate(new Palette.PaletteAsyncListener() {
#SuppressWarnings("ResourceType")
#Override
public void onGenerated(Palette palette) {
int vibrantColor = palette.getVibrantColor(R.color.primary_500);
int vibrantDarkColor = palette.getDarkVibrantColor(R.color.primary_700);
collapsingToolbarLayout.setContentScrimColor(vibrantColor);
collapsingToolbarLayout.setStatusBarScrimColor(vibrantDarkColor);
}
});
} catch (Exception e) {
// if Bitmap fetch fails, fallback to primary colors
Log.e(TAG, "onCreate: failed to create bitmap from background", e.fillInStackTrace());
collapsingToolbarLayout.setContentScrimColor(
ContextCompat.getColor(this, R.color.primary_500)
);
collapsingToolbarLayout.setStatusBarScrimColor(
ContextCompat.getColor(this, R.color.primary_700)
);
}
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
Log.d(TAG, "onTabSelected: pos: " + tab.getPosition());
switch (tab.getPosition()) {
case 0:
break;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new DummyFragment(
ContextCompat.getColor(this, R.color.cyan_50)), "Cyan");
adapter.addFrag(new DummyFragment(
ContextCompat.getColor(this, R.color.amber_50)), "Amber");
adapter.addFrag(new DummyFragment(
ContextCompat.getColor(this, R.color.purple_50)), "Purple");
adapter.addFrag(new DummyFragment(
ContextCompat.getColor(this, R.color.grey)), "Grey");
viewPager.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
final MenuItem searchItem = menu.findItem(R.id.menuSearch);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener(){
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return true;
}
});
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
private static class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
public static class DummyFragment extends Fragment {
int color;
Intent intent;
public DummyFragment() {
}
#SuppressLint("ValidFragment")
public DummyFragment(int color) {
this.color = color;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dummy_fragment, container, false);
final FrameLayout frameLayout = (FrameLayout) view.findViewById(R.id.dummyfrag_bg);
frameLayout.setBackgroundColor(color);
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.dummyfrag_scrollableview);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity().getBaseContext());
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setHasFixedSize(true);
DessertAdapter adapter = new DessertAdapter(getContext());
recyclerView.setAdapter(adapter);
adapter.SetOnItemClickListener(new DessertAdapter.OnItemClickListener(){
#Override
public void onItemClick(View view, int position) {
switch (position) {
case 3:
intent = new Intent(view.getContext(), LaunchScreenActivity.class);
startActivity(intent);
}
}
});
return view;
}
}
}
This is my Adapter class:
public class DessertAdapter extends RecyclerView.Adapter<DessertAdapter.DessertVh> {
private List<Dessert> desserts = new ArrayList<>();
OnItemClickListener clickListener;
private Context context;
public DessertAdapter(Context context) {
this.context = context;
desserts = Dessert.prepareDesserts(
context.getResources().getStringArray(R.array.dessert_names),
context.getResources().getStringArray(R.array.dessert_descriptions));
}
#Override
public DessertVh onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.item_dessert, parent, false);
return new DessertAdapter.DessertVh(view);
}
#Override
public void onBindViewHolder(DessertVh holder, int position) {
Dessert dessert = desserts.get(position);
holder.mName.setText(dessert.getName());
holder.mDescription.setText(dessert.getDescription());
holder.mFirstLetter.setText(String.valueOf(dessert.getFirstLetter()));
}
#Override
public int getItemCount() {
return desserts == null ? 0 : desserts.size();
}
public class DessertVh extends RecyclerView.ViewHolder implements View.OnClickListener{
private TextView mName;
private TextView mDescription;
private TextView mFirstLetter;
public DessertVh(View itemView) {
super(itemView);
mName = (TextView) itemView.findViewById(R.id.txt_name);
mDescription = (TextView) itemView.findViewById(R.id.txt_desc);
mFirstLetter = (TextView) itemView.findViewById(R.id.txt_firstletter);
}
#Override
public void onClick(View v) {
clickListener.onItemClick(v, getPosition());
}
}
public interface OnItemClickListener {
public void onItemClick(View view, int position);
}
public void SetOnItemClickListener(final OnItemClickListener itemClickListener) {
this.clickListener = itemClickListener;
}
I am not sure what I am doing wrong. I have checked it in debugger mode. I have put a breakpoint at line:
adapter.SetOnItemClickListener(new DessertAdapter.OnItemClickListener(){
Now, when my Activity is loading debugger comes on this line but, doesn't go inside it. But, when I am clicking something, the debugger doesn't even come on this line, means when I am clicking an item, SetOnItemClickListener doesn't get triggered.
My xml code is:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/dummyfrag_bg"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/bg_light">
<android.support.v7.widget.RecyclerView
android:id="#+id/dummyfrag_scrollableview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false"
android:paddingBottom="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_horizontal_margin" />
</FrameLayout>

Well, you implemented a normal click listener
DessertVh extends RecyclerView.ViewHolder implements View.OnClickListener
But you never set it.
public DessertVh(View itemView) {
super(itemView);
mName = (TextView) itemView.findViewById(R.id.txt_name);
mDescription = (TextView) itemView.findViewById(R.id.txt_desc);
mFirstLetter = (TextView) itemView.findViewById(R.id.txt_firstletter);
}
Did you forget about itemView.setOnClickListener(this)?

Related

Update RecyclerView from menu

I have a MainActivity with two fragments. The second fragment has RecyclerView. There is TextView ( lesson name) and ImageView(show lesson status, if it is done or not) in RecyclerView . When you click TextView, it calls another Activity with lesson. After you make the lesson you will go back to MainActivity. After that lessons ImageView will be changed from nothing to resourse 'ic_lessondone'. Also there is a menu in MainActivity. Menu have item 'Reset lessons'. When you press 'Reset lessons' all ImageViews wont show any images. So there are two problems. 1) if I do, for example , only 6th lesson. I will have image 'lessondone'. When i press 'Reset lessons' image will disappear. But when i go back to menu again and press 'Reset lessons', Image will appear again and rise to previous lesson ( 5th). 2) If i switch off display, image will also appear to previous lessons till to 0th.
Its seems i have a problem with onResume.
Help me please.
public class MainActivity extends AppCompatActivity
{
private DrawerLayout mDrawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar ab = getSupportActionBar();
ab.setHomeAsUpIndicator(R.drawable.ic_menu);
ab.setDisplayHomeAsUpEnabled(true);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
if (navigationView != null)
{
setupDrawerContent(navigationView);
}
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
if (viewPager != null)
{
setupViewPager(viewPager);
}
// Круглая кнопка
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
Snackbar.make(view, "Here's a Snackbar", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
// Картинки для табов
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.ic_home);
tabLayout.getTabAt(1).setIcon(R.drawable.ic_lessons);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.sample_actions, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu)
{
switch (AppCompatDelegate.getDefaultNightMode())
{
case AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM:
menu.findItem(R.id.menu_night_mode_system).setChecked(true);
break;
case AppCompatDelegate.MODE_NIGHT_AUTO:
menu.findItem(R.id.menu_night_mode_auto).setChecked(true);
break;
case AppCompatDelegate.MODE_NIGHT_YES:
menu.findItem(R.id.menu_night_mode_night).setChecked(true);
break;
case AppCompatDelegate.MODE_NIGHT_NO:
menu.findItem(R.id.menu_night_mode_day).setChecked(true);
break;
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START);
return true;
case R.id.menu_night_mode_system:
setNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
break;
case R.id.menu_night_mode_day:
setNightMode(AppCompatDelegate.MODE_NIGHT_NO);
break;
case R.id.menu_night_mode_night:
setNightMode(AppCompatDelegate.MODE_NIGHT_YES);
break;
case R.id.menu_night_mode_auto:
setNightMode(AppCompatDelegate.MODE_NIGHT_AUTO);
break;
}
return super.onOptionsItemSelected(item);
}
private void setNightMode(#AppCompatDelegate.NightMode int nightMode)
{
AppCompatDelegate.setDefaultNightMode(nightMode);
if (Build.VERSION.SDK_INT >= 11)
{
recreate();
}
}
private void setupViewPager(ViewPager viewPager)
{
Adapter adapter = new Adapter(getSupportFragmentManager());
adapter.addFragment(new Fragment(), "");
adapter.addFragment(new LessonsListFragment(), "");
viewPager.setAdapter(adapter);
}
// Главное меню
private void setupDrawerContent(NavigationView navigationView)
{
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem)
{
menuItem.setChecked(true);
if (menuItem.getTitle().equals("Reset lessons"))
{
// Обнуляем файл с рузультатами уроков
LessonsListFragment.sLessonsPref.edit().clear().commit();
// Перерисовываем весь писок уроков
LessonsListFragment.rv.getAdapter().notifyItemRangeChanged(0, LessonsListFragment.rv.getAdapter().getItemCount());
}
mDrawerLayout.closeDrawers();
return true;
}
});
}
static class Adapter extends FragmentPagerAdapter
{
private final List<Fragment> mFragments = new ArrayList<>();
private final List<String> mFragmentTitles = new ArrayList<>();
public Adapter(FragmentManager fm)
{
super(fm);
}
public void addFragment(Fragment fragment, String title)
{
mFragments.add(fragment);
mFragmentTitles.add(title);
}
// Получаем конкретный фрагмент
#Override
public Fragment getItem(int position)
{
return mFragments.get(position);
}
// Количество фрагментов для viewpager (2)
#Override
public int getCount()
{
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position)
{
return mFragmentTitles.get(position);
}
}
}
Fragment
public class LessonsListFragment extends Fragment
{
// Уроки
// static private Map<String,?> mLessonsKeys ;
static SharedPreferences sLessonsPref;
static RecyclerView rv;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
loadSharedPreferenses();
rv = (RecyclerView) inflater.inflate(R.layout.fragment_cheese_list, container, false);
setupRecyclerView(rv);
return rv;
}
// Загружаем список пройденных уроков
public void loadSharedPreferenses()
{
sLessonsPref = this.getActivity().getSharedPreferences("LessonsResults", Context.MODE_PRIVATE);
}
// Количество строк в листе
private void setupRecyclerView(RecyclerView recyclerView)
{
recyclerView.setLayoutManager(new LinearLayoutManager(recyclerView.getContext()));
recyclerView.setAdapter(new SimpleStringRecyclerViewAdapter(getActivity(), getRandomSublist(Cheeses.sCheeseStrings, Cheeses.sCheeseStrings.length)));
}
// Задаем Строки
private List<String> getRandomSublist(String[] array, int amount)
{
ArrayList<String> list = new ArrayList<>(amount);
//Random random = new Random();
while (list.size() < amount)
{
list.add(array[list.size()]);
}
return list;
}
//Отработка перерисования окна, при возврате к ней
#Override
public void onResume()
{
super.onResume();
//loadSharedPreferenses();
//Toast.makeText(null, "Refreshed", Toast.LENGTH_SHORT).show();
if (rv.getAdapter() != null)
{
rv.getAdapter().notifyDataSetChanged();
}
}
// Адаптер
public static class SimpleStringRecyclerViewAdapter
extends RecyclerView.Adapter<SimpleStringRecyclerViewAdapter.ViewHolder>
{
private final TypedValue mTypedValue = new TypedValue();
private int mBackground;
private List<String> mValues;
public static class ViewHolder extends RecyclerView.ViewHolder
{
// Номер урока, передается в webactivity
public int mLessonNumber;
public final View mView;
public final ImageView mImageView;
public final TextView mTextView;
public ViewHolder(View view)
{
super(view);
mView = view;
mImageView = (ImageView) view.findViewById(R.id.avatar);
mTextView = (TextView) view.findViewById(android.R.id.text1);
}
#Override
public String toString()
{
return super.toString() + " '" + mTextView.getText();
}
}
public String getValueAt(int position)
{
return mValues.get(position);
}
public SimpleStringRecyclerViewAdapter(Context context, List<String> items)
{
context.getTheme().resolveAttribute(R.attr.selectableItemBackground, mTypedValue, true);
mBackground = mTypedValue.resourceId;
mValues = items;
}
// Создаем холдер с полезной нагрузкой
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item, parent, false);
view.setBackgroundResource(mBackground);
return new ViewHolder(view);
}
//Создаем список уроков
#Override
public void onBindViewHolder(final ViewHolder holder, int position)
{
holder.mLessonNumber = position + 1;
// Увеличиваем позицион на 1 что не было 0 урока
holder.mTextView.setText((position + 1) + " " + mValues.get(position));
// Если урок пройден
String finished = sLessonsPref.getString((position + 1) + "", "");
if (finished.equals("1"))
{
// Меняем его цвет
//holder.mTextView.setTextColor(R.color.white);
Glide.with(holder.mImageView.getContext()).load(R.drawable.ic_lessondone)
//.load(Cheeses.getRandomCheeseDrawable())
.fitCenter()
.into(holder.mImageView);
Log.d("Glide", "Work");
}
else
{
holder.mTextView.setTextColor(R.color.black);
// holder.mImageView.setVisibility(View.GONE);
}
// Вызов WebActivity
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Context context = v.getContext();
Intent intent = new Intent(context, WebActivity.class);
// Передаем вебвью номер урока и запускаем ее
intent.putExtra(WebActivity.EXTRA_NAME, holder.mLessonNumber);
context.startActivity(intent);
}
});
}
// Определяем количество выводимых строк
#Override
public int getItemCount()
{
return mValues.size();
}
}
}
Implement a reset() method in the adapter that mark all items as "not done" and then try:
LessonsListFragment.rv.getAdapter().reset();
LessonsListFragment.rv.getAdapter().notifyDataSetChanged();
instead of:
LessonsListFragment.rv.getAdapter().notifyItemRangeChanged(0, LessonsListFragment.rv.getAdapter().getItemCount());
inside onNavigationItemSelected.
Also, you shouldn't be using static variables (like static RecyclerView rv), use private vars with getters
The problem was in else statement. I added there this code, and now its ok. notifydatachanged work correctly from navigationview
if (finished.equals("1"))
{
// Меняем его цвет
//holder.mTextView.setTextColor(R.color.white);
Glide.with(holder.mImageView.getContext()).load(R.drawable.ic_lessondone)
.fitCenter()
.into(holder.mImageView);
Log.d("Glide", "Work");
}
else
{
Glide.with(holder.mImageView.getContext()).load(R.color.white)
.fitCenter()
.into(holder.mImageView);
holder.mTextView.setTextColor(R.color.black);
}

How to notify all the listview with multiple checkboxes inside multiple fragments?

I've a viewpager looping a multiple fragments and set in a viewpager. Each fragment has a listview with checkbox. On clicking any one item of a list it will notify all the fragments so that all checkbox remains unchecked and only clicked item will be checked.
CreateGroupStep1
public class CreateGroupStep1 extends BaseActivity implements IGroup {
private TabLayout tabLayout;
private ViewPager viewPager;
private ImageView next_btn,back;
private int current_item_position;
private ViewPagerAdapter adapter;
private ArrayList<Interest> interestList;
ArrayList<String>al_sports;
ArrayList<String>al_list_collect;
private ArrayList<String>al_title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_group_step1);
storeDataOfArrayList();
al_list_collect=new ArrayList<String>();
initViews();
}
public void initViews() {
viewPager = (ViewPager) findViewById(R.id.viewpager);
RelativeLayout back=(RelativeLayout) findViewById(R.id.back);
back=(RelativeLayout) findViewById(R.id.back);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
next_btn=(ImageView) findViewById(R.id.next_btn);
next_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Intent ii=new Intent(CreateGroupStep1.this,CreateGroupStep2.class);
//startActivity(ii);
Toast.makeText(CreateGroupStep1.this, "", Toast.LENGTH_SHORT).show();
}
});
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setTitle("");
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
private void setupViewPager(ViewPager viewPager) {
adapter = new ViewPagerAdapter(CreateGroupStep1.this.getSupportFragmentManager());
for (int i=0;i<al_title.size();i++)
{
adapter.addFragment(InterestFragmentForGroup.getInstance(al_sports),al_title.get(i));
viewPager.setAdapter(adapter);
}
viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(10);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
public void onPageScrollStateChanged(int state) {
}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
public void onPageSelected(int position) {
current_item_position = position;
// Toast.makeText(CreateGroupStep1.this, "scrolled", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onClickedNextButton(final String message) {
next_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(CreateGroupStep1.this,message, Toast.LENGTH_SHORT).show();
}
});
}
public static class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
public void storeDataOfArrayList()
{
saveData();
al_sports=new ArrayList<>();
al_sports.add("Baseball");
al_sports.add("Basketball");
al_sports.add("Bowling");
al_sports.add("Cricket");
al_sports.add("Football");
al_sports.add("Golf");
al_sports.add("Handball");
al_sports.add("Hockey");
al_sports.add("Jogging");
al_sports.add("Racquetball");
al_sports.add("Running");
al_sports.add("Skiing");
al_sports.add("Snowboarding");
al_sports.add("Soccer");
al_sports.add("Swimming");
al_sports.add("Tennis");
}
private void saveData()
{
al_title=new ArrayList<String>();
al_title.add("Sports");
al_title.add("LifeStyle");
al_title.add("Adventure");
al_title.add("Recreation");
al_title.add("The Arts");
al_title.add("College");
al_title.add("Sos");
al_title.add("Industry");
al_title.add("LocalBiz");
al_title.add("Corporate");
}
}
InterestAdapterForGroup
public class InterestAdapterForGroup extends RecyclerView.Adapter<InterestAdapterForGroup.MyViewHolder> implements IGroup {
public int selectedPosition = -1;
IGroup inter;
private LayoutInflater inflater;
private ArrayList<Interest> stList;
private Context mContext;
private ArrayList<Interest> checked_item = new ArrayList<>();
public InterestAdapterForGroup(Context context, ArrayList<Interest> al_list) {
this.mContext = context;
this.stList = al_list;
inflater = LayoutInflater.from(context);
inter = (IGroup) mContext;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.custom_ethnic, parent, false);
InterestAdapterForGroup.MyViewHolder holder = new InterestAdapterForGroup.MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
final int pos = position;
final Interest interest = stList.get(position);
holder.title.setText(interest.getName());
if (position == selectedPosition) {
holder.chkSelected.setChecked(true);
} else {
holder.chkSelected.setChecked(false);
}
holder.chkSelected.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (buttonView.isPressed()) {
interest.isSelected = isChecked;
if (isChecked) {
checked_item.clear();
checked_item.add(interest);
selectedPosition = position;
} else {
checked_item.remove(interest);
selectedPosition = -1;
}
notifyDataSetChanged();
}
}
});
clickedItems();
}
public void clickedItems() {
if (checked_item.size() > 0) {
if (Constants.GLOBAL_ARRAY.size() > 0) {
Constants.GLOBAL_ARRAY.clear();
for (int i = 0; i < checked_item.size(); i++) {
Constants.GLOBAL_ARRAY.add(checked_item.get(i).getName());
}
}
}
ArrayList<String> al_name = new ArrayList<String>();
ArrayList<String> al_nam = new ArrayList<String>();
for (int i = 0; i < checked_item.size(); i++) {
al_name.add(checked_item.get(i).getEmailId());
}
for (int i = 0; i < checked_item.size(); i++) {
al_nam.add(checked_item.get(i).getName());
Constants.GLOBAL_ARRAY.add(checked_item.get(i).getName());
}
inter.onClickedNextButton(al_nam.toString());
}
public ArrayList<Interest> getCheckedItemList() {
return stList;
}
#Override
public int getItemCount() {
return stList.size();
}
#Override
public void onClickedNextButton(String message) {
}
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public CheckBox chkSelected;
TextView title;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.txt_ethnic);
chkSelected = (CheckBox) itemView
.findViewById(R.id.chk);
}
#Override
public void onClick(View v) {
}
}
}
InterestFragmentForGroup
public class InterestFragmentForGroup extends BasePagerFragment implements IPager {
private ArrayList<String> interestList;
private ArrayList<Interest> interestListfunction;
public static Fragment getInstance(ArrayList<String> interestList){
Bundle bundle = new Bundle();
bundle.putSerializable("interestList",interestList);
InterestFragmentForGroup interestsFragment = new InterestFragmentForGroup();
interestsFragment.setArguments(bundle);
return interestsFragment;
}
public void getInterestList(){
interestList = (ArrayList<String>) getArguments().getSerializable("interestList");
}
private RecyclerView recyclerView;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.sports_fragment, container, false);
initViews(rootView);
return rootView;
}
public void initViews(View view) {
recyclerView = (RecyclerView) view.findViewById(R.id.drawerList);
getInterestList();
setData();
}
public void setData() {
interestListfunction = new ArrayList<>();
for (int i = 0; i < interestList.size(); i++) {
Interest st = new Interest(interestList.get(i), interestList.get(i), false);
interestListfunction.add(st);
}
adapter2 = new InterestAdapterForGroup(getActivity(), interestListfunction);
recyclerView.addItemDecoration(new DividerDecoration(getActivity(), LinearLayoutManager.VERTICAL));
recyclerView.setAdapter(adapter2);
recyclerView.setLayoutManager(new LinearLayoutManager(recyclerView.getContext()));
}
}

Android application getting stuck when swiping through Viewpager, and navigation drawer in marshmallow device

I am using ViewPager inside my Navigation Drawer all are works fine in devices other than marshmallow devices. in marshmallow devices when i clicking toggle button or swiping the navigation drawer (in both direction) feel a stuck(glitch) in the flow, also when i swipe the viewpager into different tabs also found the stuckking. This was found only in marshmallow device. please help me,, thanks in advance....
this is my code
activity class
public class HomeActivity extends AppCompatActivity{
Toolbar toolbar;
DrawerLayout drawerLayout;
ActionBarDrawerToggle actionBarDrawerToggle;
FragmentTransaction fragmentTransaction;
NavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
toolbar = (Toolbar)findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.drawer_open,R.string.drawer_close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.main_container,new HomeViewPagerFragment());
fragmentTransaction.commit();
getSupportActionBar().setTitle("Home");
navigationView = (NavigationView)findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.home:
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_container,new HomeViewPagerFragment());
fragmentTransaction.commit();
getSupportActionBar().setTitle("Home");
item.setChecked(true);
drawerLayout.closeDrawers();
break;
}
return true;
}
});
}
#Override
protected void onPostCreate(#Nullable Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
actionBarDrawerToggle.syncState();
}
}
ViewPager fragment
public class HomeViewPagerFragment extends Fragment {
ArrayList<Model> mArrayList= new ArrayList<>();
Model model;
TabLayout tabLayout;
ViewPager viewPager;
HomeViewPagerAdapter viewPagerAdapter;
public HomeViewPagerFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home_view_pager,container,false);
viewPager = (ViewPager)rootView.findViewById(R.id.view_pager);
// parsing and add datas into mArrayList
viewPagerAdapter = new HomeViewPagerAdapter(getActivity().getSupportFragmentManager(),mArrayList);
viewPager.setAdapter(viewPagerAdapter);
viewPager.setOffscreenPageLimit(2);
// Give the TabLayout the ViewPager
viewPager.setCurrentItem(Credentials.homeTabSelected);
tabLayout = (TabLayout)rootView.findViewById(R.id.sliding_tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener(){
#Override
public void onTabSelected(TabLayout.Tab tab){
Credentials.homeTabSelected = tab.getPosition();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
return rootView;
}
}
viewpager adapter
public class HomeViewPagerAdapter extends FragmentStatePagerAdapter {
ArrayList<Model> mArrayList = new ArrayList<>();
String tabTitles[] = new String[] { "tab1","tab2" };
public HomeViewPagerAdapter(FragmentManager fm, ArrayList<Model> arrayList) {
super(fm);
mArrayList = arrayList;
}
#Override
public Fragment getItem(int position) {
if(position==0) {
return new HomeCentralFragment();
}
else {
return HomeRecyclerFragment.newInstance(mArrayList);
}
}
#Override
public int getCount() {
return tabTitles.length;
}
#Override
public CharSequence getPageTitle(int position) {
return tabTitles[position];
}
}
HomeCentralFragment
public class HomeCentralFragment extends Fragment {
public HomeCentralFragment(){
}
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home_central,null);
//my code is here(buttons, click events etc...)
return rootView;
}
}
HomeRecyclerFragment
public class HomeRecyclerFragment extends Fragment {
RecyclerView recyclerView;
public static ArrayList<Model> mArrayList =new ArrayList<>();
Fragment fragment;
FragmentTransaction fragmentTransaction;
public static HomeRecyclerFragment newInstance(ArrayList<Model> arrayList){
HomeRecyclerFragment fragment = new HomeRecyclerFragment();
mArrayList = arrayList;
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home_recycler_view,null);
recyclerView = (RecyclerView)rootView.findViewById(R.id.card_recycler_view);
recyclerView.setHasFixedSize(true);
//to make horizontal or vertical listview using recyclerview
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
RecyclerView.Adapter adapter = new HomeRecyclerAdapter(getActivity(), mArrayList);
recyclerView.setAdapter(adapter);
recyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
GestureDetector gestureDetector = new GestureDetector(getContext(), new GestureDetector.SimpleOnGestureListener() {
#Override public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if(child != null && gestureDetector.onTouchEvent(e)) {
Credentials.selectedPolititian = rv.getChildAdapterPosition(child);
Intent intent = new Intent(getContext(), PersonDetailActivity.class);
intent.putExtra("Class","HomeActivity");
intent.putExtra("array",mArrayList);
startActivity(intent);
getActivity().finish();
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
return rootView;
}
}
HomeRecyclerAdapter
public class HomeRecyclerAdapter extends RecyclerView.Adapter<HomeRecyclerAdapter.ViewHolder> {
private ArrayList<Model> profiles;
Context mContext;
public HomeRecyclerAdapter(Context context, ArrayList<Model> profile) {
this.profiles = profile;
this.mContext = context;
}
#Override
public HomeRecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_fragment_home_recycler, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(HomeRecyclerAdapter.ViewHolder viewHolder, int i) {
viewHolder.name.setText(profiles.get(i).getmName());
int length= profiles.get(i).getmDepartment().size();
int k;
String res ="";
for (k=0;k<length;k++){
res = res + profiles.get(i).getmDepartment().get(k)+"\n";
}
viewHolder.department.setText(res);
}
#Override
public int getItemCount() {
return profiles.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView name, department;
//private ImageView imageView;
public ViewHolder(View view) {
super(view);
// imageView = (ImageView) view.findViewById(R.id.image);
name = (TextView) view.findViewById(R.id.p_name);
department = (TextView) view.findViewById(R.id.p_department);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = getAdapterPosition();
}
});
}
}
}
check view fragments layout, avoid .jpeg images (use .png images)...
check the view pager with some simple fragments, if it work smoothly check the layout views..

Click On An Item In RecyclerView Contained In A Fragment To Open New Activity With Passed Data

I have a MainActivity and Three Fragments with recyclerViews inside the three fragments, the recyclerview contain two textviews, i want the user to click on the recyclerview and the text in should be passed on to the new activity, i am a little bit new so i would appreciate it if you can give me detailed code and some explanation.
I want to click on an item in the recyclerview and that should open a new activity, data(text) should be passed from the recyclerview to the new activity.
Here is my code for the HymnModel.java
public class HymnModel {
String title;
String song;
HymnModel(String title, String song){
this.title=title;
this.song=song;
}
public String getTitle() {return title;
}
public String getSong() {
return song;
}
}
Here is the code for ItemVeiwHolder.java
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
import com.tutorialsbuzz.recyclerview.R;
public class ItemViewHolder extends RecyclerView.ViewHolder {
public TextView title_textview;
public TextView song_textview;
public ItemViewHolder(View itemView) {
super(itemView);
itemView.setClickable(true);
title_textview = (TextView) itemView.findViewById(R.id.song_title);
song_textview = (TextView) itemView.findViewById(R.id.song);
}
public void bind(HymnModel hymnModel) {
title_textview.setText(hymnModel.getTitle());
song_textview.setText(hymnModel.getSong());
}
}
Here is my Adapter class
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.tutorialsbuzz.recyclerview.R;
import java.util.ArrayList;
import java.util.List;
public class RVAdapter extends RecyclerView.Adapter<ItemViewHolder> {
private List<HymnModel> mCountryModel;
private List<HymnModel> mOriginalCountryModel;
public RVAdapter(List<HymnModel> mCountryModel) {
this.mCountryModel = mCountryModel;
this.mOriginalCountryModel = mCountryModel;
}
#Override
public void onBindViewHolder(ItemViewHolder itemViewHolder, int i) {
final HymnModel model = mCountryModel.get(i);
itemViewHolder.bind(model);
}
#Override
public ItemViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_row, viewGroup, false);
return new ItemViewHolder(view);
}
#Override
public int getItemCount() {
return mCountryModel.size();
}
public void setFilter(List<HymnModel> countryModels){
mCountryModel = new ArrayList<>();
mCountryModel.addAll(countryModels);
notifyDataSetChanged();
}
}
Here is the code for one my fragments
public class TabOneFragment extends Fragment implements SearchView.OnQueryTextListener {
private RecyclerView recyclerview;
private List<HymnModel> mHymnModel;
private RVAdapter adapter;
#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.tab_one_fragment, container, false);
recyclerview = (RecyclerView) view.findViewById(R.id.recyclerview);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerview.setLayoutManager(layoutManager);
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setHasOptionsMenu(true);
int numOfSongs = 32;
DisplayMetrics metrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
int height = metrics.heightPixels;
int width = metrics.widthPixels;
String [] titles = {HymnTitles.hymnTitle1, HymnTitles.hymnTitle2, HymnTitles.hymnTitle3, HymnTitles.hymnTitle4, HymnTitles.hymnTitle5,
HymnTitles.hymnTitle6, HymnTitles.hymnTitle7, HymnTitles.hymnTitle8, HymnTitles.hymnTitle9, HymnTitles.hymnTitle10, HymnTitles.hymnTitle11,
HymnTitles.hymnTitle12};
String [] songs = {Hymns.hymn1.substring(width/5), Hymns.hymn2, Hymns.hymn3, Hymns.hymn4, Hymns.hymn5, Hymns.hymn6, Hymns.hymn7, Hymns.hymn8, Hymns.hymn9, Hymns.hymn10, Hymns.hymn11, Hymns.hymn12};
mHymnModel = new ArrayList<>();
for (int i = 0; i < titles.length; i++) {
mHymnModel.add(new HymnModel(i + "." + " " + titles[i], " " + songs[i]));
}
adapter = new RVAdapter(mHymnModel);
recyclerview.setAdapter(adapter);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_main, menu);
final MenuItem item = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(this);
MenuItemCompat.setOnActionExpandListener(item,
new MenuItemCompat.OnActionExpandListener() {
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
// Do something when collapsed
adapter.setFilter(mHymnModel);
return true; // Return true to collapse action view
}
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
// Do something when expanded
return true; // Return true to expand action view
}
});
}
#Override
public boolean onQueryTextChange(String newText) {
final List<HymnModel> filteredModelList = filter(mHymnModel, newText);
adapter.setFilter(filteredModelList);
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
private List<HymnModel> filter(List<HymnModel> models, String query) {
query = query.toLowerCase();
final List<HymnModel> filteredModelList = new ArrayList<>();
for (HymnModel model : models) {
final String text = model.getSong().toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
}
}
My MainActivity
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private int[] tabIcons = {
R.drawable.ic_action_person,
R.drawable.ic_action_group,
R.drawable.ic_action_call
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tablayout);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new TabOneFragment(), "Tab 1");
adapter.addFragment(new TabTwoFragment(), "Tab 2");
adapter.addFragment(new TabThreeFragment(), "Tab 3");
viewPager.setAdapter(adapter);
}
}
And lastly my ViewPageAdapter
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
}
Thank You.
Create an interface
public interface OnHymnClickListener {
void onHymnClick(HymnModel hymnModel);
}
Pass the listener to the adapter
public class RVAdapter extends RecyclerView.Adapter<ItemViewHolder> {
private OnHymnClickListener listener;
public void setListener(OnHymnClickListener listener) {
this.listener = listener;
}
#Override
public void onBindViewHolder(ItemViewHolder itemViewHolder, int i) {
final HymnModel model = mCountryModel.get(i);
itemViewHolder.bind(model);
itemViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(listener != null) {
listener.onHymnClick(model);
}
}
});
}
}
Let your fragment implement it
public class TabOneFragment extends Fragment implements SearchView.OnQueryTextListener, OnHymnClickListener {
#Override
public void onHymnClick(HymnModel hymnModel) {
//put data to bundle and startActivity
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
adapter = new RVAdapter(mHymnModel);
adapter.setListener(this);
recyclerview.setAdapter(adapter);
}
}
Hello first of all you always want to start your activity from activity or fragment.
Never start it from adapter.
So in your adapter constructor add this
public AdapterName(......,Context context){
...your code.
this.mContext=context;
}
pass context there.
and than inside this method
public ItemViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(mContext instanceof YourActivityName){
((YourActivityName)mContext).yourDesiredMethod();
}
}
});

ViewPager does not updating the Fragment with updated content

i am suffering for 3 days. I'm using the View Pager from the compatibility library. I have successfully got it displaying several views .My Problem is that when i swap view then do not update data by fragment in its recycler view .But when i closed my application then opened fragments display update content by recycler view.i use all method like setnotifydatachanged() and many more but Fragment in viewpager does not update content.Thankx For any help
this is my main activity
public class MainActivity extends AppCompatActivity {
private ViewPager viewPager;
private TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("");
setSupportActionBar(toolbar);
viewPager = (ViewPager) findViewById(R.id.viewPager);
viewPager.setAdapter(new MainAdapter(getSupportFragmentManager(),MainActivity.this));
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
addIconsToTab();
}
private void addIconsToTab() {
for (int i = 0; i < tabLayout.getTabCount(); i++) {
int drwableId = -1;
switch (i) {
case 0:
drwableId = R.drawable.home;
break;
case 1:
drwableId = R.drawable.favourite;
break;
case 2:
drwableId = R.drawable.watchlater;
break;
}
tabLayout.getTabAt(i).setIcon(drwableId);
}
}
}
this is my main adapter
public class MainAdapter extends FragmentPagerAdapter {
Context mContext;
public MainAdapter(FragmentManager fm, Context context) {
super(fm);
mContext=context;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new AllVideos();
case 1:
return new Favourite();
case 2:
return new WatchLater();
default:
return null;
}
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return mContext.getString(R.string.All_Videos);
case 1:
return mContext.getString(R.string.Favourite);
case 2:
return mContext.getString(R.string.Wtach_Later);
default:
return null;
}
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
And this is my Fragment
public class Favourite extends Fragment {
private RecyclerView mRecyclerView;
private FavouriteAdapter favouriteAdapter;
RecyclerView.LayoutManager layoutManager;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_recyclerview_carpaccio, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
layoutManager = new LinearLayoutManager(getActivity());
DatabaseHandler db = new DatabaseHandler(getActivity());
mRecyclerView.setLayoutManager(layoutManager);
mRecyclerView.setHasFixedSize(true);
List<VideoInformationDataModel> videoinfo = db.getAllFavourite();
favouriteAdapter = new FavouriteAdapter(getActivity(),videoinfo);
mRecyclerView.setAdapter(favouriteAdapter);
favouriteAdapter.notifyDataSetChanged();
Toast.makeText(getActivity(),videoinfo.size()+"",Toast.LENGTH_SHORT).show();
}
}
And this is fragmentAdapter
public class FavouriteAdapter extends RecyclerView.Adapter<FavouriteAdapter.MyViewHolder>
{
private int[] maid = {R.id.deleteoption};
Context context;
private List<VideoInformationDataModel> videoInformationDataModels;
String videoid1;
private FavouriteAdapter favouriteAdapter;
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView title;
View root;
protected ImageLoader img_uni_imageLoader;
DatabaseHandler db = new DatabaseHandler(context);
ImageView networkImage,options;
TextView Duration,Videoname;
public MyViewHolder(View view) {
super(view);
root = itemView.findViewById(R.id.videoImage);
Duration= (TextView) itemView.findViewById(R.id.duration);
Videoname= (TextView) itemView.findViewById(R.id.VideoName);
networkImage= (ImageView) itemView. findViewById(R.id.imgNetwork);
options= (ImageView) itemView.findViewById(R.id.deleteoption);
options.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (maid[0] == view.getId()) {
PopupMenu popup = new PopupMenu(context, options);
popup.getMenuInflater().inflate(R.menu.deleteoption, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
switch (menuItem.getItemId())
{
case R.id.delete:
int pos = getAdapterPosition () ;
videoid1= videoInformationDataModels.get(pos).getVideoid();
db.deleteFavourite(videoid1);
videoInformationDataModels.remove(pos);
notifyItemRemoved(pos);
notifyItemRangeChanged(pos, getItemCount());
return true;
}
return false;
}
});
popup.show();
}
}
}
public FavouriteAdapter(Context context, List<VideoInformationDataModel> videoinformation) {
this.videoInformationDataModels = videoinformation;
this.context=context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.favouritesingleitem, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
holder.Duration.setText(videoInformationDataModels.get(position).getVideoduratio n());
holder.Videoname.setText(videoInformationDataModels.get(position).getVideoinfo() );
holder.img_uni_imageLoader = ImageLoader.getInstance();
.img_uni_imageLoader.init(ImageLoaderConfiguration.createDefault(context));
holder.img_uni_imageLoader.displayImage(videoInformationDataModels.get(position) .getVideoimg(), holder.networkImage);
holder.root.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, YouTube.class);
Bundle extras = new Bundle();
String Videtittle = videoInformationDataModels.get(position).getVideoinfo();
String videodes = videoInformationDataModels.get(position).getFld_description();
String duration = videoInformationDataModels.get(position).getVideoduration();
String videoid = videoInformationDataModels.get(position).getVideoid();
extras.putString("Videtittle", Videtittle);
extras.putString("videodes", videodes);
extras.putString("duration", duration);
extras.putString("videoid", videoid);
intent.putExtras(extras);
context.startActivity(intent);
}
});
}
#Override
public int getItemViewType(int position)
{
return position;
}
public int getItemCount() {
return videoInformationDataModels.size();
}
}
I am not very sure what issue you are facing, but can you try once by replacing the FragmentPagerAdapter by FragmentStatePagerAdapter (extending by MainAdapter).
I don't clearly understand exactly what your issue is, It might be a result of wrong implementation. But if you have tried favouriteAdapter.notifyDataSetChanged(); and it still doesn't refresh.
You might as well remove the view, refresh it and add the view back and see if that works.
ViewGroup parent = (ViewGroup) viewPager.getParent(); // get the view parent
if (parent != null) {
parent.removeView(viewPager); // remove the view
viewPager.getAdapter().notifyDataSetChanged(); // notify that the data has changed
parent.addView(viewPager); // then, re-add the view
}

Categories

Resources