Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialLukas Baumgartner
14,817 PointsHow to: notifyDatasetChanged();
Hey fellow students!
I have a problem with my app and after 2 hrs of reading stackoverflow i give up.
When the user taps on the floating actionbutton a new listitem in the recyclerview should be displayed. I have it like this so far:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener,
MainFragment.OnListItemSelectedInterface,
MainFragment.OnHorizontalListItemSelectedInterface,
MainFragment.OnListItemLongSelectedInterface {
private static final String MAIN_LIST_FRAGMENT = "main_list_fragment";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
RecyclerViewAdapter adapter = new RecyclerViewAdapter() //<<-- what belongs in the brackets?!
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Exercises.mainList.add("Test");
//adapter.notifyDataSetChanged();
Toast.makeText(MainActivity.this, "The arraylist is " + Exercises.mainList.size() + " long", Toast.LENGTH_SHORT).show();
}
});
MainFragment savedFragment = (MainFragment) getSupportFragmentManager().findFragmentByTag(MAIN_LIST_FRAGMENT);
if (savedFragment == null){
MainFragment fragment = new MainFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.placeholder, fragment, MAIN_LIST_FRAGMENT);
fragmentTransaction.commit();
}
The recyclerview is displayed in the MainFragment fragment and my data is stored in a String ArrayList.
So: How do I get the notifyDataSetChanged(); method working?
1 Answer
Lukas Baumgartner
14,817 PointsSolved it. I moved the onclick method for the fab into the fragment. Now it works fine :)