-1

How can i send data from activity to default fragment? I have a layout file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.hust.thanhtv.nlp.MainActivity">

    <FrameLayout
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">
        <fragment
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/fragMain"
            class="layout.ListStory">
        </fragment>


    </FrameLayout>

    <android.support.design.widget.BottomNavigationView
        android:id="@+id/navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:background="?android:attr/windowBackground"
        app:menu="@menu/navigation" />

</LinearLayout>

and java file:

private void init(){
    databaseHelper = new DatabaseHelper(this);
    allStories = databaseHelper.getListStory();
    FragmentManager fm = getSupportFragmentManager();
    Fragment  frchapter = ListChapter.newInstance(allStories);
    FragmentTransaction transaction = fm.beginTransaction();
    transaction.replace(R.id.fragMain, frchapter);
    transaction.commit();
}

private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
        = new BottomNavigationView.OnNavigationItemSelectedListener() {

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.navigation_home:
                return true;
            case R.id.navigation_dashboard:
                return true;
            case R.id.navigation_notifications:
                return true;
        }
        return false;
    }

};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
    navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
    init();
}

}

you can see that to send allStories to fragment i have to recreate an new instance of ListChapter by this line of code

Fragment  frchapter = ListChapter.newInstance(allStories);

(old instance has been created when i call

setContentView(R.layout.activity_main);

right?) then i replace this new instace with old instace by this block:

FragmentTransaction transaction = fm.beginTransaction();
transaction.replace(R.id.fragMain, frchapter);
transaction.commit();

i think that is unnecessary to recreate instance of ListChapter to do that work i don't know if there is another way to do that (i mean i want send data directly to old instance and update some element there). Is there a way to do that?

  • [There is already an answer for this question](http://stackoverflow.com/questions/12739909/send-data-from-activity-to-fragment-in-android) – Alexander Palshyn Mar 26 '17 at 20:46
  • what exactly are you asking? you said you know how to send data between fragment with bundle? – Remario Mar 26 '17 at 20:48
  • 1
    Possible duplicate of [Send data from activity to fragment in android](http://stackoverflow.com/questions/12739909/send-data-from-activity-to-fragment-in-android) – X3Btel Mar 26 '17 at 20:54

1 Answers1

0

I would use the Parceble Interface to send data between fragments and activities. I also use shared preferences to link data between such components.You can manipulate LocalBroadcastManager to your liking to broadcast and listen to events.

A great library that effectively and efficiently does the aforementioned, is EventBus.

One of primary issues of these Parceble and bundle approaches is that they can create strong dependencies between each component, making it difficult to change one part of the system without impacting another area.

Publish/subscribe models try to avoid this tight integration by relying on an event bus model. In this type of model, there are publishers and subscribers. Publishers are responsible for posting events in response to some type of state change, while subscribers respond to these events.

The event acts as an intermediary for exchanging information, isolating and minimizing the dependencies between each side. In this way, message buses create a communication pipeline that is intended to help make your app more maintainable and scalable.

Android optimized event bus that simplifies communication between Activities, Fragments, Threads, Services, etc. Less code, better quality. Link.

To clear up your initial question, you want to pass data to fragment without recreating every time(replacing in main layout), You have options ,easiest way is to create a pubic static method that sets a file content,thus giving any class access to provide and access data to fro the Fragment. Or like i said previously you can create a shred preference and treat it as a central data storage pool, to any class requesting access. Or if you actually read about the event bus, you could treat the initiating class as a publisher that sends data( eg. start fragment), then a subscriber(your Fragment) that listens and captures data. This way is much cleaner because there is no strict dependency between any such component.Still not convinced?

Remario
  • 3,813
  • 2
  • 18
  • 25
  • you said you want to send data from a activity to a fragment, am i mistaken? – Remario Mar 26 '17 at 21:33
  • alright, this is what i can extract from your comment, you pass data to default fragment without creating a new instance of the fragment????? – Remario Mar 26 '17 at 22:00