Pedro Gomes
Pedro Gomes

Reputation: 11

Android runOnUiThread

I'm trying to get values through a query for the azure! After that I wanted to try to get these values and move to a new intent but I do not know how to do this because of threads

Here I start QrCode to find an id that I need

@Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.qrcode_activity);

        cameraPreview = findViewById(R.id.cameraPreview);
        txtResult = findViewById(R.id.txtresult);

        barcodeDetector = new BarcodeDetector.Builder(this).
                setBarcodeFormats(Barcode.QR_CODE).build();
        cameraSource = new CameraSource.Builder(getApplicationContext(), barcodeDetector)
                .setRequestedPreviewSize(640, 480).build();
        intent = new Intent(getBaseContext(), ValuesActivity.class);



        barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {
            @Override
            public void release() {

            }

            @Override
            public void receiveDetections(Detector.Detections<Barcode> detections) {
                final SparseArray<Barcode> qrcodes = detections.getDetectedItems();
                if(qrcodes.size() != 0)
                {
                    txtResult.post(new Runnable() {
                        @Override
                        public void run() {
                            //Create vibrate
                            Vibrator vibrator = (Vibrator)getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
                            vibrator.vibrate(100);
                            _idDevice = qrcodes.valueAt(0).displayValue;
                            txtResult.setText(qrcodes.valueAt(0).displayValue);

                            getQuery();

                        }

                    });

                }

            }
        });

        cameraPreview.getHolder().addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    ActivityCompat#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for ActivityCompat#requestPermissions for more details.
                    ActivityCompat.requestPermissions(QrCodeActivity.this, new String[]{Manifest.permission.CAMERA},RequestCameraPermissionID);
                    return;
                }
                try {
                    cameraSource.start(cameraPreview.getHolder());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                cameraSource.stop();
            }
        });



    }

This is where I do the query, however, as I call runUIThread I can not access the variables from that thread for another try. As you can see:

public void getQuery(){

        try
        {
            final ProgressDialog dialog = ProgressDialog.show(QrCodeActivity.this, "", "Loading. Please wait...", true);

            Query query = Query.Companion.select()
                    .from("Equipment")
                    .where("deviceId", "Box2");


            AzureData.queryDocuments("Equipment", "valuesDatabase", query, DictionaryDocument.class,null, onCallback( response  -> {
                Log.e(TAG, "Document list result: " + response.isSuccessful());
                idnomes = new ArrayList<>();
                listaValues = new ArrayList<>();
                listaValuesSensor = new HashMap<>();
                datasAlertas = new ArrayList<>();

                runOnUiThread(() -> {


                    int i = 0;
                    for( Document d : response.getResource().getItems()){
                        if(response.getResource().getItems().get(i).get("deviceId").equals("Box2")) {
                            Object alert = response.getResource().getItems().get(i).get("alert");
                            Object valueSensor = response.getResource().getItems().get(i).get("value");
                            Object datavalor = response.getResource().getItems().get(i).get("data");
                            i++;
                            if(listaValuesSensor.isEmpty()){
                                listaValues.add(Integer.valueOf(valueSensor.toString()));
                                listaValuesSensor.put(alert.toString(),listaValues );
                                datasAlertas.add(datavalor.toString());
                            }else{
                                if(listaValuesSensor.containsKey(alert.toString())){
                                    ArrayList<Integer> o =  listaValuesSensor.get(alert.toString());
                                    o.add(Integer.valueOf(valueSensor.toString()));
                                    listaValuesSensor.put(alert.toString(),o );
                                    datasAlertas.add(datavalor.toString());
                                }else{
                                    listaValues = new ArrayList<>();
                                    listaValues.add(Integer.valueOf(valueSensor.toString()));
                                    listaValuesSensor.put(alert.toString(), listaValues);
                                    datasAlertas.add(datavalor.toString());
                                }
                            }
                            if(!idnomes.contains(alert.toString())) {
                                d.setId(alert.toString());
                                idnomes.add(alert.toString());
                            }
                        }
                        dialog.cancel();
                    }

                });

                Intent i = new Intent(getApplicationContext(),ValuesActivity.class);
                intent.putExtra("id_equipamento", "Box2");
                //intent.putExtra("listaValuesSensor", listaValuesSensor.get(coll.getId()).toString());
                intent.putExtra("listaValuesSensor", listaValuesSensor);
                intent.putExtra("dataValues", datasAlertas);
                startActivity(i);
            }));
        }
        catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

Upvotes: 0

Views: 336

Answers (1)

Rodrigo Bagni
Rodrigo Bagni

Reputation: 96

You didn't pointed out which variables you can't access, so we have to figure it out, but your problem is not that they are in different threads. It seems to be related to the variables' visibility in different scopes. If everything is declared in the same Activity, then you should not have any problems accessing them in the code that you posted, but if they are not in the same class, then you have to change your design.

The only thing I could see is that you are declaring "i" and trying to use "intent":

Intent i = new Intent(getApplicationContext(),ValuesActivity.class);
                intent.putExtra("id_equipamento", "Box2");
                //intent.putExtra("listaValuesSensor", listaValuesSensor.get(coll.getId()).toString());
                intent.putExtra("listaValuesSensor", listaValuesSensor);
                intent.putExtra("dataValues", datasAlertas);

Upvotes: 1

Related Questions