GraphView не рисует

Ответить
Аватара пользователя
sergentum
Сообщения: 22
Зарегистрирован: 10 апр 2014, 13:13

GraphView не рисует

Сообщение sergentum » 01 июл 2014, 11:38

Привет. Помогите разобраться, пожалуйста, хочу рисовать график с помощью GraphView. График даже строится по тем данным которые добавляются вручную, но те новые, что должны поступать рандомно (а впоследствии с датчиков) не добавлются.
Я думал, может этот участок кода выполняется раз и все, но нет в логах появляется сообщение от строки, которая там рядом.
Пробовал еще выносить ту часть кода где вручную несколько точек задаются, вообще стало null pointer exception.

Что я делаю не так?

[syntax=java]package com.sergentum.myaccel;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.GraphView.GraphViewData;
import com.jjoe64.graphview.GraphViewSeries;
import com.jjoe64.graphview.LineGraphView;

public class MainActivity extends Activity {

TextView tvText;
SensorManager sensorManager;
Sensor sensorAccel;
Sensor sensorLinAccel;
Sensor sensorGravity;

StringBuilder sb = new StringBuilder();
Timer timer;
private final Handler mHandler = new Handler();
private Runnable mTimer1;
private Runnable mTimer2;
private GraphViewSeries exampleSeries1;
private GraphViewSeries exampleSeries2;
private double graph2LastXValue = 5d;

private double getRandom() {
double high = 3;
double low = 0.5;
return Math.random() * (high - low) + low;
}

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tvText = (TextView) findViewById(R.id.tvText);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
sensorAccel = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorLinAccel = sensorManager
.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);
sensorGravity = sensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY);

}

@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(listener, sensorAccel,
SensorManager.SENSOR_DELAY_NORMAL);
sensorManager.registerListener(listener, sensorLinAccel,
SensorManager.SENSOR_DELAY_NORMAL);
sensorManager.registerListener(listener, sensorGravity,
SensorManager.SENSOR_DELAY_NORMAL);

timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
showInfo();
}
});
}
};
timer.schedule(task, 0, 1000);
}

@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(listener);
timer.cancel();
}

String format(float values[]) {
return String.format("%1$.1f\t\t%2$.1f\t\t%3$.1f", values[0], values[1],
values[2]);
}

void showInfo() {

time2 = (int) System.currentTimeMillis();

totAcc = (float) Math.sqrt(Math.abs(Math.pow(valuesAccelMotion[0],2)+Math.pow(valuesAccelMotion[1],2)+Math.pow(valuesAccelMotion[2],2)));
curAcc = Math.round(valuesAccelMotion[0] * 1000) ;
curAcc2 = curAcc /1000;
time = time2 - time1;
totSpd = (float) ((float) totSpd + (curAcc * time * 0.001));
ntotSpd = (float) Math.round(totSpd * 100) / 100;

curDist = (float) Math.round((ntotSpd * (time * 0.001) )*100) /100;
totDist = (float) Math.round((totDist + curDist )*100) /100;


Log.d("myapp", " accel: " + Float.toString(curAcc2) + " smAcc: " + Float.toString(smAcc2));


time1 = time2;


sb.setLength(0);
sb.append("Accelerometer: " + format(valuesAccel))
.append("\n\nAccel motion: " + format(valuesAccelMotion))
.append("\nAccel gravity : " + format(valuesAccelGravity))
.append("\n\nLin accel : " + format(valuesLinAccel))
.append("\nGravity : " + format(valuesGravity))
.append("\n------------------------\n")
.append(Math.abs(curAcc2) + " acceleration\n")
.append(Math.abs(smAcc2) + " smAcc\n")
.append(time + " time, msec\n")
.append(ntotSpd + " total speed, m/sec\n")
.append(curDist + " current distance, m\n")
.append(totDist + " total distance, m\n")
// .append("\nAccel Lin: " + String.format("%1$.2f\t\t", valuesLinAccel[1]))
// .append("\nLast Dist : " + lastDist)
// .append("\nTotal Dist : " + totDist)
;
tvText.setText(sb);

/* GraphViewData newData = new GraphViewData(Math.abs(curAcc2),cycle);
cycle++;

GraphViewSeries AccRaw = new GraphViewSeries(new GraphViewData[] { });
GraphViewSeries AccSm = new GraphViewSeries(new GraphViewData[] { });
GraphView graphView = new LineGraphView(
this // context
, "Acceleration" // heading
);
graphView.addSeries(AccRaw); // data
graphView.setScrollable(true);
graphView.addSeries(AccSm); // data


AccRaw.appendData(newData, false, 10);
//AccSm.appendData(newData, false, 100);
graphView.redrawAll();

LinearLayout layout = (LinearLayout) findViewById(R.id.graph);
layout.addView(graphView);
*/
// draw sin curve

/* int num = 150;
GraphViewData[] data = new GraphViewData[num];
double v=0;
for (int i=0; i<num; i++) {
v += 0.2;
data = new GraphViewData(i, Math.sin(v));
}
GraphView graphView = new LineGraphView(
this
, "GraphViewDemo"
);*/

// add data
//graphView.addSeries(new GraphViewSeries(data));

exampleSeries2 = new GraphViewSeries(new GraphViewData[] {
new GraphViewData(1, 2.0d)
, new GraphViewData(2, 1.5d)
, new GraphViewData(2.5, 3.0d) // another frequency
, new GraphViewData(3, 2.5d)
, new GraphViewData(4, 1.0d)
, new GraphViewData(5, 3.0d)
});
GraphView graphView = new LineGraphView(
this
, "GraphViewDemo"
);
graphView.addSeries(exampleSeries2);
// set view port, start=2, size=40
graphView.setViewPort(2, 10);
graphView.setScrollable(true);
// optional - activate scaling / zooming
graphView.setScalable(true);
graphView.scrollToEnd();
Log.d("myapp", " scroll to end pointer ");
//graphView.addSeries(exampleSeries2); // data

LinearLayout layout = (LinearLayout) findViewById(R.id.graph);
layout.addView(graphView);



mTimer2 = new Runnable() {
@Override
public void run() {
graph2LastXValue += 1d;
exampleSeries2.appendData(new GraphViewData(graph2LastXValue, getRandom()), true, 10);
mHandler.postDelayed(this, 200);
Log.d("myapp", " run " + graph2LastXValue + " " + getRandom());

}

};

mHandler.postDelayed(mTimer2, 1000);


}

float[] valuesAccel = new float[3];
float[] valuesAccelMotion = new float[3];
float[] valuesAccelGravity = new float[3];
float[] valuesLinAccel = new float[3];
float[] valuesGravity = new float[3];
float[] valuesTime = new float[3];

int timeMin;
int timeSec;
int timeMsec;
float curAcc;
float curAcc2;
float smAcc;
float smAcc2;
float totAcc;
float totLin;
float curDist;
float totDist;
float totSpd;
float ntotSpd;
int lastDist;
int time1;
int time2;
int time;
int n = 10;
float[] myArray = new float[n];
int cycle = 0;



SensorEventListener listener = new SensorEventListener() {

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}

@Override
public void onSensorChanged(SensorEvent event) {
float sum = 0;
switch (event.sensor.getType()) {
case Sensor.TYPE_ACCELEROMETER:
for (int i = 0; i < 3; i++) {
valuesAccel = event.values;
valuesAccelGravity = (float) (0.1 * event.values + 0.9 * valuesAccelGravity);
valuesAccelMotion = event.values
- valuesAccelGravity;
}
break;
case Sensor.TYPE_LINEAR_ACCELERATION:
for (int i = 0; i < 3; i++) {
valuesLinAccel = event.values[i];

myArray[0] = valuesLinAccel[i];
for (int j = 1; j < n-1; j++) {
myArray[j] = myArray[j+1];
}
for (int k = 0; k < n; k++){
sum = sum + myArray[k];
}
smAcc = Math.round(sum/n * 1000) ;
smAcc2 = smAcc / 1000;
}
break;
case Sensor.TYPE_GRAVITY:
for (int i = 0; i < 3; i++) {
valuesGravity[i] = event.values[i];


}
break;
}


}

};

}[/syntax]

Аватара пользователя
sergentum
Сообщения: 22
Зарегистрирован: 10 апр 2014, 13:13

Re: GraphView не рисует

Сообщение sergentum » 14 июл 2014, 12:15

магистры, плиз, гляньте

Аватара пользователя
KamiSempai
Сообщения: 1339
Зарегистрирован: 17 фев 2012, 21:23
Откуда: Мордор

Re: GraphView не рисует

Сообщение KamiSempai » 14 июл 2014, 12:24

GraphView не пользовался, но что-то мне подсказывает, после смены данных в массиве нужно как-то GraphView об этом известить, сам он вряд ли об этом догадается.
R.id.team
Хватит таскать макулатуру на тренировку! Используй T Note.

Аватара пользователя
sergentum
Сообщения: 22
Зарегистрирован: 10 апр 2014, 13:13

Re: GraphView не рисует

Сообщение sergentum » 14 июл 2014, 12:39

[syntax=java]package com.jjoe64.graphviewdemos;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.widget.LinearLayout;

import com.jjoe64.graphview.BarGraphView;
import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.GraphView.GraphViewData;
import com.jjoe64.graphview.GraphViewSeries;
import com.jjoe64.graphview.LineGraphView;

public class RealtimeGraph extends Activity {
private final Handler mHandler = new Handler();
private Runnable mTimer1;
private Runnable mTimer2;
private GraphView graphView;
private GraphViewSeries exampleSeries1;
private GraphViewSeries exampleSeries2;
private double graph2LastXValue = 5d;
private GraphViewSeries exampleSeries3;

private double getRandom() {
double high = 3;
double low = 0.5;
return Math.random() * (high - low) + low;
}

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.graphs);

// init example series data
exampleSeries1 = new GraphViewSeries(new GraphViewData[] {
new GraphViewData(1, 2.0d)
, new GraphViewData(2, 1.5d)
, new GraphViewData(2.5, 3.0d) // another frequency
, new GraphViewData(3, 2.5d)
, new GraphViewData(4, 1.0d)
, new GraphViewData(5, 3.0d)
});
exampleSeries3 = new GraphViewSeries(new GraphViewData[] {});
exampleSeries3.getStyle().color = Color.CYAN;

// graph with dynamically genereated horizontal and vertical labels
if (getIntent().getStringExtra("type").equals("bar")) {
graphView = new BarGraphView(
this // context
, "GraphViewDemo" // heading
);
} else {
graphView = new LineGraphView(
this // context
, "GraphViewDemo" // heading
);
}
graphView.addSeries(exampleSeries1); // data
graphView.addSeries(exampleSeries3);

LinearLayout layout = (LinearLayout) findViewById(R.id.graph1);
layout.addView(graphView);

// ----------
exampleSeries2 = new GraphViewSeries(new GraphViewData[] {
new GraphViewData(1, 2.0d)
, new GraphViewData(2, 1.5d)
, new GraphViewData(2.5, 3.0d) // another frequency
, new GraphViewData(3, 2.5d)
, new GraphViewData(4, 1.0d)
, new GraphViewData(5, 3.0d)
});

// graph with custom labels and drawBackground
if (getIntent().getStringExtra("type").equals("bar")) {
graphView = new BarGraphView(
this
, "GraphViewDemo"
);
} else {
graphView = new LineGraphView(
this
, "GraphViewDemo"
);
((LineGraphView) graphView).setDrawBackground(true);
}
graphView.addSeries(exampleSeries2); // data
graphView.setViewPort(1, 8);
graphView.setScalable(true);

layout = (LinearLayout) findViewById(R.id.graph2);
layout.addView(graphView);
}

@Override
protected void onPause() {
mHandler.removeCallbacks(mTimer1);
mHandler.removeCallbacks(mTimer2);
super.onPause();
}

@Override
protected void onResume() {
super.onResume();
mTimer1 = new Runnable() {
@Override
public void run() {
exampleSeries1.resetData(new GraphViewData[] {
new GraphViewData(1, getRandom())
, new GraphViewData(2, getRandom())
, new GraphViewData(2.5, getRandom()) // another frequency
, new GraphViewData(3, getRandom())
, new GraphViewData(4, getRandom())
, new GraphViewData(5, getRandom())
});
exampleSeries3.resetData(new GraphViewData[] {
new GraphViewData(2, getRandom())
, new GraphViewData(2.5, getRandom()) // another frequency
, new GraphViewData(3, getRandom())
, new GraphViewData(4, getRandom())
});
mHandler.postDelayed(this, 300);
}
};
mHandler.postDelayed(mTimer1, 300);

mTimer2 = new Runnable() {
@Override
public void run() {
graph2LastXValue += 1d;
exampleSeries2.appendData(new GraphViewData(graph2LastXValue, getRandom()), true, 10);
mHandler.postDelayed(this, 200);
}
};
mHandler.postDelayed(mTimer2, 1000);
}
}[/syntax]
вот код который у них на гитхабе лежит, я и не вижу никакой команды типа "отобразить" кроме как хэндлер может что то делает.
у меня код не заработал из-за градлей в которых я не разобрался.

Ответить