Send Parcelable Arraylist to Fragment - android

I used to get Bundle in activity like this and it worked fine
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.singleview);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// list = (ListView) findViewById(R.id.ListView);
toolbar = (Toolbar) findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
// getSupportActionBar().setDisplayHomeAsUpEnabled(true);
imageView = (ImageView) findViewById(R.id.funnyimage);
Bundle bundle = getIntent().getExtras();
ArrayList<Listitem> personArrayList = bundle.getParcelableArrayList("Person_List");
if (personArrayList != null && !personArrayList.isEmpty()) {
for (Listitem person : personArrayList) {
Picasso.
with(this).
load(person.url)
.placeholder(R.drawable.logo)
.fit()
.noFade()
.into(imageView);
Log.i("PersonsActivity",String.valueOf(person.url));
}
}
My problem is I want to get arraylist paracble in fragment
I am having error in word bundle in the below code
ArrayList<Listitem> personArrayList = bundle.getParcelableArrayList("Person_List");
I though using instance:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//change to avoid orientation crash
imageResourceId = getArguments().getInt("param");
numberSelected = getArguments().getParcelableArrayList("number"); // this is wrong but i was trying something
}
public Fragment newInstance(int imageResourceId, int numberSelected) {
DemoObjectFragment f = new DemoObjectFragment();
f.imageResourceId = imageResourceId;
f.numberSelected = numberSelected;
}
this is my code for your reference
public class SingleViewActivity extends FragmentActivity {
ImageView imageView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page_view);
DemoCollectionPagerAdapter
mDemoCollectionPagerAdapter =
new DemoCollectionPagerAdapter(
getSupportFragmentManager());
ViewPager mViewPager = (ViewPager) findViewById(R.id.pager);
imageView = (ImageView) findViewById(R.id.funnyimage);
Bundle bundle = getIntent().getExtras();
mViewPager.setAdapter(mDemoCollectionPagerAdapter);
}
/* if (savedInstanceState == null) {
// During initial setup, plug in the details fragment.
MyFragment myrag = new MyFragment();
myrag.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction().add(android.R.id.content, myrag).commit();
}
*/
// Since this is an object collection, use a FragmentStatePagerAdapter,
// and NOT a FragmentPagerAdapter.
public class DemoCollectionPagerAdapter extends FragmentStatePagerAdapter {
public DemoCollectionPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment = new DemoObjectFragment();
Bundle args = new Bundle();
// Our object is just an integer :-P
args.putInt(DemoObjectFragment.ARG_OBJECT, i + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return 100;
}
#Override
public CharSequence getPageTitle(int position) {
return "OBJECT " + (position + 1);
}
}
// Instances of this class are fragments representing a single
// object in our collection.
public static class DemoObjectFragment extends Fragment {
public static final String ARG_OBJECT = "object";
ImageView imageView;
int imageResourceId;
int numberSelected;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//change to avoid orientation crash
imageResourceId = getArguments().getInt("param");
numberSelected = getArguments().getInt("number");
}
public Fragment newInstance(int imageResourceId, int numberSelected) {
DemoObjectFragment f = new DemoObjectFragment();
f.imageResourceId = imageResourceId;
f.numberSelected = numberSelected;
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
// The last two arguments ensure LayoutParams are inflated
// properly.
View rootView = inflater.inflate(
R.layout.fragment_collection_object, container, false);
Bundle args = getArguments();
// ((TextView) rootView.findViewById(R.id.text1)).setText(Integer.toString(args.getInt(ARG_OBJECT)));
ArrayList<Listitem> personArrayList = bundle.getParcelableArrayList("Person_List");
if (personArrayList != null && !personArrayList.isEmpty()) {
for (Listitem person : personArrayList) {
Picasso.
with(mcontext).
load(person.url)
.placeholder(R.drawable.logo)
.fit()
.noFade()
.into(imageView);
Log.i("PersonsActivity",String.valueOf(person.url));
}
}
return rootView;
}
}
}

It works for me, if it doesn't work for you post the error message from the logcat,
ArrayList<Listitem> personArrayList;
//To put your arraylist
Bundle b = new Bundle();
b.putParcelableArrayList("Person_List", personArrayList);
//To get your arraylist
Bundle extras = getIntent().getExtras();
personArrayList = extras.getParcelableArrayList("Person_List");

Related

How to access custom arraylist in fragment

I have tablayout in my app,and i want to set recyclerview in tablayout fragment.if i set static String array it is working fine.but i dont know how can i access custom arraylist in fragment to set data in my recyclerview.following is my code can any one help me with that
public class CategoriesActivity extends AppCompatActivity{
private Header myview;
private ArrayList<SubcategoryModel> subct;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.categoris_activity);
ArrayList<CategoryModel> filelist = (ArrayList<CategoryModel>)getIntent().getSerializableExtra("categorylist");
System.out.println("Category list size"+filelist.size());
myview = (Header) findViewById(R.id.categorisactivity_headerView);
myview.setActivity(this);
TabLayout tabLayout = (TabLayout) findViewById(R.id.cat_tab_layout);
for(int i = 0; i < filelist.size(); i++){
subct=filelist.get(i).getItems();
for(int j=0;j<subct.size();j++)
{
}
System.out.println("SubCategory list size"+subct.size());
}
for(int i = 0; i < filelist.size(); i++){
tabLayout.addTab(tabLayout.newTab().setText(filelist.get(i).getCategory_typename()));
ArrayList<SubcategoryModel> subct=filelist.get(i).getItems();
for(int j=0;j<subct.size();j++)
{
}
}
Bundle bundleObject = new Bundle();
bundleObject.putSerializable("key", filelist);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.categories_pager);
CategoriesAdapter mPagerAdapter = new CategoriesAdapter(getSupportFragmentManager(),tabLayout.getTabCount());
viewPager.setAdapter(mPagerAdapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
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) {
}
});
}
public class CategoriesAdapter extends FragmentStatePagerAdapter {
ArrayList<CategoryModel> catlist;
int numoftabs;
public CategoriesAdapter(FragmentManager fm, int numoftabs) {
super(fm);
this.numoftabs = numoftabs;
}
#Override
public Fragment getItem(int position) {
Log.v("adapter", "getitem" + String.valueOf(position));
return FirstFragment.create(position);
}
#Override
public int getCount() {
return numoftabs;
}
}
}
Fragment
public class FirstFragment extends Fragment {
// Store instance variables
public static final String ARG_PAGE = "page";
private int mPageNumber;
private Context mContext;
private int Cimage;
private ArrayList<SubcategoryModel> subcatlist;
private RecyclerView rcylervw;
private ArrayList<CategoryModel> filelist;
public static FirstFragment create(int pageNumber){
FirstFragment fragment = new FirstFragment();
Bundle args = new Bundle();
args.putInt(ARG_PAGE, pageNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPageNumber = getArguments().getInt(ARG_PAGE);
// image uri get uri of image that saved in directory of app
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater
.inflate(R.layout.test, container, false);
// Get the Bundle Object
Bundle bundleObject = getActivity().getIntent().getExtras();
// Get ArrayList Bundle
ArrayList<CategoryModel> classObject = (ArrayList<CategoryModel>) bundleObject.getSerializable("key");
System.out.println("Frag Category list size"+classObject.size());
rcylervw=(RecyclerView)rootView.findViewById(R.id.subcategory_recycler_view);
rcylervw.setHasFixedSize(true);
MyAdapter adapter = new MyAdapter(new String[]{"test one", "test two", "test three", "test four", "test five" , "test six" , "test seven"});
rcylervw.setAdapter(adapter);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
rcylervw.setLayoutManager(llm);
return rootView;
}
getting NPE here
// Get the Bundle Object
Bundle bundleObject = getActivity().getIntent().getExtras();
// Get ArrayList Bundle
ArrayList<CategoryModel> classObject = (ArrayList<CategoryModel>) bundleObject.getSerializable("key");
Make CategoryModel implements serializable. Put data in bundle using
Bundle args = new Bundle();
args.putSerializable("key", data);
fragment.setArguments(args);
Then, while getting data use:
if (getArguments() != null) {
classObject = (ArrayList<CategoryModel>) getArguments().getSerializable("key");
}
Make CategoryModel implement Parcelable then use bundle.putParcelableArrayList(key,list) and bundle.getParcelableArrayList(key)

getting empty arraylist to fragment activity

I am sending arraylist from gridviewadapter to the fragment but data its not displayed. the gridview code was working when sending arraylist to an activity, so the problem is with the fragment
this is the grid view adapter
#Override
public View getView(int position, View convertView, ViewGroup parent) {
System.out.println("entering adapter1");
View row = convertView;
final ViewHolder holder;
if (row == null) {
LayoutInflater inflater = LayoutInflater.from(mcontext);
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ViewHolder();
holder.imageTitle = (TextView) row.findViewById(R.id.text);
holder.imageView = (ImageView) row.findViewById(R.id.imageView);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
final Listitem item = getItem(position);
System.out.println("item.getUrl() ");
System.out.println(item.getUrl());
Picasso.with(mcontext).setIndicatorsEnabled(true);
holder.imageTitle.setText(item.getId());
/* Picasso.
with(mcontext).
load(item.getUrl())
.placeholder(R.drawable.logo)
.fit()
.noFade()
.into(holder.imageView)
;*/
//int maxSize = 4 * 1024 * 1024; // 4MiB
//Picasso myNewPicasso = new Picasso.Builder(mcontext).memoryCache(new LruCache(maxSize)).build();
Picasso.with(mcontext)
.load(item.getUrl())
.placeholder(R.drawable.logo)
.fit()
.noFade()
.into(holder.imageView);
holder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
ArrayList<Listitem> personArrayList = new ArrayList<>();
personArrayList.add(new Listitem(item.getId(), item.getUrl()));
Intent intent = new Intent(mcontext,SingleViewActivity.class);
intent.putExtra("Person_List", personArrayList);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mcontext.startActivity(intent);
Log.d("OnImageButton", "Clicked");
}
});
return row;
}
static class ViewHolder {
TextView imageTitle;
ImageView imageView;
}
this is the fragment that contain also a view pager
public class SingleViewActivity extends FragmentActivity {
ImageView imageView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page_view);
DemoCollectionPagerAdapter mDemoCollectionPagerAdapter = new DemoCollectionPagerAdapter( getSupportFragmentManager());
ViewPager mViewPager = (ViewPager) findViewById(R.id.pager);
imageView = (ImageView) findViewById(R.id.funnyimage);
Bundle bundle = getIntent().getExtras();
Log.d("s","singleview");
mViewPager.setAdapter(mDemoCollectionPagerAdapter);
}
/* if (savedInstanceState == null) {
// During initial setup, plug in the details fragment.
MyFragment myrag = new MyFragment();
myrag.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction().add(android.R.id.content, myrag).commit();
}
*/
// Since this is an object collection, use a FragmentStatePagerAdapter,
// and NOT a FragmentPagerAdapter.
public class DemoCollectionPagerAdapter extends FragmentStatePagerAdapter {
public DemoCollectionPagerAdapter(FragmentManager fm) {
super(fm);
Log.d("s","adapterview");
}
#Override
public Fragment getItem(int i) {
Fragment fragment = new DemoObjectFragment();
Bundle args = new Bundle();
// Our object is just an integer :-P
args.putInt(DemoObjectFragment.ARG_OBJECT, i + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return 100;
}
#Override
public CharSequence getPageTitle(int position) {
return "OBJECT " + (position + 1);
}
}
// Instances of this class are fragments representing a single
// object in our collection.
public static class DemoObjectFragment extends Fragment {
public static final String ARG_OBJECT = "object";
ImageView imageView;
int imageResourceId;
int numberSelected;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//change to avoid orientation crash
Log.d("s","fragview");
}
public static Fragment newInstance(Context context,ArrayList<Listitem> personArrayList, int numberSelected) {
DemoObjectFragment f = new DemoObjectFragment();
Bundle args= new Bundle();
args.putParcelableArrayList("Person_List", personArrayList);
//args.putInt("",imageResourceId);
f.setArguments(args);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
// The last two arguments ensure LayoutParams are inflated
// properly.
View rootView = inflater.inflate(
R.layout.fragment_collection_object, container, false);
// Bundle args = getArguments();
// ((TextView) rootView.findViewById(R.id.text1)).setText(Integer.toString(args.getInt(ARG_OBJECT)));
Bundle args= new Bundle();
ArrayList<Listitem> personArrayList = args.getParcelableArrayList("Person_List");
System.out.print(personArrayList);
System.out.print("here1");
if (personArrayList != null && !personArrayList.isEmpty()) {
for (Listitem person : personArrayList) {
Picasso.
with(getActivity()).
load(person.url)
.placeholder(R.drawable.logo)
.fit()
.noFade()
.into(imageView);
Log.i("PersonsActivity",String.valueOf(person.url));
}
}
return rootView;
}
}
}
A bit explanation of what I am doing
In my main activity I have a grid view of image, when I click on one image , I get the single image-clicked on a new activity. I used that with parcelable arraylist that send data from gridview to singleview acitivity. it was working for the activity. but when I implemented the viewpager and the fragment and fragment adapter nothing is showing I dont know why,
this is my logcat , as you notice its not proceeding to the rest,fragview is a log print added in my code.
01-11 20:54:40.814 3323-3323/com.justedhak.www.i D/Activity: performCreate Call secproduct feature valuefalse
01-11 20:54:40.814 3323-3323/com.justedhak.www.i D/Activity: performCreate Call debug elastic valuetrue
01-11 20:54:40.829 3323-3323/com.justedhak.www.i D/s: fragview
01-11 20:54:40.839 3323-3323/com.justedhak.www.i D/s: fragview
01-11 20:54:40.954 3323-3323/? I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy#211f949f time:9248062
this is part of the fragment code in Singleviewactivity.java
public static class DemoObjectFragment extends Fragment {
public static final String ARG_OBJECT = "object";
ImageView imageView;
int imageResourceId;
int numberSelected;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//change to avoid orientation crash
Log.d("s","fragview");
}
public static Fragment newInstance(Context context,ArrayList<Listitem> personArrayList, int numberSelected) {
DemoObjectFragment f = new DemoObjectFragment();
Bundle args= new Bundle();
args.putParcelableArrayList("Person_List", personArrayList);
//args.putInt("",imageResourceId);
f.setArguments(args);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
// The last two arguments ensure LayoutParams are inflated
// properly.
View rootView = inflater.inflate(
R.layout.fragment_collection_object, container, false);
// Bundle args = getArguments();
// ((TextView) rootView.findViewById(R.id.text1)).setText(Integer.toString(args.getInt(ARG_OBJECT)));
Bundle args= new Bundle();
ArrayList<Listitem> personArrayList = args.getParcelableArrayList("Person_List");
System.out.print(personArrayList);
System.out.print("here1");
if (personArrayList != null && !personArrayList.isEmpty()) {
for (Listitem person : personArrayList) {
Picasso.
with(getActivity()).
load(person.url)
.placeholder(R.drawable.logo)
.fit()
.noFade()
.into(imageView);
Log.i("PersonsActivity",String.valueOf(person.url));
}
}
return rootView;
}
}
}
Moudiz,
You need to change your DemoCollectionPagerAdapter constructor to accept the ArrayList of people as such:
DemoCollectionPagerAdapter(FragmentManager fm, ArrayList<Listitem> personArrayList)
With the new constructor be sure to pass this to your adapter object when you first create it at the SinglePageActivity View.
public class SingleViewActivity extends FragmentActivity {
ImageView imageView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page_view);
Bundle bundle = getIntent().getExtras();
ArrayList<Listitem> personList = getIntent().getParcelableArrayListExtra("Person_List");
// Pass it here using your new constructor.
DemoCollectionPagerAdapter mDemoCollectionPagerAdapter = new DemoCollectionPagerAdapter(getSupportFragmentManager(), personList);
ViewPager mViewPager = (ViewPager) findViewById(R.id.pager);
imageView = (ImageView) findViewById(R.id.funnyimage);
Log.d("s","singleview");
mViewPager.setAdapter(mDemoCollectionPagerAdapter);
}
The next part is for you to figure out because it is rather confusing why you are passing in your ArrayList when you create a Fragment object here :
public static Fragment newInstance(Context context,ArrayList<Listitem> personArrayList, int numberSelected) {
Let me know if this helps.

how receive arraylist in fragment

I need to know how to get array list using Bundle in fragment , in the examples I have seen they are using ints or strings. how to get fragments ? In my activity it was working good getting the arraylist
my updated code
public class SingleViewActivity extends FragmentActivity {
ImageView imageView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page_view);
ArrayList<Listitem> personArrayList = new ArrayList<Listitem>();
// add some ListItem's...
DemoObjectFragment f = DemoObjectFragment.newInstance(personArrayList);
ViewPager mViewPager = (ViewPager) findViewById(R.id.pager);
imageView = (ImageView) findViewById(R.id.funnyimage);
Bundle bundle = getIntent().getExtras();
Log.d("s","singleview");
mViewPager.setAdapter(mDemoCollectionPagerAdapter);
/*
DemoCollectionPagerAdapter mDemoCollectionPagerAdapter = new DemoCollectionPagerAdapter( getSupportFragmentManager());
ViewPager mViewPager = (ViewPager) findViewById(R.id.pager);
imageView = (ImageView) findViewById(R.id.funnyimage);
Bundle bundle = getIntent().getExtras();
Log.d("s","singleview");
mViewPager.setAdapter(mDemoCollectionPagerAdapter);*/
/* if (savedInstanceState == null) {
// During initial setup, plug in the details fragment.
MyFragment myrag = new MyFragment();
myrag.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction().add(android.R.id.content, myrag).commit();
}
*/
}
// Since this is an object collection, use a FragmentStatePagerAdapter,
// and NOT a FragmentPagerAdapter.
public class DemoCollectionPagerAdapter extends FragmentStatePagerAdapter {
public static final String ARG_OBJECT = "Person_List";
public DemoCollectionPagerAdapter(FragmentManager fm, ArrayList<Listitem> personArrayList)
{
super(fm);
Log.d("s","adapterview");
}
#Override
public Fragment getItem(int i) {
Fragment fragment = new DemoObjectFragment();
Bundle args = new Bundle();
// Our object is just an integer :-P
args.putInt(DemoObjectFragment.ARG_PERSON_LIST, i + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return 100;
}
#Override
public CharSequence getPageTitle(int position) {
return "OBJECT " + (position + 1);
}
}
// Instances of this class are fragments representing a single
// object in our collection.
public class DemoObjectFragment extends Fragment {
public static final String ARG_PERSON_LIST = "Person_List";
private ArrayList<Listitem> items;
public DemoObjectFragment newInstance(ArrayList<Listitem> items) {
DemoObjectFragment f = new DemoObjectFragment();
Bundle args = new Bundle();
args.putParcelableArrayList(ARG_PERSON_LIST, items);
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
if (args.containsKey(ARG_PERSON_LIST)) {
// UNTESTED: probably will need to cast this
this.items = args.getParcelableArrayList(ARG_PERSON_LIST);
} else { // avoid the NullPointerException later by initializing the list
this.items = new ArrayList<Listitem>();
}
// use this.items as you wish, but it will be empty if you didn't set the Bundle argument correctly
}
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
// The last two arguments ensure LayoutParams are inflated
// properly.
View rootView = inflater.inflate(
R.layout.fragment_collection_object, container, false);
// Bundle args = getArguments();
// ((TextView) rootView.findViewById(R.id.text1)).setText(Integer.toString(args.getInt(ARG_OBJECT)));
Bundle args= new Bundle();
ArrayList<Listitem> personArrayList = args.getParcelableArrayList("Person_List");
System.out.print(personArrayList);
System.out.print("here1");
if (personArrayList != null && !personArrayList.isEmpty()) {
for (Listitem person : personArrayList) {
Picasso.
with(getActivity()).
load(person.url)
.placeholder(R.drawable.logo)
.fit()
.noFade()
.into(imageView);
Log.i("PersonsActivity",String.valueOf(person.url));
}
}
return rootView;
}
}
}
I have 2 errors now :
for newInstance as I mentioned before I cannot refer to not static .
and I am getting error now for picasso
edit 3
This is a good start for what you are looking for and assumes you have correctly implemented Parcelable for the ListItem class.
Somewhere in your Activity
ArrayList<ListItem> personArrayList = new ArrayList<ListItem>();
// add some ListItem's...
DemoObjectFragment f = DemoObjectFragment.newInstance(personArrayList);
From the top of your Fragment class (note: it is not a static class)
public class DemoObjectFragment extends Fragment {
public static final String ARG_PERSON_LIST = "Person_List";
private ArrayList<ListItem> items;
public static DemoObjectFragment newInstance(ArrayList<ListItem> items) {
DemoObjectFragment f = new DemoObjectFragment();
Bundle args = new Bundle();
args.putParcelableArrayList(ARG_PERSON_LIST, items);
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
if (args.containsKey(ARG_PERSON_LIST)) {
// UNTESTED: probably will need to cast this
this.items = args.getParcelableArrayList(ARG_PERSON_LIST);
} else { // avoid the NullPointerException later by initializing the list
this.items = new ArrayList<ListItem>();
}
/*
* use this.items as you wish, but
* it will be empty if you didn't set the
* Bundle argument correctly
*/
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.fragment_collection_object, container, false);
ImageView imageView = (ImageView) rootView.findViewById(R.id.imageView);
Log.i("DemoObjectFragment", "Inside onCreateView");
if (this.items.isEmpty()) {
Log.i("DemoObjectFragment", "Warning: There are no items!");
}
if (this.items != null) {
for (Listitem person : items) {
Picasso.with(getActivity())
.load(person.url)
.placeholder(R.drawable.logo)
.fit()
.noFade()
.into(imageView);
Log.i("DemoObjectFragment", "Person URL: " + String.valueOf(person.url));
}
} else {
Log.i("DemoObjectFragment", "Oh no! items is null!");
}
return rootView;
}
}
From what I see the fragment has no way of knowing what personArrayList you are referring to. Usually you pass the list as an extra argument in the newInstance method (step 1), save it in the bundle (step 2) and then retrieve it from the bundle in onCreate (step 3).
To fix you code you would have to either initialize the list with a new ArrayList(), but it would be empty in that case, or do as I said above (you're just missing step 1, so you're almost done).

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..

Update fragment view after onCreateView in FragmentPagerAdapter

I'm trying to implement an activity with tabs in action bar and a view pager. I have the same fragment for every tab.
I need to update fragments after onCreateView is called, passing objects.
Pager adapter :
public class MyFragmentPagerAdapter extends FragmentPagerAdapter {
public MyFragmentPagerAdapter() {
super(getSupportFragmentManager());
}
#Override
public int getCount() {
return cat_pages.getList_categories().size();
}
#Override
public Fragment getItem(int position) {
Log.i("position fragment", "i = " + position);
final Handler uiHandler = new Handler();
int index = position;
final Category cat = cat_pages.getList_categories().get(index);
Log.i("position fragment", "name = " + cat.getName());
mCategoriesFragment = new ListPostFragment();
return mCategoriesFragment;
}
}
Fragment :
public class ListPostFragment extends Fragment {
// Layouts
private LinearLayout layout_loading;
public static GridView list_view_articles;
private TextView txt_nothing, txt_title;
// The list of headlines that we are displaying
private List<Post> mPostsList = new ArrayList<Post>();
private List<Post> list_posts = new ArrayList<Post>();
// The list adapter for the list we are displaying
private ArticlesAdapter mListAdapter;
private Category mCurrentCat;
Category clicked_cat;
String activity;
String title;
public ListPostFragment() {
super();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mListAdapter = new ArticlesAdapter(getActivity(), mPostsList);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_grid_posts, container, false);
layout_loading = (LinearLayout) rootView.findViewById(R.id.layout_loading);
list_view_articles = (GridView) rootView.findViewById(R.id.gridViewArticles);
txt_nothing = (TextView) rootView.findViewById(R.id.txt_no_result);
txt_title = (TextView) rootView.findViewById(R.id.txt_title);
Log.i("frag", "frag create view");
return rootView;
}
#Override
public void onStart() {
super.onStart();
list_view_articles.setAdapter(mListAdapter);
}
public void loadPosts(Category clicked_cat, List<Post> list_posts, String title) {
Log.i("frag", "frag load");
layout_loading.setVisibility(View.VISIBLE);
list_view_articles.setVisibility(View.GONE);
txt_title.setVisibility(View.GONE);
mPostsList.clear();
layout_loading.setVisibility(View.GONE);
if(list_posts != null){
mPostsList.addAll(list_posts);
if(mPostsList.size() > 0){
list_view_articles.setVisibility(View.VISIBLE);
txt_nothing.setVisibility(View.GONE);
}else{
list_view_articles.setVisibility(View.GONE);
txt_nothing.setVisibility(View.VISIBLE);
}
mListAdapter.notifyDataSetChanged();
}else{ // Nothing to display
list_view_articles.setVisibility(View.GONE);
txt_nothing.setVisibility(View.VISIBLE);
}
}
}
==> What I need to to call loadPosts(...) in PagerAdapter getItem(), once onCreateView has been called.
Any help is very appreciated.
You should pass your Category as an Extra to the fragment like so:
Bundle bundle = new Bundle();
bundle.putSerializable("CATEGORY", cat);
mCategoriesFragment.setArguments(bundle);
and then in onCreate() in the fragment you can read it using:
Bundle bundle = this.getArguments();
Category cat = (Category) bundle.getSerializable("CATEGORY");
// now you can call loadPosts()

Categories

Resources