0

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 : enter image description here

for newInstance as I mentioned before I cannot refer to not static .

and I am getting error now for picasso

enter image description here

edit 3 enter image description here

Community
  • 1
  • 1
Moudiz
  • 7,211
  • 22
  • 78
  • 156
  • You are using `putSerializable(String key, Serializable value)`. You need to use `putParcelableArrayList(String, key, ArrayList extends Parcelable> value)`. – Jared Rummler Jan 10 '16 at 14:16
  • @JaredRummler do you have an example for `putParcelableArrayList` so I can apply it in my code ? – Moudiz Jan 10 '16 at 14:22
  • Does your `Listitem` class implement `Parcelable`? If so, it's as simple as `bundle.putParcelableArrayList("your_key", yourList)` – Jared Rummler Jan 10 '16 at 14:26
  • @JaredRummler please check is my fragment class correct in this way , check my edit please – Moudiz Jan 10 '16 at 14:35
  • You need to initialize the ArrayList, put the ArrayList in a bundle and add that bundle to your fragment in `newInstance` – Jared Rummler Jan 10 '16 at 14:39
  • @JaredRummler I got error for personArrayList , please check my edit and can you tell me where I did wrong ? – Moudiz Jan 10 '16 at 14:42
  • It says what you did wrong in the comment. You need to initialize personArrayList. – Jared Rummler Jan 10 '16 at 14:44
  • @JaredRummler one more question please where should I declare mcontext ? if declare above in the fragment , its not reading `with(mcontext).` – Moudiz Jan 10 '16 at 15:27

2 Answers2

2

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;
    }
}
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • Thanks for your help its night over here so ill test it tomorow and ill tell us if it worked – Moudiz Jan 11 '16 at 22:12
  • i have an error can you please check my edit please – Moudiz Jan 12 '16 at 15:54
  • Are you also new to Java? Initialize the ArrayList... `ArrayList personArrayList = new ArrayList();`. **OR** pass it in as a parameter to `newInstance()` as I have shown – OneCricketeer Jan 12 '16 at 15:56
  • Actually, just look at the parameters to `newInstance`. What are they? `(int imageResourceId, int numberSelected)`... There is no `ArrayList` there, right? **That** is your error. – OneCricketeer Jan 12 '16 at 16:03
  • I have initliazed already the personarraylist , its shown in my edit. beside when I removed the static from the fragment I got an error in newInstance `DemoObjectFragment f = DemoObjectFragment.newInstance(personArrayList);` Non static method can be refrenced .. can you help me in them ? – Moudiz Jan 12 '16 at 16:06
  • i have updated my code i did some modiication yesterday – Moudiz Jan 12 '16 at 16:10
  • Here is what you have `public Fragment newInstance(Context context,ArrayList personArrayList)`. **1)** That method is not `static` as it should be. Look at my answer. **2)** You don't need the `Context` parameter, you can just call `getActivity()` from within the Fragment class **3)** You are welcome to have that method return `Fragment`, but it makes more sense for it to return `DemoObjectFragment` as my answer has shown – OneCricketeer Jan 12 '16 at 16:15
  • I did what you said ..I still have 2 errors , please check my update question , I really appreaciate your help, I still need to fix this issue so I can send my project. thanks – Moudiz Jan 12 '16 at 16:59
  • For your first error. Look carefully at number 1 I mentioned above. For the second error, that is definitely [a valid method](http://developer.android.com/reference/android/support/v4/app/Fragment.html) – OneCricketeer Jan 12 '16 at 17:03
  • when i added it like this i get error on static public static DemoObjectFragment newInstance(ArrayList items) and error says inner classes cannot have static declaration .. want screenshot ? – Moudiz Jan 12 '16 at 17:10
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/100504/discussion-between-cricket-007-and-moudiz). – OneCricketeer Jan 12 '16 at 17:20
  • @Moudiz - I'm actually busy today, sorry. I think you got pretty far yesterday and should be able to make a new post with any additional errors/questions you have. – OneCricketeer Jan 13 '16 at 15:53
  • hi man I asked a new question related to the code we where working on it can you check it please https://stackoverflow.com/questions/34799975/a-fragment-is-not-being-accessed-from-from-viewpageradapter – Moudiz Jan 15 '16 at 06:33
0

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

flower_green
  • 1,314
  • 2
  • 25
  • 30
  • I did what jared told me but i am facng another issue , how to declare the context to add it in picasso ? If u check my code above in the part where i add picasso , where should i seclare the context ? In the fragment create view or where – Moudiz Jan 10 '16 at 16:57
  • 1
    You don't need to declare a new context, the hosting activity is a valid context in Android. Just call getActivity() to get one. – flower_green Jan 11 '16 at 13:38
  • @Moudiz - If you error is in reference to the context for Picasso, you can create a question specifically for that, otherwise flower_green is correct here, you simply need to do `getActivity()` to get the `Context` within the `Fragment` – OneCricketeer Jan 11 '16 at 22:09
  • Yes flower green helped here i add getactivity – Moudiz Jan 11 '16 at 22:15