Android折线图

我正在尝试使用Firebase实时数据库中的数据在Android中制作折线图。

这是数据库的结构:

enter image description here

这是代码:

public class TemperaturaActivity extends AppCompatActivity {

    private LineChart Temp_linechart;
    ArrayList<Entry> yData;
    ValueEventListener valueEventListener;
    DatabaseReference mPostReference;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_temperatura);
        Temp_linechart = (LineChart) findViewById(R.id.linechart1);

        mPostReference = FirebaseDatabase.getInstance().getReference("dht");
        mPostReference.addValueEventListener(valueEventListener = new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                yData = new ArrayList<>();
                float i = 0;
                for (DataSnapshot ds : dataSnapshot.getChildren()) {
                    i = i + 1;
                    String SV = ds.child("temp").getValue().toString();
                    Float SensorValue = Float.parseFloat(SV);
                    yData.add(new Entry(i, SensorValue));
                }
                final LineDataSet lineDataSet = new LineDataSet(yData, "Temp");
                lineDataSet.setLineWidth(4);
                LineData lineData = new LineData(lineDataSet);
                Temp_linechart.clear();
                Temp_linechart.setData(lineData);
                //Temp_linechart.notifyDataSetChanged();
                Temp_linechart.invalidate();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    }
}

我在折线图中没有收到任何数据,也不知道为什么。

评论
所以狠在乎
所以狠在乎

To get the values of temp property, please use the following lines of code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference dhtRef = rootRef.child("sensor").child("dht");
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            double temp = ds.child("temp").getValue(Double.class);
            Log.d("TAG", name);
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d("TAG", databaseError.getMessage()); //Don't ignore errors!
    }
};
dhtRef.addListenerForSingleValueEvent(valueEventListener);

The result in the logcat will be the values of temp property:

32.7
32.7
32.7

我对折线图库不熟悉,但是现在有了这些值,您可以使用它们进行任何操作。

P.S. Always add calls to all nodes that are present in your reference, including the one to .child("sensor").

点赞
评论