简体   繁体   中英

how to access list of fragment from another activity?

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

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.

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.

将该列表传递给Activity,进行更改,将列表传递回片段并显示新列表。

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM