onCreateView pager adapter [duplicate] - android

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
Attempt to invoke virtual method 'void androidx.viewpager.widget.ViewPager.setAdapter(androidx.viewpager.widget.PagerAdapter)' on a null object reference
I'm trying to implement sliding tab layout using android material design. But it gives me NullPointerException. Here is my code so far:
public class HomeFragment extends Fragment {
private HomeViewModel homeViewModel;
private List<Slide> listSlides;
private ViewPager slidePager;
private TabLayout indicator;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
homeViewModel =
ViewModelProviders.of(this).get(HomeViewModel.class);
View root = inflater.inflate(R.layout.fragment_home, container, false);
listSlides = new ArrayList<>();
listSlides.add(new Slide(R.drawable.a, "slide title"));
listSlides.add(new Slide(R.drawable.b, "slide title"));
final SliderPagerAdapter adapter = new SliderPagerAdapter(getContext(), listSlides);
homeViewModel.getText().observe(this, new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
slidePager.setAdapter(adapter);
}
});
return root;
}
}
public class SliderPagerAdapter extends PagerAdapter {
private Context mText;
private List<Slide> mList;
public SliderPagerAdapter(Context mText, List<Slide> mList) {
this.mText = mText;
this.mList = mList;
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
LayoutInflater inflater = (LayoutInflater) mText.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View slideLayout = inflater.inflate(R.layout.slider_item,null);
ImageView slideImg = slideLayout.findViewById(R.id.slide_img);
TextView slideText= slideLayout.findViewById(R.id.slide_title);
slideImg.setImageResource(mList.get(position).getImage());
slideText.setText(mList.get(position).getTitle());
container.addView(slideLayout);
return slideLayout;
}
#Override
public int getCount() {
return mList.size();
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == object;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((View) object);
}
}

You didn't instantiate the slidePagerso when you try to setAdapter, it is in fact a null object. You should call a findViewById on the ViewPager.

Related

How to remove/disable pages in viewpager adapter?

I have struggled a lot with my ViewPagerAdapter for remove/disable pages. But nothing happens. Is there any ways to remove pages from a ViewPagerAdapter? Here is my code-
As you can see, I have three positions there. I just want to remove/disable position 1(paragraph 1).
public class ViewPagerAdapter2 extends PagerAdapter
{
private Context context;
private LayoutInflater layoutInflater;
String strings[] = {
"paragraph 0",
"paragraph 1",
"paragraph 2"
};
public ViewPagerAdapter2 (Context context) {
this.context = context;
}
#Override
public int getCount()
{
// TODO: Implement this method
return strings.length;
}
#Override
public boolean isViewFromObject(View view, Object object)
{
// TODO: Implement this method
return view == object;
}
#Override
public Object instantiateItem(ViewGroup container, int position)
{
layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.view_pager_lyrics,null);
final TextView textView = view.findViewById(R.id.view_pager_lyricsTextView);
textView.setText(Html.fromHtml("<!DOCTYPE html><html><head></head><body><div style='text-align: center'><p>"+strings[position]+"</p></div></body></html>"));
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object)
{
ViewPager vp = (ViewPager) container;
View view = (View) object;
vp.removeView(view);
}
}

ViewPager and ImageGallery

The problem is this:
When you first choose a picture - everything is fine. If you swipe, and press the "back" button, after you open another image then will open last image which will opened.
The correct position is passed through the Bundle. I don’t understand where to look for the error.
public class ViewPagerAdapter extends PagerAdapter {
private LayoutInflater layoutInflater;
public ViewPagerAdapter() {
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.image_fullscreen, container, false);
ImageView imageView = view.findViewById(R.id.image_fScreen);
Hit hit = hits.get(position);
Picasso.get().load(hit.getLargeImageURL())
.into(imageView);
container.addView(view);
return view;
}
#Override
public int getCount() {
return hits.size();
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == object;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((View) object);
}
}
DialogFragment:
public class FullScreenDialogFragment extends DialogFragment {
private ArrayList<Hit> hits;
private ViewPager viewPager;
private ViewPagerAdapter viewPagerAdapter;
private TextView author;
private TextView count;
private int selectedPosition;
private Button buttonShare;
private static FullScreenDialogFragment fullScreenDialogFragment;
private int rlyPosition;
public static FullScreenDialogFragment getInstance() {
if (fullScreenDialogFragment == null) {
fullScreenDialogFragment = new FullScreenDialogFragment();
}
return fullScreenDialogFragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(DialogFragment.STYLE_NO_FRAME, R.style.DialogStyle);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.image_viewpager, container, false);
viewPager = view.findViewById(R.id.viewpager);
author = view.findViewById(R.id.author);
buttonShare = view.findViewById(R.id.btnShare);
count = view.findViewById(R.id.count);
hits = (ArrayList<Hit>) getArguments().getSerializable("hits");
selectedPosition = getArguments().getInt("position");
viewPagerAdapter = new ViewPagerAdapter();
viewPager.setAdapter(viewPagerAdapter);
viewPager.addOnPageChangeListener(onViewPageChangeListener);
setItem(selectedPosition);
return view;
}
private void setItem(int pos) {
viewPager.setCurrentItem(pos, true);
setItemInfo(selectedPosition);
}
private void setItemInfo(int pos) {
count.setText((pos + 1) + " of " + hits.size());
Hit hit = hits.get(pos);
author.setText(hit.getUser());
}
ViewPager.OnPageChangeListener onViewPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
setItemInfo(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
};
I Guess the Problem is here
private void setItem(int pos) {
viewPager.setCurrentItem(pos, true);
setItemInfo(selectedPosition);
}
You might be passing the selectedPosition instead of currentPosition
Please check.
My problem was in creating DialogFramgent object.
I did it him in Singlton pattern and called it with old data.
Now in OnClick i'm created new object DialogFramget and him get new values.
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fullScreenDialog = new FullScreenDialogFragment();
fullScreenDialog.setArguments(bundle);
fullScreenDialog.show(fragmentTransaction, "");

How make viewpager to slide image with image's url?

I followed this tutorial to make an image slider with images url but the slider is empty.
Here is my adapter's code:
public class ViewPagerAdapterUrl extends PagerAdapter {
private Context context;
private LayoutInflater layoutInflater;
private ArrayList<String> photosUrl= new ArrayList<>();
public ViewPagerAdapterUrl(Context context, ArrayList<String> photosUrl){
this.context = context;
this.photosUrl = photosUrl;
}
#Override
public int getCount() {
return photosUrl.size();
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == object;
}
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.viewpager_layout, null);
ImageView imageView = (ImageView)view.findViewById(R.id.imageView);
Picasso.get().load(photosUrl.get(position)).into(imageView);
container.addView(imageView);
return imageView;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((View)object);
}
}
Here is the activity where i want to show the adapter:
public class UrlActivity extends AppCompatActivity {
private Advertisement adv;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_url);
viewPager = (ViewPager)findViewById(R.id.viewPager);
//adv is a custom object that contain an arraylist<String> of url.
adv = (Advertisement)getIntent().getSerializableExtra("adv");
ViewPagerAdapterUrl viewPagerAdapterUrl = new ViewPagerAdapterUrl(this, adv.getPhotosUrl());
viewPager.setAdapter(viewPagerAdapterUrl);
}
}
EDIT
I found this in debug but it isn't show like an error:
method int android.support.v7.widget.DropDownListView.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView

OnPageChangeListener in ViewPager adapter?

I have a regular ViewPager with an adapter:
public class MyDialogFragment extends DialogFragment {
private ViewPager viewPager;
private MyViewPagerAdapter myViewPagerAdapter;
private City city;
public static MyDialogFragment newInstance() {
MyDialogFragment fragment = new MyDialogFragment();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_layout, container, false);
viewPager = (ViewPager) v.findViewById(R.id.viewPager);
city = Parcels.unwrap(getArguments().getParcelable("city"));
myViewPagerAdapter = new MyViewPagerAdapter(getContext());
viewPager.setAdapter(myViewPagerAdapter);
viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// Page changed
}
});
return v;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public class MyViewPagerAdapter extends PagerAdapter {
private Context context;
private LayoutInflater layoutInflater;
public MyViewPagerAdapter(Context context) {
this.context = context;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.city_layout, container, false);
ImageView imageView = (ImageView) view.findViewById(R.id.cityImage);
Glide.with(context)
.load(city.getImage())
.into(imageView);
}
container.addView(view);
return view;
}
#Override
public int getCount() {
return city.size();
}
#Override
public boolean isViewFromObject(View view, Object obj) {
return view == ((View) obj);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
}
}
As you can see, I have a page change listener set on my ViewPager. But I need to be able to notify the adapter when the page has changed so that I can modify the adapter's ImageView. How can I do this?
Add a method to your adapter class
public class MyViewPagerAdapter extends PagerAdapter {
...
public void pageChanged(int position) {
// Do something
}
...
}
After that in your OnPageChangeListener use that method
#Override
public void onPageSelected(int position) {
myViewPagerAdapter.pageChanged(position);
}
One approach is to create a data structure in your adapter to map the pager view to its position. A SparseArray is most efficient:
private SparseArray<View> pageMap = new SparseArray<>();
Then in the adapter's instantiateItem() method, add the view to the SparseArray:
public Object instantiateItem(ViewGroup container, int position) {
...
pageMap.put(position, view);
...
}
Now in your OnPageChangeListener you can do the following:
#Override
public void onPageSelected(int position) {
View view = adapter.getView(pos);
if (view != null) {
ImageView iv = (ImageView) view.findViewById(R.id.your_image_view);
// You now have the image view
}
}
Make sure you remove views from the SparseArray in the adapter's destroyItem() method:
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
pageMap.remove(position);
...
}
You can use the constructor with imagelist to pass and that automatically called on next page..In your code will be modified like :::
ArrayList imageList=new ArrayList<>();
imageList.add("ImagePath here");
myViewPagerAdapter = new MyViewPagerAdapter(getContext(),imageList);
viewPager.setAdapter(myViewPagerAdapter);
Then your adapter will be like ::
public class MyViewPagerAdapter extends PagerAdapter {
private Context context;
private ArrayList<String> imageList
private LayoutInflater layoutInflater;
public MyViewPagerAdapter(Context context,ArrayList<String> imageList) {
this.context = context;
this.imageList = imageList;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.city_layout, container, false);
ImageView imageView = (ImageView) view.findViewById(R.id.cityImage);
Glide.with(context)
.load(imageList.get(position)) // This will be changes like
.into(imageView);
}
container.addView(view);
return view;
}
#Override
public int getCount() {
return city.size();
}
#Override
public boolean isViewFromObject(View view, Object obj) {
return view == ((View) obj);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
}
That done ..
After this, there are some suggestion that
- please use arraylist while using the viewpager ..
Now you just taking the parceble object from bundle..
you can do the same for the arraylist,
just receive the arraylist from the same bundle by passing the whole arraylist at once.
so you dont need to find the page change event..viewpager will automatically handle that..
Here's How to send & receiving the parceable arraylist
// while sending the list
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("citylist", new ArrayList<City>());
// while receiving the list
ArrayList<City> citylist = getIntent().getParcelableArrayListExtra("citylist");
After this just get the all image and add in the imagelist array
for (int i = 0; i < citylist.size(); i++) {
imageList.add(citylist.get(i).getImage());
}
And pass this imageList in
myViewPagerAdapter = new MyViewPagerAdapter(getContext(),imageList);
viewPager.setAdapter(myViewPagerAdapter);
Tell me if needed more assitance.

Making GridView with Fragment Instances

I want to implement GridView that each cell contains an object of class. for this I implemented fragment class:
public class DayUC extends Fragment {
/*
some variables
*/
// use to create instance of class with initial parameters
public static DayUC newInstance(//initial parameters) {
DayUC dayUC = new DayUC();
/*
set parameters
*/
return dayUC;
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_layout, container, false);
initialization() //initial variables and view elemans (textView, ...)
return rootView;
}
}
and also I created GridViewAdapter:
public class GridViewAdapter extends BaseAdapter {
private ArrayList<DayUC> gridList; //list of grid DayUC objects
Context context;
public GridViewAdapter(Context context, ArrayList<DayUC> gridList) {
this.gridList = gridList;
this.context = context;
}
#Override
public int getCount() {
return gridList.size();
}
#Override
public DayUC getItem(int position) {
return gridList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
return gridList.get(position).getView();
}
}
but when I create GridView it throws NullPointerException! I found that in gridView elements (DayUC) onCreateView() never called. so gridList.get(position).getView() returns null!!
could anyone help me to solve this problem? how could I force onCreateView to be called??
Edit: MainActivity onCreate method added:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DayUC[] dayUC = new DayUC[42];
monthGridView = (GridView) findViewById(R.id.month_view);
for (int i = 0; i < 42; i++) {
dayUC[i] = DayUC.newInstance(//inpute arguments)
dayUCList.add(dayUC[i]);
monthCal.add(Calendar.DATE, 1);
}
gridViewAdapter = new MonthGridViewAdapter(getActivity(), dayUCList);
monthGridView.setAdapter(gridViewAdapter);
gridViewAdapter.notifyDataSetChanged();
}

Categories

Resources