In the MainActivity there is a variable grad . Its value must be obtained in MyDraw . Below is the code. What's wrong? Variable value in MyDraw is always 0.0

  public class MainActivity extends AppCompatActivity { TextView tvListSen, tvTemp, tvHyd, tvOrient; Button btnListSen, btnTestSen; SensorManager sensorManager; List<Sensor> sensors; Sensor sensorLight, sensorTemp, sensorHyd, sensorAccel, sensorMagnet; StringBuilder sb = new StringBuilder(); Timer timer; int rotation; SensorEventListener listenerLight = new SensorEventListener() { @Override public void onSensorChanged(SensorEvent event) { //tvListSen.setText(String.valueOf(event.values[0])); } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } }; SensorEventListener listenerTemp = new SensorEventListener() { @Override public void onSensorChanged(SensorEvent event) { float fl = event.values[0]; tvTemp.setText("Температура: "+ String.format("%.1f", fl)+"°C"); } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } }; SensorEventListener listenerHyd = new SensorEventListener() { @Override public void onSensorChanged(SensorEvent event) { float fl = event.values[0]; tvHyd.setText("Влажность: "+String.format("%.1f", fl)+"%"); } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } }; float[] valaccel = new float[3]; float[] valmagnet = new float[3]; float[] valresult = new float[3]; float[] valresult2 = new float[3]; private float grad; public float GetGrad(){ return this.grad; } SensorEventListener listenerAccel = new SensorEventListener() { @Override public void onSensorChanged(SensorEvent event) { for (int i=0; i<3; i++){ valaccel[i]=event.values[i]; } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } }; SensorEventListener listenerMagnet = new SensorEventListener() { @Override public void onSensorChanged(SensorEvent event) { for (int i=0; i<3; i++){ valmagnet[i]=event.values[i]; } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } }; float[] r = new float[9]; void GetDeviceOrientation (){ sensorManager.getRotationMatrix(r,null, valaccel, valmagnet); sensorManager.getOrientation(r, valresult); valresult[0] = (float) Math.toDegrees(valresult[0]); valresult[1] = (float) Math.toDegrees(valresult[1]); valresult[2] = (float) Math.toDegrees(valresult[2]); return; } float[] Rin =new float[9]; float[] Rout=new float[9]; void GetActDevOrientation(){ sensorManager.getRotationMatrix(Rin, null, valaccel, valmagnet); int X_axis = SensorManager.AXIS_X; int Y_axis = SensorManager.AXIS_Y; switch (rotation){ case (Surface.ROTATION_0): break; case (Surface.ROTATION_90): X_axis = SensorManager.AXIS_Y; Y_axis = SensorManager.AXIS_MINUS_X; break; case (Surface.ROTATION_180): Y_axis = SensorManager.AXIS_MINUS_Y; break; case (Surface.ROTATION_270): X_axis = SensorManager.AXIS_MINUS_Y; Y_axis = SensorManager.AXIS_X; break; default:break; } sensorManager.remapCoordinateSystem(Rin, X_axis, Y_axis, Rout); sensorManager.getOrientation(Rout, valresult2); valresult2[0] = (float) Math.toDegrees(valresult2[0]); valresult2[1] = (float) Math.toDegrees(valresult2[1]); valresult2[2] = (float) Math.toDegrees(valresult2[2]); return; } 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(){ sb.setLength(0); sb .append("Orientation: "+ format(valresult)) .append("\nOrientation2: "+ format(valresult2)); tvOrient.setText(String.format("%.1f", valresult[0])); grad = valresult[0]; } void GraphMod(){ } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //tvListSen = (TextView) findViewById(R.id.tvListSen); tvTemp = (TextView) findViewById(R.id.tvTemp); tvHyd = (TextView) findViewById(R.id.tvHyd); tvOrient = (TextView) findViewById(R.id.tvOrient); sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); sensors = sensorManager.getSensorList(Sensor.TYPE_ALL); sensorLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT); sensorTemp = sensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE); sensorHyd = sensorManager.getDefaultSensor(Sensor.TYPE_RELATIVE_HUMIDITY); sensorAccel = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); sensorMagnet= sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } @Override protected void onResume() { super.onResume(); sensorManager.registerListener(listenerMagnet, sensorMagnet, SensorManager.SENSOR_DELAY_NORMAL); sensorManager.registerListener(listenerAccel, sensorAccel, SensorManager.SENSOR_DELAY_NORMAL); timer = new Timer(); TimerTask task = new TimerTask() { @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { //сюда поместить действия__________ GetDeviceOrientation(); GetActDevOrientation(); ShowInfo(); GraphMod(); } }); } }; timer.schedule(task, 0, 400); WindowManager windowManager = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)); Display display = windowManager.getDefaultDisplay(); rotation = display.getRotation(); //tvHyd.setText(deg); } public void OnClickbtnListSens(View v) { sensorManager.unregisterListener(listenerLight, sensorLight); sensorManager.unregisterListener(listenerTemp, sensorTemp); sensorManager.unregisterListener(listenerHyd, sensorHyd); StringBuilder sb = new StringBuilder(); for (Sensor sensor: sensors){ sb.append("Name: ").append(sensor.getName()) .append("\nType: ").append(sensor.getType()) .append("\nVendor: ").append(sensor.getVendor()) .append("\nResolution: ").append(sensor.getResolution()) .append("\nMaxRange: ").append(sensor.getMaximumRange()) .append("\n ======== \n"); } //tvListSen.setText(sb); } public void OnClickbtnTestSen(View v){ sensorManager.registerListener(listenerLight, sensorLight, SensorManager.SENSOR_DELAY_NORMAL); sensorManager.registerListener(listenerTemp, sensorTemp, SensorManager.SENSOR_DELAY_NORMAL); sensorManager.registerListener(listenerHyd, sensorHyd, SensorManager.SENSOR_DELAY_NORMAL); } @Override protected void onPause() { super.onPause(); sensorManager.unregisterListener(listenerLight, sensorLight); sensorManager.unregisterListener(listenerTemp, sensorTemp); sensorManager.unregisterListener(listenerHyd, sensorHyd); sensorManager.unregisterListener(listenerAccel, sensorAccel); sensorManager.unregisterListener(listenerMagnet, sensorMagnet); timer.cancel(); } } 

MyDraw code :

 public class MyDraw extends View { Paint p; //float deg; int Width, Heidht, x, y; //int[] x = new int[360]; //int[] y = new int[360]; Timer timer = new Timer(); Path path, path1; Matrix matrix; MainActivity mAct = new MainActivity(); public MyDraw(Context context) { this(context, null); } public MyDraw(Context context, AttributeSet attrs) { super(context, attrs); p = new Paint(); path = new Path(); matrix = new Matrix(); } @Override protected void onDraw(Canvas canvas) { float deg = mAct.GetGrad(); canvas.drawColor(Color.GREEN); Width = canvas.getWidth(); Heidht = canvas.getHeight(); //синий конец стрелки path.reset(); path.moveTo((Width/2-50), (Heidht/2)); path.lineTo((Width/2), (Heidht/2-250)); path.lineTo((Width/2+50), (Heidht/2)); path.close(); p.setStrokeWidth(2); p.setColor(Color.BLUE); matrix.reset(); matrix.setRotate(deg, Width/2, Heidht/2); path.transform(matrix); canvas.drawPath(path, p); //красный конец стрелки path.reset(); path.moveTo(Width/2-50, Heidht/2); path.lineTo(Width/2, Heidht/2+250); path.lineTo(Width/2+50, Heidht/2); path.close(); p.setStrokeWidth(2); p.setColor(Color.RED); path.transform(matrix); canvas.drawPath(path, p); p.setTextSize(70); p.setColor(Color.BLUE); // рисуем текст в точке (150,500) canvas.drawText(String.valueOf(deg), 10, 70, p); invalidate(); } } 

Lord. Help with advice and example, if not difficult. I'm still new to this business.

  • 3
    There are general conventions by which method names should begin with a small letter. Capital letters are the names of classes. - rjhdby

2 answers 2

The problem is that in the MyDraw class MyDraw create a new MainActivity object, which has nothing to do with the activit that is displayed on the screen and the value you want to get, so the GetGrad method returns the value of the default variable that was created when the object was created. One way to solve the problem is to add the setGrad method to the setGrad class and set the value from outside through it.

  • In the MainActivity, sensors are polled and the value of the variable grad is assigned. In MyDraw, I don’t even know the values ​​from these sensors. At the same time, both classes are one screen (one activation). The idea is to get and process the readings from the sensors in MainActivity, and draw something in MyDraw based on the readings. - Konstantin
  • one
    @Konstantin You in MyDrawe have created a new MainActivity object. Despite the fact that they have the same type, these are 2 different objects that have their own values ​​for the variable grad . Because in the MyDraw object MyDraw variable does not change, respectively, and returns 0. I see a way out only in passing values ​​from outside, or using something like EventBus, but it seems to me that this is not the best option - temq
  • Yes thank you. I caught up. - Konstantin

You fill the variable grad only in the ShowInfo method. Here you have it and initialized with the default value.

Here is your code:

 void ShowInfo(){ sb.setLength(0); sb .append("Orientation: "+ format(valresult)) .append("\nOrientation2: "+ format(valresult2)); tvOrient.setText(String.format("%.1f", valresult[0])); grad = valresult[0]; // Вы присваиваете новое значение переменной grad, но если valresult[0] == 0.0, то значение не изменится } 

That is, until you call the ShowInfo method, you will still have a default value of 0.0 . Well, either change the value in another place.

  • Cited the full code 'MainActivity'. 'ShowInfo' is called, 'valresult [0]' has a specific value. not equal to 0 - Konstantin
  • @Konstantin, that is, in the line grad = valresult[0]; Is a specific value assigned? And you debugged and confident in this? - Denis Bubnov
  • in the variable valresult [0] the number <> 0. That's for sure. This number is displayed in tvOrient (text on the screen). hence the variable grad contains the same number. I think so. - Konstantin
  • @Konstantin and you do not guess, and run in debugger mode and check - rjhdby
  • one
    @Konstantin, Put a breakpoint and make sure that there does not come 0. Try calling the ShowInfo method first and then GetGrad and put the resulting value into a temporary variable and see what returned the second method to you, after GetGrad exactly the first not null value. And then we will not guess, but we will know. - Denis Bubnov