ViewPager work not correctly - android

Can not implement so: if tap to image in MainActivity - this image has to open in PreviewActivity full screen and there I can make scroll right and left use ViewPager to browse the next or previous image in the array. Now, when i tap to image, and if use in PageFragment - resultView.setImageResource(pageNumber); - then always open firts image in my array, and if use resultView.setImageURI(source); - then open true image but if swipe - always show this one image.
PageFragment - probably in this class something wrong
public class PageFragment extends Fragment {
private static final String ARGUMENT_PAGE_NUMBER = "id_test";
private int pageNumber;
private Uri source;
static PageFragment newInstance(int page) {
PageFragment pageFragment = new PageFragment();
Bundle arguments = new Bundle();
arguments.putInt(ARGUMENT_PAGE_NUMBER, page);
pageFragment.setArguments(arguments);
return pageFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent i = getActivity().getIntent();
pageNumber = i.getExtras().getInt("id_test");
source = Uri.parse("android.resource://com.test.nico/drawable/" + Images.loadImages[pageNumber]);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_view_pager, null);
ImageView resultView = (ImageView) view.findViewById(R.id.result_image);
// resultView.setImageURI(source);
pageNumber = getArguments().getInt(ARGUMENT_PAGE_NUMBER);
resultView.setImageResource(pageNumber);
return view;
}
}
MainActivity
public class MainActivity extends AppCompatActivity {
private Context mContext;
private RecyclerView mRecyclerView;
private ImageAdapter mImageAdapter;
private RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = getApplicationContext();
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mImageAdapter = new ImageAdapter(mContext, Images.loadImages);
mLayoutManager = new GridLayoutManager(this, 2);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mImageAdapter);
}
}
PreviewActivity
public class PreviewActivity extends FragmentActivity {
private ViewPager viewPager;
private PagerAdapter pagerAdapter;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_preview);
viewPager = (ViewPager) findViewById(R.id.preview_pager);
pagerAdapter = new PreviewPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(pagerAdapter);
}
}
ImageAdapter
class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.Holder> {
private int[] mItemList;
private Context mContext;
ImageAdapter(Context context, int[] itemList) {
this.mContext = context;
this.mItemList = itemList;
}
#Override
public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.view_list, null);
return new Holder(layoutView);
}
#Override
public void onBindViewHolder(Holder holder, int position) {
Picasso.with(mContext).load(Images.loadImages[position]).placeholder(R.drawable.ic_stub).resize(400, 750).into(holder.view);
}
#Override
public int getItemCount() {
return this.mItemList.length;
}
class Holder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView view;
Holder(View itemView) {
super(itemView);
mContext = itemView.getContext();
view = new ImageView(mContext);
view = (ImageView) itemView.findViewById(R.id.recycler_view);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
final Intent intent = new Intent(mContext, PreviewActivity.class);
intent.putExtra("id_test", getAdapterPosition());
mContext.startActivity(intent);
}
}
}
PreviewPagerAdapter
class PreviewPagerAdapter extends FragmentStatePagerAdapter {
private int imagesCount = Images.loadImages.length;
private int[] images = Images.loadImages;
PreviewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return imagesCount;
}
#Override
public Fragment getItem(int position) {
return PageFragment.newInstance(images[position]);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}

In your PreviewActivity you have to "jump" to the position you passed.
viewpager.setCurrentItem(getIntent().getExtras().getInt("id_test"));

Related

No Data in Recycler View in Fragment

I am building an Android Application which have Tab Layout in which there are Fragments and in Fragment I am displaying some value.
I have just only added hardcoded values to test the layout, but even these are not visible in the fragment.
Here is the code for ViewPagerAdapter:
public class FavouriteViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> favouriteFragmentList = new ArrayList<>(); // this line can cause crashes
private final List<String> favouriteFragmentListTitles = new ArrayList<>();
public FavouriteViewPagerAdapter(#NonNull FragmentManager fm, int behavior) {
super(fm, behavior);
}
#NonNull
#Override
public Fragment getItem(int position) {
return favouriteFragmentList.get(position);
}
#Override
public int getCount() {
return favouriteFragmentListTitles.size();
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return favouriteFragmentListTitles.get(position);
}
public void AddFragment(Fragment fragment, String title) {
favouriteFragmentList.add(fragment); // this line can cause crashes
favouriteFragmentListTitles.add(title);
}
}
I have tried the answers available already none of them solves my problem.
I debugged the application and my RecyclerViewAdapter is not even called, very strange. I have done this many time but this never happened.
Here is my code for RecyclerViewAdapter :
public class ProductsRecyclerAdapter extends RecyclerView.Adapter<ProductsRecyclerAdapter.viewHolder> {
Context context;
private List<FavouriteProducts> favouriteProductsData;
public ProductsRecyclerAdapter(Context context, List<FavouriteProducts> favouriteProductsData) {
this.context = context;
this.favouriteProductsData = favouriteProductsData;
}
#NonNull
#Override
public viewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.single_favourite_product_item, parent, false);
viewHolder vHolder = new viewHolder(v);
return vHolder;
}
#Override
public void onBindViewHolder(#NonNull viewHolder holder, int position) {
holder.product_name.setText(favouriteProductsData.get(position).getProduct_name());
holder.product_price.setText(favouriteProductsData.get(position).getProduct_price());
holder.product_image.setImageResource(favouriteProductsData.get(position).getProduct_image());
Toast.makeText(context,favouriteProductsData.get(position).getProduct_price() , Toast.LENGTH_SHORT).show();
/*holder.heart_button.setOnLikeListener(new OnLikeListener() {
#Override
public void liked(LikeButton likeButton) {
showSuccessToast(context,"Liked");
}
#Override
public void unLiked(LikeButton likeButton) {
showSuccessToast(context,"Unliked");
}
});*/
}
#Override
public int getItemCount() {
return favouriteProductsData.size();
}
static class viewHolder extends RecyclerView.ViewHolder {
MaterialTextView product_name, product_price;
ImageView product_image;
LikeButton heart_button;
public viewHolder(#NonNull View itemView) {
super(itemView);
product_name = itemView.findViewById(R.id.product_name);
product_price = itemView.findViewById(R.id.product_price);
product_image = itemView.findViewById(R.id.product_image);
heart_button = itemView.findViewById(R.id.heart_button);
}
}
}
I am not getting any errors but after I check adapter is not even called. Some help will be really helpful.
Fragment Code:
public class FavouriteProductsFragment extends Fragment {
View v;
private List<FavouriteProducts> productList;
public FavouriteProductsFragment() {
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
productList = new ArrayList<>();
productList.add(new FavouriteProducts("All Weather", "200/Ltr", R.drawable.all_weather));
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.products_favourite_fragment, container, false);
RecyclerView productRecyclerView = v.findViewById(R.id.favourite_products_rv);
ProductsRecyclerAdapter recyclerAdapter = new ProductsRecyclerAdapter(getContext(), productList);
productRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
productRecyclerView.hasFixedSize();
productRecyclerView.setAdapter(recyclerAdapter);
return v;
}
}
productList = new ArrayList<>();
productList.add(new FavouriteProducts("All Weather", "200/Ltr",R.drawable.all_weather));
recyclerAdapter.notifyDataSetChanged()
RecyclerView productRecyclerView = v.findViewById(R.id.favourite_products_rv);
ProductsRecyclerAdapter recyclerAdapter = new ProductsRecyclerAdapter(getContext(), productList);
productRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
productRecyclerView.hasFixedSize();
productRecyclerView.setAdapter(recyclerAdapter);
You need to add
RecyclerView productRecyclerView = v.findViewById(R.id.favourite_products_rv);
ProductsRecyclerAdapter recyclerAdapter = new ProductsRecyclerAdapter(getContext(), productList);
productRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
productRecyclerView.hasFixedSize();
productRecyclerView.setAdapter(recyclerAdapter);
productList = new ArrayList<>();
productList.add(new FavouriteProducts("All Weather", "200/Ltr",R.drawable.all_weather));recyclerAdapter.notifyDataSetChanged()
and Remove oncreate() method
try productRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); befor setting adapter in recyclerview.
Step1: First Create one or MoreFragment For Your ViewPager and in This Fragment Add your Recyclerview Code as per Your Requirement.
Like Below Code
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_whatsapp_image, container, false);
context = getActivity();
((HomeActivity) getActivity()).toolbar.setVisibility(View.VISIBLE);
setupView(root);
return root;
}
private void setupView(ViewGroup root) {
recyclerView = (RecyclerView) root.findViewById(R.id.recyclerViewImage);
progressBar=root.findViewById(R.id.simpleProgressBar);
txtinfo=root.findViewById(R.id.txtinfo);
setUPList();
}
Step2: Then Create ViewPager Adapter for Your TabLayout
public class ViewPagerAdapter extends FragmentPagerAdapter {
public ViewPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
#Override
public Fragment getItem(int position) {
if(position == 0) return new AudioFragment();
if(position == 1) return new VideoFragment();
if(position == 2) return new ImageFragment();
throw new IllegalStateException("Unexpected position " + position);
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
if(position == 0) return "Audio";
if(position == 1) return "Video";
if(position == 2) return "Image";
throw new IllegalStateException("Unexpected position " + position);
}
}
Step3 : Then Call Your SetupViewpager Method in Your Oncreate method of your Activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar=findViewById(R.id.toolbar);
viewPager=findViewById(R.id.viewpager);
tabLayout=findViewById(R.id.tabs);
//add toolbar
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setupViewPager(viewPager);
tabLayout.setupWithViewPager(viewPager);
setTabIcons();
}
NOTE: You Can Download ViewPager Code from Below Link.Click Here to View and Download

Using ViewPager with fragments

I have a list of images that I display in a ImageListFragment fragment of my MainActivity, clicking on one of those images should open that image as ImageDisplayFragment inside FooPager. I have created a FooPager activity so that when the image the user clicked in ImageListFragment is displayed, the user can then swipe and view all images. The problem I have is that when I click on the image I want to view in ImageListFragment, it displays the very first image in my /drawable directory instead of the actual image I click on. I am not sure what I am doing wrong.
Here is ImageListFragment:
public class ImageListFragment extends Fragment {
private int[] mImageResIds;
private OnGalleryImageSelected mListener;
public static ImageListFragment newInstance() {
return new ImageListFragment();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
mListener = (OnGalleryImageSelected) context;
final Resources resources = context.getResources();
final TypedArray typedArray = resources.obtainTypedArray(R.array.images);
final int imageCount = 18;
mImageResIds = new int[imageCount];
for (int i = 0; i < imageCount; i++) {
mImageResIds[i] = typedArray.getResourceId(i, 0);
}
typedArray.recycle();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_image_list, container, false);
final Activity activity = getActivity();
final RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(activity));
recyclerView.setAdapter(new GalleryImageAdapter(activity));
return view;
}
class GalleryImageAdapter extends RecyclerView.Adapter<ViewHolder> {
private LayoutInflater mLayoutInflater;
public GalleryImageAdapter(Context context) {
mLayoutInflater = LayoutInflater.from(context);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
return new ViewHolder(mLayoutInflater
.inflate(R.layout.recycler_view, viewGroup, false));
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, final int position) {
final int imageResId = mImageResIds[position];
viewHolder.setData(imageResId);
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println(imageResId);
Intent intent = FooPager.newIntent(getActivity(),imageResId);
startActivity (intent);
// mListener.OnGalleryImageSelected(imageResId);
}
});
}
#Override
public int getItemCount() {
return mImageResIds.length;
}
}
class ViewHolder extends RecyclerView.ViewHolder {
private ImageView mImageView;
private ViewHolder(View itemView) {
super(itemView);
mImageView = (ImageView) itemView.findViewById(R.id.gallery_image);
}
private void setData(int imageResId) {
mImageView.setImageResource(imageResId);
}
}
public interface OnGalleryImageSelected {
void OnGalleryImageSelected(int imageResId);
}
}
This is what my pager activity looks like:
public class FooPager extends FragmentActivity{
public static final String EXTRA_IMAGE_ID = "meow";
private ViewPager mViewPager;
private Integer images [] = {
R.drawable.a, R.drawable.b,R.drawable.c,R.drawable.d,R.drawable.e,
R.drawable.f, R.drawable.g, R.drawable.h,R.drawable.i,R.drawable.j,
R.drawable.k, R.drawable.l, R.drawable.m,R.drawable.n,R.drawable.o,
R.drawable.p, R.drawable.q, R.drawable.r
};
public static Intent newIntent(Context packageContext, int id) {
Intent intent = new Intent(packageContext,FooPager.class);
intent.putExtra(EXTRA_IMAGE_ID,id);
return intent;
}
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView(R.layout.activity_image_pager);
mViewPager = (ViewPager) findViewById (R.id.activity_image_pager_view_pager);
FragmentManager fragmentManager = getSupportFragmentManager ();
mViewPager.setAdapter(new FragmentStatePagerAdapter(fragmentManager) {
#Override
public Fragment getItem(int position) {
System.out.println(images[position]);
int id = images[position];
return ImageDetailFragment.newInstance(id);
}
#Override
public int getCount() {
return images.length;
}
});
for (int i=0; i < images.length; i++) {
mViewPager.setCurrentItem(i);
break;
}
}
}
And then ImageDetailFragmentfragment:
public class ImageDetailFragment extends Fragment {
private static final String IMAGE_ID = "imageResId";
public static ImageDetailFragment newInstance(int imageResId) {
final Bundle args = new Bundle();
args.putInt(IMAGE_ID, imageResId);
final ImageDetailFragment fragment = new ImageDetailFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_image_details, container, false);
final ImageView imageView = (ImageView) view.findViewById(R.id.gallery_image);
final Bundle args = getArguments();
imageView.setImageResource(args.getInt(IMAGE_ID));
return view;
}
}
How do I fix my FooPager activity so that it actually displays the image I clicked on from within ImageListFragment?
it displays the very first image in my /drawable directory instead of
the actual image I click on
In your FooPager Activity, this will show the first item in your viewpager. That the reason why it display the first item (i = 0 and break)
for (int i=0; i < images.length; i++) {
mViewPager.setCurrentItem(i);
break;
}
YOu need to send the position from ImageListFragment to FooPager, not imageResId and set mViewPager.setCurrentItem(position). If you send imageResId, you need to browse in you list images
for (int i=0; i < images.length; i++) {
if(images[i] == imageResId) {
mViewPager.setCurrentItem(i);
break;
}
}

RecyclerView.Adapter onClick ClassCastException

I'm trying to load a Fragment inside an Activity and I was able to load the items. Now, what I want to do is to click the items on the list and pass it to the DetailsView.class which is a Fragment that will receive the bundle data. But everytime I click on the item I always get an error. Below is the logcat error that I'm getting
Logcat Error
java.lang.ClassCastException: com.test.example.LoadAFragment cannot be cast to com.test.example.MainActivity at com.test.example.controller.DetailsView.onCreateView(DetailsView.java:178)
line java:178
MainActivity activity = ((MainActivity) getActivity());
LoadAFragment.class
public class LoadAFragment extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.load_layout);
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
MyFragment myFragment = new MyFragment();
fragmentTransaction.add(R.id.frame_container, myFragment);
fragmentTransaction.commit();
}
}
RecyclerView Adapter
public class MyFragmentAdapter extends RecyclerView.Adapter <RecyclerView.ViewHolder> {
private List<ListModel> list;
private Context mContext = null;
private DetailsView detailsView;
public MyFragmentAdapter(Context context, List<ListModel> list) {
mContext = context;
this.list = list;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
final ListModel list = list.get(holder.getAdapterPosition());
String mID = list.getID();
final int id = Integer.valueOf(mID );
((MyViewHolder) holder).title.setText(list.getTitle());
((MyViewHolder) holder).caption.setText(list.getCaption());
((MyViewHolder) holder).itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager manager = ((Activity) mContext).getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
Bundle bundle = new Bundle();
bundle.putInt("id", id);
detailsView = new DetailsView ();
detailsView.setTitle(title);
detailsView.setArguments(bundle);
transaction.replace(R.id.frame_container, detailsView);
transaction.addToBackStack("list");
transaction.commit();
}
});
}
#Override
public int getItemCount() {
return (list != null? list.size():0);
}
private class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title;
public TextView caption;
MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.title);
caption = (TextView) itemView.findViewById(R.id.caption );
}
}
}
MyFragment.class
public class MyFragment extends Fragment{
List<ListModel> list;
RecyclerView mRecyclerView;
MyFragmentAdapter myFragmentAdapter;
ListDb listDb;
public MyFragment() {}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View rootView = inflater.inflate(R.layout.fragment, container, false);
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerview);
listDb = new ListDb(getActivity());
list = listDb.getList();
myFragmentAdapter = new MyFragmentAdapter (getActivity(), list);
mRecyclerView.setAdapter(myFragmentAdapter);
return rootView;
}
}
DetailsView.class
public class DetailsView extends Fragment{
private MainActivity activity;
Bundle b;
public DetailsView() {}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null)
b = savedInstanceState.getBundle("save");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
activity = ((MainActivity) getActivity());
return rootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);}
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (b != null) {
setTitle(b.getString("title"));
id = b.getInt("id");
}
if (b != this.getArguments().getInt("id")) {
b = this.getArguments().getInt("id");
//get data from id
}
}
}
The best and cleanest solution would be to pass a listener to the adapter.
public interface MyClickListener {
void onResult(Data data);
}
public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public MyAdapter(Context context, MyClickListener listener, List<ListModel> list) {
mContext = context;
this.list = list;
this.listener = listener;
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
Data data = getData(position);
//bind views
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.onResult(data);
}
});
}
}
Have the Fragment implement the listener and create the new adapter.
public class MyFragment extends Fragment implements MyClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyAdapter adapter = new MyAdapter(getActivity(),this,listData);
}
#Override
public void onResult(Data data) {
//do work after an item is clicked
}
}
Cast getActivity() to 'LoadAFragment' instead of 'MainActivity' in DetailsView.java. This way:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
activity = ((LoadAFragment) getActivity());
return rootView;
}
try this way to get Reference of MainActivity in your DetailViewFragment
private MainActivity parent_activity;
#Override
public void onAttach(Activity activity)
{
parent_activity = (MainActivity.class.isAssignableFrom(activity
.getClass())) ? (MainActivity) activity : null;
super.onAttach(activity);
}
#Override
public void onDetach()
{
parent_activity = null;
super.onDetach();
}
Now use the reference using:
if(parent_activity!=null)
{
parent_activity.someMethod();
}

No adapter attached; skipping layout Only displays 1st content

I am new at android programming and I getting the error "No adapter attached; skipping layout". My app runs but when I click to open my fragment wich have an cardview inside, only displays the first content of my ArrayList.
I have been following this tutorial: https://code.tutsplus.com/tutorials/getting-started-with-recyclerview-and-cardview-on-android--cms-23465, but I am doing in a different way. I am using fragments instead of activity, but I think that is not a problem. So, here I have my Activity:
public class Av_ninja extends AppCompatActivity {
TabLayout tabLayout;
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_av_ninja);
viewPager = (ViewPager) findViewById(R.id.viewPager);
viewPager.setAdapter(new CustomAdapter(getSupportFragmentManager(), getApplicationContext()));
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
private class CustomAdapter extends FragmentPagerAdapter{
private String fragmentes [] = {"Info","Abilitities"};
public CustomAdapter(FragmentManager suppFragmentManager, Context applicaContext){
super(suppFragmentManager);
}
#Override
public Fragment getItem(int position){
switch (position){
case 0:
return new Fragment1();
case 1:
return new Fragment2();
default:
return null;
}
}
#Override
public int getCount(){
return fragmentes.length;
}
#Override
public CharSequence getPageTitle(int position) {
return fragmentes[position];
}
}
}
Fragment
public class Fragment1 extends Fragment {
ImageView Icons;
TextView Titulos;
TextView Textos;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
// return inflater.inflate(R.layout.frag1,container,false);
View rootView = inflater.inflate(R.layout.card_ninja_info,container,false);
Icons = (ImageView) rootView.findViewById(R.id.Icons);
Titulos = (TextView) rootView.findViewById(R.id.Titulos);
Textos = (TextView) rootView.findViewById(R.id.Textos);
Icons.setImageResource(R.drawable.offenseicon);
Titulos.setText("Role");
Textos.setText("Scout");
return rootView;
}
}
RecyclerView
public class RecyclerViewAv extends Fragment{
private List<Heroi> herois;
private RecyclerView rv;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
//return inflater.inflate(R.layout.frag2,container,false);
View rootView = inflater.inflate(R.layout.card_ninja_info,container,false);
rv = (RecyclerView)rootView.findViewById(R.id.rv_frag1);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
rv.setLayoutManager(llm);
rv.setHasFixedSize(true);
initializeData();
initializeAdapter();
return rootView;
}
private void initializeData(){
herois = new ArrayList<>();
herois.add(new Heroi(R.drawable.offenseicon, "Role", "Scout"));
herois.add(new Heroi(R.drawable.identityicon, "Identity", "Genji Shimada"));
herois.add(new Heroi(R.drawable.workicon, "Work", "Adventurer"));
herois.add(new Heroi(R.drawable.localizationicon, "Base of Operation", "Nepal"));
herois.add(new Heroi(R.drawable.empresaicon, "Affiliation", "Shiamda Clan"));
herois.add(new Heroi(R.drawable.ageicon, "Age", "27"));
herois.add(new Heroi(R.drawable.healthicon, "Health", "100"));
}
private void initializeAdapter(){
RVAdapter adapter = new RVAdapter(herois);
rv.setAdapter(adapter);
}
}
Adapter
public class RVAdapter extends RecyclerView.Adapter<RVAdapter.HeroiViewHolder>{
public static class HeroiViewHolder extends RecyclerView.ViewHolder{
CardView cv;
ImageView Icons;
TextView Titulos;
TextView Textos;
public HeroiViewHolder(View itemView) {
super(itemView);
cv = (CardView)itemView.findViewById(R.id.cv);
Icons = (ImageView)itemView.findViewById(R.id.Icons);
Titulos = (TextView)itemView.findViewById(R.id.Titulos);
Textos = (TextView)itemView.findViewById(R.id.Textos);
}
}
List<Heroi> herois;
RVAdapter(List<Heroi> herois){
this.herois=herois;
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView){
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public RVAdapter.HeroiViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item, viewGroup, false);
HeroiViewHolder hvh = new HeroiViewHolder(v);
return hvh;
}
#Override
public void onBindViewHolder(HeroiViewHolder holder, int position) {
holder.Icons.setImageResource(herois.get(position).photoId);
holder.Titulos.setText(herois.get(position).tit);
holder.Textos.setText(herois.get(position).res);
}
#Override
public int getItemCount() {
return herois.size();
}
}
class Heroe
public class Heroi {
int photoId;
String tit;
String res;
public Heroi(int photoId, String tit, String res) {
this.photoId = photoId;
this.tit = tit;
this.res = res;
}
}
Thanks in advance!
Here you could do following changes to make it properly :
1) Update your onCreateView method
private RVAdapter rvAdapter;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
//return inflater.inflate(R.layout.frag2,container,false);
View rootView = inflater.inflate(R.layout.card_ninja_info,container,false);
rv = (RecyclerView)rootView.findViewById(R.id.rv_frag1);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
// Added here
llm.setOrientation(LinearLayoutManager.VERTICAL);
rv.setHasFixedSize(true); // Here we changed order you should call it first before setting LayoutManager
rv.setLayoutManager(llm);
//Set empty adapter and pass only context if you will needed inside it
rvAdapter = new RVAdapter(getActivity());
rv.setAdapter(rvAdapter);
initializeData();
initializeAdapter();
return rootView;
}
2) Create method in your adapter class to update your content list
public void updateList(List<Heroi> herois){
this.herois = herois;
notifyDataSetChanged();
}
3) Only update your contentList inside initializeAdapter method(No need to set adapter again)
private void initializeAdapter(){
rvAdapter.updateList(herois);
}
That's it!
Update your adapter as per below :
public class RVAdapter extends RecyclerView.Adapter<RVAdapter.HeroiViewHolder>{
List<Heroi> herois;
public static class HeroiViewHolder extends RecyclerView.ViewHolder{
CardView cv;
ImageView Icons;
TextView Titulos;
TextView Textos;
Context context;
public HeroiViewHolder(View itemView) {
super(itemView);
cv = (CardView)itemView.findViewById(R.id.cv);
Icons = (ImageView)itemView.findViewById(R.id.Icons);
Titulos = (TextView)itemView.findViewById(R.id.Titulos);
Textos = (TextView)itemView.findViewById(R.id.Textos);
}
}
RVAdapter(Context context){
this.context = context;
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView){
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public RVAdapter.HeroiViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item, viewGroup, false);
HeroiViewHolder hvh = new HeroiViewHolder(v);
return hvh;
}
#Override
public void onBindViewHolder(HeroiViewHolder holder, int position) {
holder.Icons.setImageResource(herois.get(position).photoId);
holder.Titulos.setText(herois.get(position).tit);
holder.Textos.setText(herois.get(position).res);
}
#Override
public int getItemCount() {
return herois.size();
}
public void updateList(List<Heroi> herois){
this.herois = herois;
notifyDataSetChanged();
}
}
Problem Solved I just deleted RecyclerView Class and putted it into Fragment1 class.
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
// return inflater.inflate(R.layout.frag1,container,false);
View rootView = inflater.inflate(R.layout.frag1,container,false);
rv = (RecyclerView)rootView.findViewById(R.id.rv_frag1);
LinearLayoutManager llm = new LinearLayoutManager(getContext());
// llm.setOrientation(LinearLayoutManager.VERTICAL);
// rv.setHasFixedSize(true);
rv.setLayoutManager(llm);
initializeData();
rvAdapter = new RVAdapter(herois);
rv.setAdapter(rvAdapter);
return rootView;
}
Thanks Anyway

Two fragment using same adapter in TabLayout not working

Only the first fragment is populated with the image, the second fragment is blank. I am using the same adapter for both fragments. I am not sure where is the problem.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mSectionsPagerAdapter.addFragment(PopularMoviesFragment.newInstance(SORT_POPULAR), "MOST POPULAR");
mSectionsPagerAdapter.addFragment(RatingMoviesFragment.newInstance(SORT_RATING), "TOP RATING");
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
public void switchToDetail(Intent intent){
startActivity(intent);
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
static class SectionsPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragments = new ArrayList<>();
private final List<String> mFragmentTitles = new ArrayList<>();
public SectionsPagerAdapter(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);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
}
}
First fragment
public static PopularMoviesFragment newInstance(String sort) {
PopularMoviesFragment fragment = new PopularMoviesFragment();
Bundle args = new Bundle();
args.putString("sort", sort);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sortOrder = getArguments().getString("sort");
mContext = getActivity();
if (savedInstanceState != null) {
mPopularList = savedInstanceState.getParcelableArrayList(POPULAR_LIST);
for (Movie m : mPopularList) {
Log.d(LOG_TAG, "onCreate: " + m.getTitle());
}
} else {
FetchPopularMovies pm = new FetchPopularMovies();
pm.execute(SORT_POPULAR);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View pView = inflater.inflate(R.layout.fragment_popular_movies, container, false);
mAdapter = new MoviePosterAdapter(mContext, mPopularList);
mProgressBar = (ProgressBar) pView.findViewById(R.id.movies_progress_bar);
RecyclerView mRecyclerView = (RecyclerView) pView.findViewById(R.id.my_recycler_view);
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 3, GridLayoutManager.VERTICAL, false);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
return pView;
}
Second fragment
public static RatingMoviesFragment newInstance(String sort) {
RatingMoviesFragment fragment = new RatingMoviesFragment();
Bundle args = new Bundle();
args.putString("sort", sort);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sortOrder = getArguments().getString("sort");
mContext = getActivity();
if (savedInstanceState != null) {
Log.d(LOG_TAG, "Has saved instance");
mRatingList = savedInstanceState.getParcelableArrayList(RATING_LIST);
} else {
FetchRatingMovies rm = new FetchRatingMovies();
rm.execute(SORT_RATING);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_rating_movies, container, false);
ratingAdapter = new MoviePosterAdapter(mContext, mRatingList);
mProgressBar = (ProgressBar) view.findViewById(R.id.movies_progress_bar);
RecyclerView mRecyclerView = (RecyclerView) view.findViewById(R.id.my_recycler_view);
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 3, GridLayoutManager.VERTICAL, false);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(ratingAdapter);
return view;
}
MoviePosterAdapter
public class MoviePosterAdapter extends RecyclerView.Adapter<MoviePosterAdapter.ViewHolder> {
private final String LOG_TAG = MoviePosterAdapter.class.getSimpleName();
final Context mContext;
private ArrayList<Movie> mDataset;
public static class ViewHolder extends RecyclerView.ViewHolder {
//public final View mView;
public final ImageView mImageView;
public ViewHolder(View view) {
super(view);
mImageView = (ImageView) view.findViewById(R.id.imageView);
}
}
// Provide a suitable constructor (depends on the kind of dataset)
public MoviePosterAdapter(Context context, ArrayList<Movie> myDataset) {
this.mContext = context;
mDataset = myDataset;
}
public void setMoviesData(ArrayList<Movie> moviesData){
mDataset = moviesData;
}
// Create new views (invoked by the layout manager)
#Override
public MoviePosterAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View v = LayoutInflater.from(mContext).inflate(R.layout.movie_poster, parent, false);
// set the view's size, margins, paddings and layout parameters
return new ViewHolder(v);
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
final Movie mMovie = mDataset.get(position);
//Creating URL for image
final String POSTER_BASE_URL = "http://image.tmdb.org/t/p/";
final String SIZE_PATH = "w185";
String IMG_PATH = mMovie.getImg();
//Loading image using Glide
Glide.with(holder.mImageView.getContext())
.load(POSTER_BASE_URL + SIZE_PATH + IMG_PATH)
.placeholder(R.color.grid_placeholder_bg)
.into(holder.mImageView);
holder.mImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(mContext, DetailActivity.class);
i.putExtra("id", mMovie.getId());
i.putExtra("title", mMovie.getTitle());
if (mContext instanceof MainActivity) {
MainActivity main= (MainActivity) mContext;
main.switchToDetail(i);
}
}
});
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return mDataset.size();
}
}
Please help me!
EDIT: Both the arrays are not empty. Here is the issue I think, only one fragment gets populated, maybe because there is some problem with the adapter(not sure). If I try to stop first fragment to get populated(commenting out the notifyDatasetChanged()), then the second fragment works fine.
The image wasn't populating in the second fragment because it was an issue with Glide library. Switched to Picasso. Works fine.
I checked your code and i found that everything is fine. I tried with dummy data so i am damn sure that the mistake is in your data or adapter where you are setting data. Just try once with dummy data so you will be more clear or if still you are getting blank screen then let me know.
Generally blank screen comes because of there is no data. so please check once..

Categories

Resources