1

I have a fragment which has list of items. I want to access that list from another activity which adds items in list as user enters in edit text and saves the item. this item should get added in the list of fragment. How can I achieve this?? How can I access List created in the fragment from another activity?

Fragment

public class ItemFragment extends Fragment {

    RecyclerView recyclerView;

    IAdapter adapter;
    ArrayList<Expense> items;

    public ItemFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_item_list, container, false);
        setHasOptionsMenu(true);
        Expense e = new Expense();

        recyclerView = (RecyclerView) view.findViewById(R.id.RecyclerView);
        ImageButton imageButton = (ImageButton) view.findViewById(R.id.imgbtn_fab);
        LinearLayoutManager llm = new LinearLayoutManager(this.getActivity());


        items=new ArrayList<>();
        recyclerView.setLayoutManager(llm);

        recyclerView.setHasFixedSize(true);

        initializeDataType1();
        adapter = new IAdapter(getActivity(),items);
        recyclerView.setAdapter(adapter);


        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent(ItemFragment.this.getActivity(), Main2Activity.class);
                startActivity(intent);


            }
        });
        return view;
    }

    private void initializeDataType1() {

        items.add(new Expense("1000", "2000", 1));
        items.add(new Expense("2000", "5000", 1));
        items.add(new Expense("3000", "400", 2));
        items.add(new Expense("1000", "4000", 1));
        items.add(new Expense("3000", "3000", 2));
        items.add(new Expense("2000", "100", 1));
        items.add(new Expense("2000", "3333", 2));
        items.add(new Expense("3000", "shopping", 1));
        items.add(new Expense("1000", "food", 1));
        items.add(new Expense("1000", "food", 2));
        items.add(new Expense("2000", "drink", 1));
        items.add(new Expense("3000", "shopping", 2));
        items.add(new Expense("2000", "3333", 1));
        items.add(new Expense("3000", "shopping", 1));
        items.add(new Expense("1000", "food", 1));
        items.add(new Expense("1000", "food", 1));
        items.add(new Expense("2000", "drink", 1));
        items.add(new Expense("3000", "shopping", 1));
    }
}

Activity

public class Main2Activity extends Activity {

    public Expense ex;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        final EditText amt=(EditText)findViewById(R.id.editText);
       final  EditText exp=(EditText)findViewById(R.id.editText2);
      final  EditText typ=(EditText)findViewById(R.id.typ);


        Button save=(Button)findViewById(R.id.addamt);


        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String amount = amt.getText().toString();
                String expense = exp.getText().toString();
                int type=(Integer.parseInt(typ.getText().toString()));

                Toast.makeText(getApplicationContext(),
                        "Saved",
                        Toast.LENGTH_LONG).show();


            }
        });

    }
}

Please help...

5 Answers5

1

According to official documentation, it is not possible to access Fragments from other Activities:

You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own input events, and which you can add or remove while the activity is running (sort of like a "sub activity" that you can reuse in different activities).

A fragment must always be embedded in an activity and the fragment's lifecycle is directly affected by the host activity's lifecycle. For example, when the activity is paused, so are all fragments in it, and when the activity is destroyed, so are all fragments.

You can however pass the list to the second Activity in the Intent:

Intent intent = new Intent(ItemFragment.this.getActivity(),Main2Activity.class);
intent.putExtra("key", items);
getActivity().startActivity(intent);

Inside your Main2Activity onCreate():

items = (ArrayList<Expense>) getIntent().getSerializableExtra("key");

The key may be chosen arbitrarily. Please bear in mind that you will receive a copy of the list, rather than the actual object.

Community
  • 1
  • 1
localhorst
  • 355
  • 2
  • 11
  • when i passed the list in second activity it shows error on Item fragment that it is not an enclosing class –  Oct 18 '15 at 18:26
1

You can use object of fragment's list as pointer and send this pointer to Main2Activity. And when fragment is visible again just refresh recyclerview. For example start Main2Activity like this :

Intent intent = new Intent(context, Main2Activity.class);
Bundle bundle  = new Bundle();
bundle.putSerializable("list", items);
intent.putExtras(bundle);
context.startActivity(intent);

And in your onCreate() method receive this list pointer and add items. After finishing activity and resuming fragment, just refresh recyclerview.

Sirojiddin Komolov
  • 771
  • 10
  • 17
  • it shows can not resolve symbol for items in bundle.putSerializable("list", items); and how to refresh recycler view? –  Oct 18 '15 at 18:22
  • Where are you calling the **Main2Activity**? – Sirojiddin Komolov Oct 18 '15 at 18:27
  • To refresh recyclerView you can reinitialize your adapter and reset it to recyclerview. – Sirojiddin Komolov Oct 18 '15 at 18:29
  • Main2Activity is called from ItemFragment –  Oct 18 '15 at 18:31
  • **items** is the list that you are working on. If you put above lines of codes into your **ItemFragment** everything should be ok. – Sirojiddin Komolov Oct 18 '15 at 18:36
  • to put list into bundle, your `Expense` class should impliment `Serializable`, so implement `Serializable` for `Expense`. – Sirojiddin Komolov Oct 18 '15 at 18:40
  • and how to access the list object in Main2Activity?? items.add(new Expense(amount, expense, type )); adapter = new IAdapter(this,Main2Activity.items); recyclerView.setAdapter(adapter); Is this right?? –  Oct 18 '15 at 18:44
  • in your onCreate method just write this: `Intent intent = getIntent(); Bundle bundle = intent.getExtras(); ArrayList items = (ArrayList) bundle.get("list");` – Sirojiddin Komolov Oct 18 '15 at 18:46
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/92658/discussion-between-user3623979-and-sirojiddin-komolov). –  Oct 18 '15 at 18:48
0

Pass that list to Activity, make changes, pass back list to fragment and show the new list.

Muhammad Umer
  • 70
  • 1
  • 13
0

Just create a public method on the Fragment which returns this list.

Then get a reference to your fragment and call the method.

ESala
  • 6,878
  • 4
  • 34
  • 55
0

Assuming you don't need the Activity class after you getting the data from user. If that's the case, use startActivityForResult to launch the Activity from the Fragment. When user finishes inputing all of the EditText fields and hit Save then set all data to a bundle and finish() the Activity. Now get the data from onActivityResult of your Fragment and update the list accordingly.

fluffyBatman
  • 6,524
  • 3
  • 24
  • 25