Giac
Giac

Reputation: 21

How can I pass a ArrayList<String> created in a fragment to the main activity

I have a drawer menu with 3 items (Restaurant, Movie, Food). They are basically 3 to do lists. Each list has its on fragment and in the view there is a way to add items to the list. The restaurant list, the movie list ad the groceries list. I need to be able to share that list (via any share-channel) by clicking the share icon that is in the toolbar. This is my fragment where i populate the items list that i want to use when i click the share icon that is on the toolbar. Basically i need to pass "items" to the MainActivity and use it.

package com.example.mylists;

import android.content.Intent;

public class FoodFragment extends Fragment  {
public FoodFragment() {
    // Required empty public constructor
}
private ArrayList<String> items;
private ArrayAdapter<String> itemsAdapter;
private ListView lvItems;
private static final String TAG = "FoodFragment";
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    Log.i(TAG, "in on onCreateView ");
    View view = inflater.inflate(R.layout.fragment_food, container, false);
    lvItems = (ListView) view.findViewById(R.id.lvItems);
    items = new ArrayList<String>();
    readItems();
    itemsAdapter = new ArrayAdapter<String>(view.getContext(),android.R.layout.simple_list_item_1, items);
    lvItems.setAdapter(itemsAdapter);
    if (items.isEmpty())
        items.add("Dummy Item");
    final EditText newTask    = (EditText) view.findViewById(R.id.etNewItem);
    Button btnAdd = (Button) view.findViewById(R.id.btnAddItem);

    btnAdd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String itemText = newTask.getText().toString();
            itemsAdapter.add(itemText);
            newTask.setText("");
            writeItems();
            Log.i(TAG, "in on send data ");
        }
    });
    return view;
}

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    Log.i(TAG, "in on onViewCreated ");

    super.onViewCreated(view, savedInstanceState);
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    Log.i(TAG, "in on onActivityCreated ");

    super.onActivityCreated(savedInstanceState);

    OnItemLongClickListener listener = new OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int position, long id) {
            //Log.i(TAG, "in on onItemLongClick ");
            //Toast.makeText( getActivity().getBaseContext()  , "Long Clicked " , Toast.LENGTH_SHORT).show();
            items.remove(position);
            itemsAdapter.notifyDataSetChanged();
            writeItems();
            //return true;
            return false;
        }
    };
    lvItems.setOnItemLongClickListener(listener);
}

private void readItems() {
    File filesDir = getContext().getFilesDir();
    File todoFile = new File(filesDir, "todo.txt");
    try {
        items = new ArrayList<String>(FileUtils.readLines(todoFile));
    } catch (IOException e) {
        items = new ArrayList<String>();
    }
}

private void writeItems() {
    File filesDir = getContext().getFilesDir();
    File todoFile = new File(filesDir, "todo.txt");
    try {
        FileUtils.writeLines(todoFile, items);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
}

Upvotes: 1

Views: 96

Answers (3)

Victor Cold
Victor Cold

Reputation: 653

Interface for Callback

interface MyInterface {
    void setItems(ArrayList<String> items);
}

In your activity:

class MyActivity {
    ArrayList<String> items;

    MyInterface itemsCallback = new MyInterface(){
        @Override
        void setItems(ArrayList<String> items){
            this.items = items;
        }
    }

    myFragment.setItemsCallback(itemsCallback);
}

And then in fragment

class MyFragment {
    private MyInterface itemsCallback;
    public void setItemsCallback(MyInterface itemsCallback){
        this.itemsCallback = itemsCallback;
    }

    private void readItems(){
        ...
        itemsCallback.setItems(items); 
    }
}

I guess it's better then public setter in MainActivity. Because, you know, it's like more SOLID code. In this case your Fragment doesnt hold reference to Activity and doesnt even know about it existence.

Upvotes: 1

Beyazid
Beyazid

Reputation: 1835

You should declare ArrayList<String> items in your MainActivity. Then create a public setter method for items.

public void setItems(ArrayList<String> items){
   this.items = items;
}

Then you should call setItems() method in your fragment.

((MainActivity) getActivity()).setItems(items);

Upvotes: 1

zht2005
zht2005

Reputation: 46

1.Define an interface , 2.Let your Activity implements the interface 3.use (interface)getActivity() to cast your Activity to that interface,then you can call the method in the interface to send your ArrayList "items"

Upvotes: 0

Related Questions