0

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();
        }
    }
}
Shubham Agrawal
  • 1,252
  • 12
  • 29

1 Answers1

1

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);
  • Hi @Rodrigo, You were right, I had to use i, but even then I still have problems I am trying to do a query to azure and the result of this query move to another activity, but the problem is that I need the query to execute first and it is not happening. When I try to call the query it runs in runUIThread only after running onCreate and creating an activity in the getQuery method is not working – Pedro Gomes Feb 27 '19 at 11:20
  • The first thing you should notice is that txtResult.post() will have the Runnable running on the UI thread because txtResult is a view of the Activity. If you run getQuery() in the Runnable, then you already are in the UI thread.
    Second thing, if I understand correctly your use case, you are trying to access a server in the internet on the UI thread, which you definitely shouldn't do because you end up receiving an ANR error.
    – Rodrigo Bagni Feb 27 '19 at 14:19
  • I still don't know which variable you can't access. As I said, you need to make sure variables are accessible from where you want to. If they are private or declared inside a method, you will no be able to access them according the scope limitation. Please, point out exactly which variable you can't access. Thanks – Rodrigo Bagni Feb 27 '19 at 14:25