3

I have a problem with my MVVM structure. I create apps and pass data between fragments. Now it works fine, but I need to add this logic to my ViewModel.

This is my NotesClickFragment:

@AndroidEntryPoint
class NotesClickFragment : Fragment(R.layout.fragment_click_notes) {

    private val args by navArgs<NotesClickFragmentArgs>()

    private val viewModel: NotesClickViewModel by viewModels()
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val binding = FragmentClickNotesBinding.bind(view)


        binding.apply {
            textViewTitleClick.setText(args.notesClickArgs.titleNotes)
            textViewContentNotesClick.setText(args.notesClickArgs.contentNotes)
            textViewHistoryClick.setText(args.notesClickArgs.createdNotesDateFormat)
        }
    }
}

This is my NotesClickViewModel:

class NotesClickViewModel @ViewModelInject constructor(
            private val notesDao: NotesDao
    
    ) : ViewModel() {
    
 }

I'm trying to add a private argument val navArgs: NotesClickFragmentArgs and create the other functions to set data from fragments but it doesn't work. What is good practice? Thanks in advance for your tips.

OctaveL
  • 1,017
  • 8
  • 18
siwus1230
  • 31
  • 2

1 Answers1

0
  1. NotesDao has no place in ViewModel and instead should be inside Repository.

    For more information on MVVM, please read the following: Guide to app architecture

  2. As far as I know, ViewModel cannot be used here. Navigation should be handled inside Fragment itself. In order to use SafeArgs you first need to declare parameters inside NavGraph and then you can use Directions to navigate to a fragment where you can pass your necessary data.

For example. Let's say I have list of movies in RecyclerView. When I click on any of the movies I want to see id of the movie I clicked in a new fragment.

  • Step 1: Declare information in NavGraph

This is how Fragment is declared in my NavGraph. The tag argument means that this Fragment accepts Int(id).

<fragment
 android:id="@+id/movieDetailsFragment" 
 android:name="my.test.MovieDetailsFragment"
 android:label="fragment_movie_details"
 tools:layout="@layout/fragment_movie_details">
 <argument
  android:name="id"
  app:argType="integer" />
</fragment>

Then, in any other Fragment connected to MovieDetailsFragment I simply use Directions and pass id that I need.

val direction = MoviesPopularFragmentDirections.actionPopularFragmentToMovieDetailsFragment(id = movie.id)
this.findNavController().navigate(direction)

And that should be it.

Again, more information in official documentation here Navigation Safe Args

Vitaliy-T
  • 733
  • 6
  • 23