Reputation: 1
it is my first time doing an android app and i have problem with the affiche the notes list , and that happen when i tried to add fragment , this is the part of connecting the MainActivity with the fragment : protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
notesContainer = findViewById(R.id.notesContainer);
noteList = new ArrayList<>();
// Find the Button with ID myButton
Button addButton = findViewById(R.id.myButton);
// Set up a click listener for the "Add Note" button
addButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Replace the current fragment with AddNoteFragment
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragmentContainer, new AddNoteFragment())
.addToBackStack(null) // Optional: Add transaction to back stack
.commit();
}
});
LoadNotesFromPreferences();
displayNote();
}
i need to solve the problem that the note list doent affiche , because when i try to do it without the fragment every thing was working good
Upvotes: 0
Views: 30
Reputation: 634
As I can see and assume that you are creating a new instance of your fragment every time you click on add button. instead you should declare an global variable and use it inside the add button scope so that unnecessary creation of new instance of the fragment is avoided.
For eg.
noteList = new ArrayList<>();
AddNoteFragment fragment = new AddNoteFragment();
// Find the Button with ID myButton
Button addButton = findViewById(R.id.myButton);
// Set up a click listener for the "Add Note" button
addButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Replace the current fragment with AddNoteFragment
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragmentContainer,fragment)// use variable so that it will use the same instance of fragment created above.
.addToBackStack(null)
.commit();
}
});
LoadNotesFromPreferences();
displayNote();
}
Let me know if this helps.
Upvotes: 0