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?