Search code examples
javaandroidandroid-fragmentsandroid-bundle

Update Fragment UI with data passed from Activity


My Requirement :

My MainActivity receives data from other app. MainActivity is listed as shareable.

Now, I need to pass this data to a fragment in MainActivity and update the fragment's textview.

In MainActivity.java : here I'm handling the received data (which is a URL) in handleSendText method.

    if (Intent.ACTION_SEND.equals(action) && type != null) {
        if ("text/plain".equals(type)) {
            handleSendText(intent); // Handle text being sent
        }
    }
}

In handleSendText, I'm trying to create a bundle and pass that data to my fragment.

void handleSendText(Intent intent) {
    String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
    if (sharedText != null) {
   
        Bundle bundle = new Bundle();
        bundle.putString("url", sharedText);

   // set Fragmentclass Arguments
        AddTab fragobj = new AddTab(); //AddTab() is my Fragment class's name
        fragobj.setArguments(bundle);
    }

In Fragment class : In its onCreateView()

   public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
...
//some code

       Bundle bundle = this.getArguments();

        if(bundle!=null) {
     
            String sharedUrl = getArguments().getString("url");
     
            textBox.setText(sharedUrl);

            inflater.inflate(R.layout.fragment_add, container, false);
            // to update the UI to reflect changes, I'm trying the 
           // above line. Is it right?            
        }

1) The problem is the control is never reaching inside of the if loop, which means bundle is always returning NULL.

2) Moreover, if I don't receive the data from other app. I want to leave my editText empty, so I have to perform this check.How can I make that happen?

3) Moreover, from setArgument's documentation, I learnt that it should be called before the fragment has been attached to its activity. Then how can I reflect the changes in the Fragment's UI?

public void setArguments (Bundle args)

Supply the construction arguments for this fragment. This can only be called before the fragment has been attached to its activity; that is, you should call it immediately after constructing the fragment. The arguments supplied here will be retained across fragment destroy and creation.


Solution

  • Just add a proper method in your fragment, something like this:

    public void receiveURL(String input){
    //to handle what you want to pass to the fragment
    }
    

    And in your mainActivity call you can do something like this:

    YourFragment fragment = (YourFragment)getSupportFragmentManager.findFragmentById(R.id.your_fragment);
    fragment.receive(sharedUrl);