Jaison Joseph
Jaison Joseph

Reputation: 79

How to access a string value from the fragment to the main activity?

I have an android application in which I used webview fragment. From that fragment, i am going to take the current url by using the below code. But the problem is that I want to access String webUrl from the MainActivity.

How can I get it? What I actually planned to do is creating a favorite url according to the wish of the user from the fragment.

final String webUrl = view.getUrl();

Upvotes: 0

Views: 977

Answers (2)

Divyesh Patel
Divyesh Patel

Reputation: 2576

Create Interface :

public interface HomeListener {

    void onHomeClick(String url);
}

Now in Fragment:

HomeListener mCallback;

 @Override
    public void onAttach(Context con) {
        super.onAttach(con);
        try {
            mCallback = (HomeListener) con;
        } catch (ClassCastException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onDetach() {
        mCallback = null;
        super.onDetach();
    }

Now when url is get:

mCallback.onHomeClick(view.getUrl());

Last in Activity, implement HomeListener, and override method:

@Override
    public void onHomeClick(String url) {

       Log.e("urlFromFragment",url);


}

Sample Activity:

public class MainActivity extends AppCompatActivity
        implements HomeListener {

        String URL="";

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


        }


        @Override
    public void onHomeClick(String url) {

           URL=url;
          Toast.makeText(getApplicationContext(), URL, Toast.LENGTH_LONG).show();
        }

Upvotes: 1

matio
matio

Reputation: 427

From Activity to Fragment: In your fragment, use getActivity() method to access the object of Activity.

YourActivity activity = (YourActivity) getActivity();
activity.someString = "some_url";
webView.setUrl(activity.someString);

From Fragment to Activity:

FragmentManager fm = getSupportFragmentManager();
SampleFragment sampleFragment=(SampleFragment)  fm.findFragmentById(R.id.fragment_id);
activity.someString = "some_url";
webView.setUrl(activity.someString);

Your fragment root view should have the same id:

SampleFragment.xml file

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragment_id" >
<!-- [Your other layout views goes here] -->
</LinearLayout>

Upvotes: 1

Related Questions