在Android Studio中,可以使用Firebase实时数据库创建图表。可以按照以下步骤进行操作:
以下是一个示例代码:
// build.gradle(app) dependencies { implementation 'com.google.firebase:firebase-database:16.0.1' implementation 'com.github.PhilJay:MPAndroidChart:v3.0.3' }
// build.gradle(project) dependencies { classpath 'com.google.gms:google-services:4.3.4' }
// MainActivity public class MainActivity extends AppCompatActivity {
private LineChart mChart;
private DatabaseReference mDatabase;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mChart = findViewById(R.id.lineChart);
mChart.setTouchEnabled(true);
mChart.setDragEnabled(true);
mChart.setScaleEnabled(true);
mDatabase = FirebaseDatabase.getInstance().getReference().child("data");
mDatabase.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
ArrayList entries = new ArrayList<>();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
float value = snapshot.getValue(Float.class);
entries.add(new Entry(entries.size(), value));
}
LineDataSet dataSet = new LineDataSet(entries, "Data");
dataSet.setColor(Color.RED);
dataSet.setLineWidth(2f);
dataSet.setValueTextSize(10f);
LineData lineData = new LineData(dataSet);
mChart.setData(lineData);
mChart.invalidate();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.d(TAG, "Database Error: " + databaseError.getMessage());
}
});
}
}
// activity_main.xml