-3

I have a view as following hierarchy.

enter image description here

The main Activity has

ArraylistArrayListArraylist()

I want to access and change the data of the Arraylist from the button of the Card view. I'm using Custom ArrayAdapter. So is there are any way to do this?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
  • Possible duplicate of [Passing data between a fragment and its container activity](https://stackoverflow.com/questions/9343241/passing-data-between-a-fragment-and-its-container-activity) – Santanu Sur May 11 '18 at 09:39
  • it was for accessing data from fragment. I have another level. I have Grid Layout with custom Array Adapter in fragment. – Madawa De Silva May 11 '18 at 09:42
  • pass the `arraylist` to the fragment from activity ..then pass the `arraylist` to the `arrayadapter` same thing indirectly.. – Santanu Sur May 11 '18 at 09:43
  • Make your arraylist as global variable with public access. So in which ever fragment you need this variable you can access it through the activity context. – hasan_shaikh May 11 '18 at 09:43
  • you can use getActivity() to access MainActivity rference from fragments – darwin May 11 '18 at 09:44
  • by doing that will it be able to change Arraylist data in the Activity ? – Madawa De Silva May 11 '18 at 09:46

1 Answers1

0

You just need to pass your list data from activity to your custom adapter by calling adapter's constructor. See below how you can pass list data and that from adapter.

public TestAdapter extends ArrayAdapter<String>{
private Context mContext;
    private List<String> list = new ArrayList<>();

    public MovieAdapter(@NonNull Context context, @LayoutRes ArrayList<String> list) {
        super(context, 0 , list);
        this.mContext = context;
        this.list = list;
    }

.............//use "list" in your adapter

}

In activity you have below list.

 Arraylist a = new Arraylist();
a.add("test");
a.add("test1");
a.add("test2");
a.add("test3");
TestAdapter testadapter=new TestAdapter(this,a);

Now you have that list in adapter and you can use list in your adapter.

Koushik Mondal
  • 865
  • 7
  • 15