1

I want to get an ArrayList from one Fragment to another, I use the Intentmethod, like this:

Fragment where I want to get it from

                    Intent intent = new Intent(getActivity(), MainActivity.class);
                intent.putStringArrayListExtra("server_name_list", server_name_list);

If I debug this, I can see the new entry I did. But in the Fragment where I use getIntent().getStringArrayListExtra there is no new entry. What did I wrong?

Here is the code from the Fragment where I use the method:

/* Server Name Spinner */
        ArrayList<String> server_name_list = getIntent().getStringArrayListExtra("server_name_list");

        if (server_name_list != null) {

            spinner = (Spinner) view.findViewById(R.id.server_spinner);
            ;
            ArrayAdapter<String> server_adapter = new ArrayAdapter<String>(this.getActivity(),
                    android.R.layout.simple_spinner_item, server_name_list);

            server_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinner.setAdapter(server_adapter);

            spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

                public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {

                    selected = parent.getItemAtPosition(pos).toString();

                    myWebView.loadUrl(selected);
                }

                public void onNothingSelected(AdapterView<?> parent) {

                }
            });

Edit: Whole code

public class MainActivity extends AppCompatActivity implements AddServerFragment.Callback {

    static WebView myWebView;
    Fragment AddServerFragment, WebViewFragment;
    ArrayList<String> server_name_list;

    @Override
    public ArrayList<String> getArrayListFromActivity() {

        WebViewFragment frag = (WebViewFragment) getSupportFragmentManager().findFragmentByTag("AddServerFragment");
        if (frag != null) {
            server_name_list = frag.getArrayListFromWebViewFragment();
        }
        return server_name_list;
    }

    /* Menu */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.webview:
                getSupportFragmentManager().beginTransaction()
                        .replace(R.id.container, new WebViewFragment() {

                        })
                        .commit();
                return true;
            case R.id.add_server:
                getSupportFragmentManager().beginTransaction()
                        .replace(R.id.container, new AddServerFragment() {

                        })
                        .commit();
                return true;
            case R.id.menu_refresh:
                myWebView.reload();
                return true;
            default:
                return true;
        }
    }

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

        if (findViewById(R.id.container) != null) {
            if (savedInstanceState != null) {
                return;
            }
            AddServerFragment = new Fragment();
            WebViewFragment = new Fragment();
        }
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.container, new WebViewFragment() {

                })
                .commit();
    }

    /*WebView Fragment*/
    public class WebViewFragment extends Fragment {

        String selected;
        Spinner spinner;

        public WebViewFragment(){
        }

        private Callback callback;

        public interface Callback {
            public ArrayList<String> getArrayListFromActivity();
        }

        @Override
        public void onAttach(Activity activity) {
            callback = (Callback) activity;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.webview, container, false);

            /* WebView */
            myWebView = (WebView) view.findViewById(R.id.webView);
            myWebView.setWebViewClient(new WebC());
            WebSettings webSettings = myWebView.getSettings();

            /* JavaScript Enable */
            webSettings.setJavaScriptEnabled(true);

            /* Server Name Spinner */

            ArrayList<String> server_name_list = callback.getArrayListFromActivity();

            if (server_name_list != null) {

                spinner = (Spinner) view.findViewById(R.id.server_spinner);
                ;
                ArrayAdapter<String> server_adapter = new ArrayAdapter<String>(this.getActivity(),
                        android.R.layout.simple_spinner_item, server_name_list);

                server_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                spinner.setAdapter(server_adapter);

                spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

                    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {

                        selected = parent.getItemAtPosition(pos).toString();

                        myWebView.loadUrl(selected);
                    }

                    public void onNothingSelected(AdapterView<?> parent) {

                    }
                });
            }
            return view;
        }
    }

    /*Add Server Fragment*/
    public class AddServerFragment extends Fragment
            implements View.OnClickListener {

        @Override
        public void onClick(View view) {
        }

        public AddServerFragment(){
        }

        Button btn_back, btn_add;
        EditText server_ip, server_name;

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.add_ip, container, false);

            server_ip = (EditText) view.findViewById(R.id.edit_server_address);
            server_name = (EditText) view.findViewById(R.id.edit_server_name);

            btn_back = (Button) view.findViewById(R.id.btn_back);
            btn_back.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View view) {
                    getSupportFragmentManager().beginTransaction()
                            .replace(R.id.container, new WebViewFragment() {

                            })
                            .commit();
                }
            });

            btn_add = (Button) view.findViewById(R.id.btn_add);
            btn_add.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View view) {
                    String new_server_ip = null, new_server_name = null;

                    ArrayList<String> server_name_list = new ArrayList<>();
                    ArrayList<String> server_ip_list = new ArrayList<>();

                    new_server_ip = server_ip.getText().toString();
                    server_ip_list.add(new_server_ip);

                    new_server_name = server_name.getText().toString();
                    server_name_list.add(new_server_name);
                }
            });

            return view;
        }
    }

    /* WebView Client */
    public class WebC extends WebViewClient {

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {

            super.onReceivedError(view, errorCode, description, failingUrl);

        }
    }
}
Sorrow91
  • 69
  • 1
  • 1
  • 13

4 Answers4

2

You can store your ArrayList as a member variable of your container activity :

private ArrayList<String> server_name_list;

Add a getter:

public ArrayList<String> getArrayList() {
    return server_name_list;
}

And in your fragments, you access it this way: (supposing that the container activity's name is MainActivity)

ArrayList<String> arraylist = ((MainActivity)getActivity()).getArrayList();
Mohammed Aouf Zouag
  • 17,042
  • 4
  • 41
  • 67
  • 1
    Not the recommended technique due to [tight coupling](http://stackoverflow.com/questions/22565661/fragment-2-fragment-communicating). An `interface` or `EventBus` is always the better option, even if it takes a bit more boilerplate. – PPartisan Nov 15 '15 at 11:31
  • In deed. Let's just take it easy on the guy. The other way is pretty complicated for him now, I suppose. http://stackoverflow.com/questions/33708631/trying-to-set-text-of-edittext-from-datepicker-dialogfragment/33708667#33708667 – Mohammed Aouf Zouag Nov 15 '15 at 11:34
  • Haha yes, I'm a noob at this, first I only want to get it work. So you say I should try the link in your answere? – Sorrow91 Nov 15 '15 at 11:41
  • You can try both ways. Though I highly recommend you use the one listed here, not in the link. (for the moment) – Mohammed Aouf Zouag Nov 15 '15 at 11:41
  • Ok, I try it to put the right code fragments in my code. If I have problems, I edit my question with the new code I put in – Sorrow91 Nov 15 '15 at 11:43
  • Let me know how it ends – Mohammed Aouf Zouag Nov 15 '15 at 11:44
  • 2 questions: Where do I put `private ArrayList server_name_list;` in? In the `Fragment` where I want to get the new `server_name_list`? The second question is the same with `public ArrayList getArrayList() { return server_name_list; }` – Sorrow91 Nov 15 '15 at 11:47
  • 1
    @JDev Fair enough - I've put up an answer that shows the `interface` technique if @Sorrow91 wants to take a look alongside yours :) – PPartisan Nov 15 '15 at 11:52
2

JDev's answer is correct in so far as it will give you the result you want with the smallest amount of code. It is also, conceptually, the easiest method to understand. However, the technique recommended by Android Developers for a Fragment to communicate with its hosting Activity is via an interface.

It is worth learning this technique IMO, even if you are unfamiliar with interfaces in Java and Android. This is because interfaces are used in all but the most basic of projects, and they underpin many recommended design patterns, so you can be sure they will turn up sooner or later :)

Here is how you would solve your problem with an interface:

public class MyFragment extends Fragment {

    private Callback callback;

    public interface Callback {
        public ArrayList<String> getArrayListFromActivity();
    }

    @Override
    public void onAttach(Activity activity) {
        callback = (Callback) activity; 
        //NB: The above will throw ClassCastException if your Activity
        //Does not implement MyFragment.Callback
    }

    //Later in your code, whenever you want to grab the ArrayList<String> from your Activity:
    ArrayList<String> arrList = callback.getArrayListFromActivity();

Inside MainActivity:

public class MainActivity extends AppCompatActivity implements MyFragment.Callback {

    ArrayList<String> arrayList;

    @Override
    public ArrayList<String> getArrayListFromActivity() {

        //If the ArrayList is in your Activity, then use:
        return arrayList;

        //If the ArrayList is in another Fragment, then use:
        FragmentTwo frag = (FragmentTwo) getSupportFragmentManager().findFragmentByTag("tag_of_fragment_two");
        if (frag != null) {
            arrayList = frag.getArrayListFromFragmentTwo();
            return arrayList;
        }
    }

}
PPartisan
  • 8,173
  • 4
  • 29
  • 48
  • Hey dude, I edit my question, with the edited code. But there is something from and I can't find out what I have to do. Can you take a look if you have time? Tanks :) – Sorrow91 Nov 15 '15 at 18:41
  • 1
    @Sorrow91 Hey Sorrow. It may be worth opening a new question if you're having a problem setting up your interface, simply because it's a separate topic and probably too long to debug via comments. Specify the problem you are having (i.e. you're getting the incorrect data, you're getting an error message), specify what it is you're trying to do, any debugging steps you've tried with and that haven't worked, a link to this answer and add in the code you feel is relevant,along with any `LogCat` output for error messages. Comment in a link when done and I can take a look! – PPartisan Nov 15 '15 at 19:11
  • 1
    Ok thank you, I will open a new question. But maby tomorrow, now I don't have the time. Have a good night dude – Sorrow91 Nov 15 '15 at 19:14
  • [link](http://stackoverflow.com/questions/33725356/passing-an-arraylist-via-interface-between-2-fragments) here is my new question – Sorrow91 Nov 15 '15 at 21:45
0
ArrayList<String> server_name_list;//declare variable

... void onCreate(...)
{
 .
 .
 .
 server_name_list = getIntent().getStringArrayListExtra("server_name_list");//assign value
}

try this.if doesn't work try

intent.putExtra("server_name_list", server_name_list); instead of intent.putStringArrayListExtra("server_name_list", server_name_list);

Burak Karasoy
  • 1,682
  • 2
  • 21
  • 33
  • Thanks for your answere. I put `ArrayList server_name_list;` over my `protected void onCreate(...)` and the `server_name_list = getIntent().getStringArrayListExtra("server_name_list");` before my `if (server_name_list != null)` but it doesnt work. – Sorrow91 Nov 15 '15 at 11:28
  • have you changed putStringArrayExtra(..) to putExtra(..) look my answer i edited it. – Burak Karasoy Nov 15 '15 at 11:33
  • Yes I did, should I do the same with getStringArrayExtra to getExtra? – Sorrow91 Nov 15 '15 at 11:42
-1

you can simply pass any parameter through static instance of that fragment. intent is normally used to transfer data among activities not fragments

 DestinationFragment Frag = DestinationFragment.getInstance(yourArrayList);

 FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            if (shouldAddToBackStack)
                ft.addToBackStack(tag);
            else {
                getSupportFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
            }
            ft.replace(R.id.container, Frag, tag)
                    .commit();
            getSupportFragmentManager().executePendingTransactions();

in your DestinationFragment

public static DestinationFragment getInstance(ArrayList yourArrayList){
        DestinationFragment fragment=new DestinationFragment();
        Bundle args = new Bundle();
        args.putString(args, yourArrayList);
        fragment.setArguments(args);
        return fragment;
    }
Askarc Ali
  • 318
  • 4
  • 21