GridView in fragment not populating (using picasso) - android

I am trying to use this example on the official android tutorial site and translating it into a gridview inside a fragment that uses picasso to load images.
I am looking at my code and I can't figure out what is wrong. The images simply won't load and all I get is a blank screen. What am I missing here?
My fragment code:
public class MainFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
GridView gridView = (GridView) view.findViewById(R.id.gridview);
gridView.setAdapter(new ImageAdapter(getActivity().getApplicationContext()));
return view;
}
}
My custom adapter:
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c){
mContext = c;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
ImageView imageView;
if(view == null){
imageView = new ImageView(mContext);
}
else{
imageView = (ImageView) view;
}
Picasso.with(mContext).setLoggingEnabled(true);
Picasso.with(mContext)
.load(eatFoodyImages[i])
.fit()
.into(imageView);
return imageView;
}
#Override
public int getCount() {
return 0;
}
public static String[] eatFoodyImages = {
"http://i.imgur.com/rFLNqWI.jpg",
"http://i.imgur.com/C9pBVt7.jpg",
"http://i.imgur.com/rT5vXE1.jpg",
"http://i.imgur.com/aIy5R2k.jpg",
"http://i.imgur.com/MoJs9pT.jpg",
"http://i.imgur.com/S963yEM.jpg",
"http://i.imgur.com/rLR2cyc.jpg",
"http://i.imgur.com/SEPdUIx.jpg",
"http://i.imgur.com/aC9OjaM.jpg",
"http://i.imgur.com/76Jfv9b.jpg",
"http://i.imgur.com/fUX7EIB.jpg",
"http://i.imgur.com/syELajx.jpg",
"http://i.imgur.com/COzBnru.jpg",
"http://i.imgur.com/Z3QjilA.jpg",
};
}
My activity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState == null){
getSupportFragmentManager()
.beginTransaction().add(R.id.mainfragment, new MainFragment())
.commit();
}
}
}

#Override
public int getCount() {
return eatFoodyImages.length;
}

Related

Gridview gallery with Viewpager and pinch to zoom

I am developing a simple gallery app .
I have 2 problems :
First problem :
When I touch a specific image in my GridView to show in the fullscreen activity (viewpager activity) it always shows the first image in the GridView gallery!!! not the one I touched!!!
But ViewPager work correctly .
Second problem:
I want to zoom in the ViewPager activity
I tried a library (chrisbanes:phtoview) but it has some issues with ViewPager
Summary :
I want my gallery app to work normal. GridView gallery (you can swipe and pinch to zoom images)
MainActivity.java
public class MainActivity extends AppCompatActivity {
private ViewPager slider;
private SliderAdapter sliderAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
slider=findViewById(R.id.slider);
sliderAdapter=new SliderAdapter(this);
slider.setAdapter(sliderAdapter);
}
private class SliderAdapter extends PagerAdapter{
private Context context;
private LayoutInflater inflater;
public SliderAdapter(Context context) {
this.context = context;
}
int[] list_img={R.drawable.ferari,R.drawable.ferrari,R.drawable.ferrarilogoo,R.drawable.yellowferrariiii,R.drawable.models,R.drawable.applogo,R.drawable.carfront,R.drawable.california,R.drawable.laferrari
};
#Override
public int getCount() {
return list_img.length;
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view==object;
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, final int position) {
inflater=(LayoutInflater)context.getSystemService(LAYOUT_INFLATER_SERVICE);
View view=inflater.inflate(R.layout.item_slider,container,false);
ImageView imageView=view.findViewById(R.id.img_item);
imageView.setImageResource(list_img[position]);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent=new Intent(context,Fullscreen.class);
intent.putExtra("Ferrari",position);
startActivity(intent);
}
});
container.addView(view);
return view;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((ImageView)object);
}
}
}
ImageAdapter.java
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
// if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new ViewGroup.LayoutParams(230, 250));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(3, 3, 3, 3);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
// references to our images
public Integer[] mThumbIds = {
R.drawable.ferari, R.drawable.models,
R.drawable.ferrarihd,
R.drawable.ferrari,
R.drawable.yellowferrariiii,
R.drawable.models,
R.drawable.home,
R.drawable.carfront,
R.drawable.villa,
R.drawable.derrarii,
R.drawable.laferrari,
R.drawable.realestate,
R.drawable.carfront,R.drawable.california,R.drawable.laferrari
};
}
FullscreenviewActivity.java
public class FullScreenViewActivity extends AppCompatActivity {
private ViewPager slider;
private SliderAdapter sliderAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_full_screen_view);
slider=findViewById(R.id.slider);
sliderAdapter=new SliderAdapter(this);
slider.setAdapter(sliderAdapter);
slider.setPageTransformer(false, new ViewPager.PageTransformer() {
#Override
public void transformPage(View page, float position) {
// do transformation here
final float normalizedposition = Math.abs(Math.abs(position) - 1);
page.setScaleX(normalizedposition / 2 + 0.5f);
page.setScaleY(normalizedposition / 2 + 0.5f);
//or
// page.setRotationY(position * -30);
}
});
// get intent data
Intent i = getIntent();
// Selected image id
int position = i.getExtras().getInt("id");
ImageAdapter gridViewAdapter = new ImageAdapter(this);
gridViewAdapter.getItemId(position);
}
private class SliderAdapter extends PagerAdapter {
private Context context;
private LayoutInflater inflater;
public SliderAdapter(Context context) {
this.context = context;
}
int[] mThumbIds={ R.drawable.ferari, R.drawable.models,
R.drawable.ferrarihd,
R.drawable.ferrari,
R.drawable.yellowferrariiii,
R.drawable.models,
R.drawable.home,
R.drawable.carfront,
R.drawable.villa,
R.drawable.derrarii,
R.drawable.laferrari,
R.drawable.realestate,
R.drawable.carfront,R.drawable.california,R.drawable.laferrari
};
#Override
public CharSequence getPageTitle (int position) {
return "Ferrari Cars";
}
#Override
public int getCount() {
return mThumbIds.length;
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view==object;
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, final int position) {
inflater=(LayoutInflater)context.getSystemService(LAYOUT_INFLATER_SERVICE);
View view=inflater.inflate(R.layout.item_slider,container,false);
ImageView imageView=view.findViewById(R.id.img_item);
imageView.setImageResource(mThumbIds[position]);
container.addView(view);
return view;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((ImageView)object);
}
}
}
Firstly you have the position of image in FullScreenActivity so only do one thing to scroll that image
slider.setCurrentItem(pos);
After
int position = i.getExtras().getInt("id");
And use TouchImageView for zoom

ViewPager [FragmentPagerAdapter] inside ListView

i'm trying to put ViewPager into ListView
here the code of ListView AdapterClass:
public class AdapterPager extends BaseAdapter {
.....
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = lInflater.inflate(R.layout.component_pager, parent, false);
new ViewHolder(view, itemData.get(position));
}
return view;
}
View Holder:
private class ViewHolder {
ViewPager pager;
PagerAdapter pagerAdapter;
public ViewHolder(View view, ModelItem model){
pager = (ViewPager) view.findViewById(R.id.pager);
pager.setId(model.getId()); /// uniq ID
pagerAdapter = new MyFragmentPagerAdapter(((FragmentActivity)view.getContext()).getSupportFragmentManager());
pager.setAdapter(pagerAdapter);
}
then, Pager Adapter:
static final int PAGE_COUNT = 2;
private class MyFragmentPagerAdapter extends FragmentPagerAdapter {
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return FragmentComponentPager.newInstance(position, mModel);
}
#Override
public float getPageWidth(int position) {
float f_width = 1f;
return f_width;
}
#Override
public int getCount() {
return PAGE_COUNT;
}
}
and, the last, Pager Fragment:
public class FragmentComponentPager extends Fragment {
static final String ARGUMENT_PAGE_NUMBER = "arg_page_number";
static final String ARGUMENT_NAME = "arg_name";
int pageNumber;
public static FragmentComponentPager newInstance(int page, ModelItem data) {
FragmentComponentPager pageFragment = new FragmentComponentPager();
Bundle arguments = new Bundle();
arguments.putInt(ARGUMENT_PAGE_NUMBER, page);
if (data != null){
arguments.putString(ARGUMENT_NAME, data.getName());
}
pageFragment.setArguments(arguments);
return pageFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pageNumber = getArguments().getInt(ARGUMENT_PAGE_NUMBER);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.component_list, null);
TextView tvTitle = (TextView) view.findViewById(R.id.tvTitle);
tvTitle.setText(getArguments().getString(ARGUMENT_NAME));
return view;
}
}
when i run it ListView shows all items that i've added, but all of them, except the last one, with empty ViewPager.
and, if i removed pager.setId(model.getId()); the first item shows view pager, and the others empty.
guess that smth wrong with FragmentManager, but have no idea how deal with it :(
In your ViewHolder you need to call getChildFragmentManager instead of getSupportFragmentManager.

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();
}

Two instances of the same ListFragment in one FragmentActivity using ViewPager

I have a FragmentActivity that uses a ViewPager to flip left and right through pages of data (two ListFragments).
public class StopsActivity extends FragmentActivity {
private ViewPager mViewPager;
private PagerTabStrip mPagerTabStrip;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stops);
mPagerTabStrip =(PagerTabStrip)findViewById(R.id.pager_header);
mViewPager = (ViewPager)findViewById(R.id.pager);
mPagerTabStrip.setDrawFullUnderline(true);
mPagerTabStrip.setTabIndicatorColorResource(R.color.pagerTabStrip);
mViewPager.setAdapter(new StopsAdapter(getSupportFragmentManager()));
mViewPager.setCurrentItem(0);
}
private class StopsAdapter extends FragmentPagerAdapter {
public StopsAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return StopsFragment.newInstance(routename, Stop.FORWARD);
case 1:
return StopsFragment.newInstance(routename, Stop.BACKWARD);
}
return null;
}
#Override
public int getCount() { return 2;}
#Override
public CharSequence getPageTitle(int position) { /* implementation ... */}
}
}
Everything runs ok, but I think that the instantation of the second StopFragment invalidate the data of the first one when getItem is called.
public class StopsFragment extends ListFragment {
private StopsAdapter mStopsAdapter;
private ListView mListView;
private String routename;
private int direction;
public static StopsFragment newInstance(String routename, int direction) {
StopsFragment stopsFragment = new StopsFragment();
// Supply arguments
Bundle args = new Bundle();
args.putString("routename", routename);
args.putInt("direction", direction);
stopsFragment.setArguments(args);
return stopsFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Setup the adapter
ArrayList<Stop> stops = ...
mStopsAdapter = new StopsAdapter(getActivity(), stops);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle inState) {
View rootView = inflater.inflate(R.layout.fragment_stops, container, false);
// Attach the adapter
mListView = (ListView) rootView.findViewById(android.R.id.list);
mListView.setAdapter(mStopsAdapter);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
The page "IDA" corresponds to StopFragment with argument Stop.FORWARD and the page "VUELTA" corresponds the StopFragment with argument Stop.BACKWARD. As you can see in the images below, just one of them (the last one instantiate) is populated:
What I'm doing wrong?
EDIT
This is StopsAdapter
class StopsAdapter extends BaseAdapter {
private ArrayList<Stop> stops;
private LayoutInflater inflater;
public StopsAdapter(Context context, ArrayList<Stop> stops) {
this.stops = stops;
this.inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return stops.size();
}
#Override
public Object getItem(int position) {
return stops.get(position);
}
#Override
public long getItemId(int position) {
return (long)position;
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.item_stop, parent, false);
}
TextView name = (TextView)convertView.findViewById(R.id.tvStopName);
TextView description = (TextView)convertView.findViewById(R.id.tvStopDescription);
Stop stop = (Stop)getItem(position);
name.setText(stop.name);
if (stop.info != null) {
description.setText(stop.info);
}
return convertView;
}
}
Ok, my fault. The code that was giving me problems is the only that I haven't posted (ArrayList<Stop> stops = ...). The code about Fragments and ViewPager works correctly.

ViewPager + ListView animation lag

I have a CarsFragment which is inculde cars. One page is one trade (Ferrari, Mercedes) and on every page has a list with models of actual trade.
The main view:
public class CarsFragment extends Fragment {
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.cars_fragment, container, false);
pager = (ViewPager) view.findViewById(R.id.carsPager);
adapter = new CarsPagerAdapter(getChildFragmentManager());
pager.setAdapter(adapter);
return view;
}
}
Adapter:
public class CarsPagerAdapter extends FragmentStatePagerAdapter {
private final FragmentManager fm;
private String[] cars = new String[]{"Ferrari","Mercedes"};
public MatchesPageAdapter(final FragmentManager fm) {
super(fm);
this.fm = fm;
}
#Override
public int getCount() {
return cars.length;
}
#Override
public Fragment getItem(final int position) {
return FragmentModelList.newInstance(cars[position]);
}
#Override
public void destroyItem(final ViewGroup container, final int position, final Object object) {
super.destroyItem(container, position, object);
}
}
List:
public class FragmentModelList extends Fragment {
public static FragmentModelList newInstance(String trade) {
FragmentModelList fragmentModelList = new FragmentModelList();
Bundle args = new Bundle();
args.putString("trade", trade);
fragmentModelList.setArguments(args);
return fragmentModelList;
}
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_matches_list_view, container, false);
list = (ListView) view.findViewById(R.id.modelList);
return view;
}
#Override
public void onActivityCreated(final Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
modelListAdapter = new ModelListAdapter(getActivity());
list.setAdapter(modelListAdapter);
loadModels();
}
private void loadModels() {
new AsyncTask<Void, Void, Boolean>() {
#Override
protected Boolean doInBackground(final Void... params) {
try {
List<Model> result = Downloader.getModelsByName(getArguments().getString("trade"));
modelListAdapter.setData(result);
return true;
} catch (Exception ex) {
return false;
}
}
#Override
protected void onPostExecute(final Boolean success) {
if (!success) {
// Show error
} else {
// Update list
modelListAdapter.notifyDataSetChanged();
}
}
}.execute();
}
}
and the modelListAdapter set row where one row inculde 2 image and some textview.
And the problem:
when i swiping on the viewpager it isn't smooth :( a loged it and when created the next or previous page (depends on swipe direction) the animation will be bad, is lagging.
What is the solution?
(SGS4 android 4.2.2 - where is the project butter :(( )

Categories

Resources