0

I'd like to know if in Android (Java) you can pass a photo using LiveData and a shared ViewModel between two fragments? I have hunted high and low online and can only find references online to something similar in Kotlin. Please excuse the basic question I'm a complete beginner. I have implemented working camera functionality within a fragment, but I would now like to display the resulting image in another fragment.

If this is possible, would I need to put the reference to the ViewModel in the onActivityResult() method in my existing fragment?

I am working with a bitmap so will I need to use Glide? Thanks for any suggestions.

2 Answers2

0

Although this doesn't answer your question directly, if you have found a Kotlin example you want to use, you can decompile the bytecode to view it in Java.

If you are using Android Studio or IntelliJ IDEA,

  1. Open the Kotlin file
  2. From the main menu select Tools -> Kotlin -> Show Kotlin Bytecode
  3. Click Decompile

This is what the option menu should look like

Kotlin and Java are interoperable because they both use the Java Virtual Machine. So they are compiled to the same bytecode.

Jason
  • 1
  • 3
-1

Yes you can use LiveData in java to expose any entity as a Observable Viewholder, which in your case is a photo. I assume you would like to change the bitmap as a reasoning to keeping it a livedata. Sharing the instance between two different Lifecycle owners, in your case are Fragments is possible by keeping the livedata instance in a share ViewModel. Both these lifecycler owners can observe this single viewModel.

You do not need to put reference in onActivityResult() rather make the two fragments get a reference to the shared viewModel through ViewModelProviders.

Karan Dhillon
  • 1,186
  • 1
  • 6
  • 14
  • Thank you very much for your reply. I don't think I need to change the bitmap. Is there a different way to do this with a ViewModel but not using LiveData? I'm happy to get the photo to the other fragment in anyway possible that is efficient because at the moment I don't know how to and I don't know what the best way to do this would be. I am very grateful for suggestions. – Hannah Gill Apr 27 '20 at 16:03
  • refer to this https://stackoverflow.com/questions/44272914/sharing-data-between-fragments-using-new-architecture-component-viewmodel – Karan Dhillon Apr 27 '20 at 16:05
  • Thank you, I'll look at that. – Hannah Gill Apr 27 '20 at 16:17