First, you'll want to add the dependency for Vico library in your app-level build.gradle:
dependencies {
implementation 'com.androidplot:androidplot-core:1.5.7'
implementation 'com.patrykandpatrick.vico:vico:0.1.4'
}
Next, in your layout XML, add a VicoView component where you want to display the graph:
<com.patrykandpatrick.framework.VicoView
android:id="@+id/vicoView"
android:layout_width="match_parent"
android:layout_height="200dp" />
Now, update your Report data class to store the data as a list of Entry objects:
import com.patrykandpatrick.framework.Entry
data class Report(
val title: String,
val data: List<Entry>
)
Update the ReportRepository to convert the Firestore data into a list of Entry objects:
private fun convertSnapshotToReport(document: QueryDocumentSnapshot): Report {
val title = document.getString("title") ?: ""
val dataMap = document.data as? Map<String, Any> ?: emptyMap()
val dataList = dataMap.map { (key, value) ->
Entry(key.toFloat(), value as Float)
}.sortedBy { it.x }
return Report(title, dataList)
}
fun getReports(timePeriod: TimePeriod, callback: (List<Report>) -> Unit) {
db.collection(timePeriod.toString().toLowerCase()).get()
.addOnSuccessListener { querySnapshot ->
val reports = querySnapshot.map { document ->
convertSnapshotToReport(document)
}
callback(reports)
}
.addOnFailureListener {
callback(emptyList())
}
}
In your activity or fragment, update the observer to load the data into VicoView:
private lateinit var vicoView: VicoView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
vicoView = findViewById(R.id.vicoView)
reportViewModel = ViewModelProvider(this).get(ReportViewModel::class.java)
reportViewModel.reports.observe(this, Observer { reports ->
// Load the first report's data into VicoView (modify this according to your needs)
if (reports.isNotEmpty()) {
showGraphData(reports[0].data)
}
})
// Fetch reports for a specific time period
reportViewModel.fetchReports(TimePeriod.MONTHLY)
}
private fun showGraphData(data: List<Entry>) {
vicoView.lines.removeAll { true } // Remove existing lines from the graph
val line = Line(vicoView.context, data, R.color.colorPrimary) // Create new line with fetched data
vicoView.lines.add(line)
vicoView.invalidate() // Update the graph
}
This will display the data fetched from Firestore into the VicoView using the VICO library. Modify the ReportRepository and the observer accordingly to reflect your specific data structure and requirements.